<template>
  <div class="carousel-management">
    <div class="table-actions">
      <a-button type="primary" @click="showAddModal">新增</a-button>
    </div>

    <a-table :columns="columns" :data-source="data" :rowKey="record => record.id">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'img'">
      <template v-if="record.img.endsWith('.mp4')">
        <video
          :src="record.img"
          :width="50"
          :height="50"
          style="margin-right: 5px;"
          controls
        />
      </template>
      <template v-else>
        <a-image
          :src="record.img"
          :width="50"
          :height="50"
          style="margin-right: 5px;"
        />
      </template>
    </template>
        <template v-if="column.key === 'status'">
          <a-tag :color="record.status === 1 ? 'green' : 'red'">
            {{ record.status === 1 ? '启用' : '不启用' }}
          </a-tag>
        </template>
        <template v-if="column.key === 'action'">
          <a-space>
            <a-button type="link" @click="editItem(record)">编辑</a-button>
            <a-button type="link" @click="deleteItem(record)">删除</a-button>
          </a-space>
        </template>
      </template>
    </a-table>

    <a-modal
      v-model:visible="modalVisible"
      :title="modalMode === 'add' ? '新增中奖图' : '编辑中奖图'"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      width="800px"
    >
      <a-form :model="formState" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
        <a-form-item label="标题" name="title" :rules="[{ required: true, message: '请输入标题' }]">
          <a-input v-model:value="formState.title" />
        </a-form-item>
        <a-form-item label="图片" name="img" :rules="[{ required: true, message: '请上传图片' }]">
          <a-upload
            v-model:fileList="formState.images"
            list-type="picture-card"
            :max-count="1"
            @preview="handlePreview"
            @change="handleImageChange"
            :customRequest="customRequest"
          >
            <div v-if="formState.images.length < 1">
              <plus-outlined />
              <div style="margin-top: 8px">上传图片</div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item label="状态" name="status">
          <a-switch v-model:checked="formState.status" :checked-value="1" :unchecked-value="0" />
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal v-model:visible="previewVisible" :title="previewTitle" :footer="null">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import { getCarouselListApi, saveCarouselApi, deleteCarouselApi, updateCarouselApi, uploadImageApi } from "../../api/carouselConfig";

const modalVisible = ref(false);
const modalMode = ref('add');
const previewVisible = ref(false);
const previewImage = ref('');
const previewTitle = ref('');

const columns = [
  { title: '标题', dataIndex: 'title', key: 'title' },
  { title: '图片', dataIndex: 'img', key: 'img' },
  { title: '状态', dataIndex: 'status', key: 'status' },
  { title: '操作', key: 'action' },
];

const data = reactive([]);

const formState = reactive({
  id: null,
  title: '',
  images: [],
  img: '',
  status: 1,
});

const showAddModal = () => {
  modalMode.value = 'add';
  Object.assign(formState, { id: null, title: '', images: [], img: '', status: 1 });
  modalVisible.value = true;
};

const editItem = (record) => {
  modalMode.value = 'edit';
  Object.assign(formState, {
    id: record.id,
    title: record.title,
    images: [{
      uid: -1,
      name: 'image.jpg',
      status: 'done',
      url:  record.img,
    }],
    img: record.img,
    status: record.status,
  });
  modalVisible.value = true;
};

const deleteItem = async (record) => {
  try {
    await deleteCarouselApi(record.id);
    message.success('删除成功');
    fetchData();
  } catch (error) {
    message.error('删除失败');
  }
};

const handleModalOk = async () => {

  console.log(formState);

  try {
    const data = { 
      title: formState.title,
      img:  processImagePath(formState.img),
      status: formState.status
    };
    if (modalMode.value === 'add') {

      console.log(data);


      await saveCarouselApi(data);
    } else {
      await updateCarouselApi({ ...data, recordId: formState.id });
    }
    message.success(modalMode.value === 'add' ? '添加成功' : '编辑成功');
    modalVisible.value = false;
    fetchData();
  } catch (error) {
    message.error(modalMode.value === 'add' ? '添加失败' : '编辑失败');
  }
};

const processImagePath = (imgPath) => {
  const urlPrefix = 'http://123.249.121.26:8801/images/';
  if (imgPath.startsWith(urlPrefix)) {
    return imgPath.substring(urlPrefix.length);
  }
  return imgPath;
};

const handleModalCancel = () => {
  modalVisible.value = false;
};

const handlePreview = async (file) => {
  if (!file.url && !file.preview) {
    file.preview = await getBase64(file.originFileObj);
  }
  previewImage.value = file.url || file.preview;
  previewVisible.value = true;
  previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
};

const customRequest = async ({ file, onSuccess, onError }) => {
  try {
    const response = await uploadImageApi(file);
    formState.img = response.data.url;
    onSuccess(response, file);
  } catch (error) {
    onError(error);
  }
};

const handleImageChange = ({ fileList }) => {
  formState.images = fileList;
  if (fileList.length > 0) {
    const lastFile = fileList[fileList.length - 1];
    formState.img = lastFile.response ? lastFile.response.data : lastFile.url;
  }
};

const getBase64 = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
};

const fetchData = async () => {
  try {
    const response = await getCarouselListApi(1);
    // data.splice(0, data.length, ...response.data.records);
    const records = response.data.records.map(record => {
      if (record.img) {
        record.img = 'http://123.249.121.26:8801/images/' + record.img;
      }
      return record;
    });
    data.splice(0, data.length, ...records);
  } catch (error) {
    message.error('获取数据失败');
  }
};

onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.carousel-management {
  padding: 24px;
}
.table-actions {
  margin-bottom: 16px;
  text-align: right;
}
</style>

