<template>
  <div class="content-management">
    <a-tabs v-model:activeKey="activeTab" @change="tabChange">
      <a-tab-pane key="recommendations" tab="今日推荐"></a-tab-pane>
      <a-tab-pane key="stores" tab="门店"></a-tab-pane>
      <a-tab-pane key="events" tab="赛事分析"></a-tab-pane>
      <template #rightExtra>
        <a-button type="primary" @click="showAddModal">新增</a-button>
      </template>
    </a-tabs>

    <a-table :columns="columns" :data-source="filteredData" :rowKey="record => record.id">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'content'">
          <div v-if="record.classify === 1">
            <a-image
              :src="record.img"
              :width="50"
              :height="50"
              style="margin-right: 5px;"
            />
          </div>
          <span v-else v-text="record.content1"></span>
        </template>
        <template v-if="column.key === 'status'">
          <a-tag :color="record.status === 1 ? 'green' : 'orange'">
            {{ 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)" v-if="activeTab != 'recommendations'">删除</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="类型">
          <a-select v-model:value="formState.classify" :disabled="modalMode === 'edit'">
            <a-select-option :value="1">今日推荐</a-select-option>
            <a-select-option :value="0">门店</a-select-option>
            <a-select-option :value="2">赛事分析</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="标题">
          <a-input v-model:value="formState.title" placeholder="输入标题"/>
        </a-form-item>
        <a-form-item label="主图">
          <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="内容" v-if="formState.classify !== 1">
          <wysiwyg-editor v-model="formState.content" @image-upload="handleEditorImageUpload" />
        </a-form-item>
        <a-form-item label="状态">
          <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, computed, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import WysiwygEditor from './WysiwygEditor.vue';
import { saveContentApi, updateContentApi, getContentListApi, deleteContentApi, uploadImageApi } from "../../api/contentConfig";

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

const columns = [
  { title: '类型', dataIndex: 'classify', key: 'classify' },
  { title: '标题', dataIndex: 'title', key: 'title' },
  { title: '内容', dataIndex: 'content', key: 'content' },
  { title: '状态', dataIndex: 'status', key: 'status' },
  { title: '操作', key: 'action' },
];

const data = reactive([]);
const classify = ref(1);

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

const filteredData = computed(() => {
  const tabToClassify = {
    'recommendations': 1,
    'stores': 0,
    'events': 2
  };
  return data.filter(item => item.classify === tabToClassify[activeTab.value]);
});

const showAddModal = () => {
  modalMode.value = 'add';
  const tabToClassify = {
    'recommendations': 1,
    'stores': 0,
    'events': 2
  };
  Object.assign(formState, { id: null, classify: tabToClassify[activeTab.value], title: '', content: '', img: '', images: [], status: 0 });
  modalVisible.value = true;
};

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

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


 

const handleModalOk = async () => {
  try {
    const data = {
      classify: formState.classify,
      title: formState.title,
      content: formState.classify === 1 ? '' : formState.content,
      img: processImagePath(formState.img),
      status: formState.status ? 1 : 0,
    };
    if (modalMode.value === 'add') {
      await saveContentApi(data);
    } else {
      await updateContentApi({ ...data, recordId: formState.id });
    }
    message.success(modalMode.value === 'add' ? '添加成功' : '编辑成功');
    modalVisible.value = false;
    fetchData();
  } catch (error) {
    message.error(modalMode.value === 'add' ? '添加失败' : '编辑失败');
  }
};

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

const tabChange = (activeKey) => {
  classify.value = activeKey === 'recommendations' ? 1 : activeKey === 'stores' ? 0 : 2;
  fetchData();
};

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;
    onSuccess(response, file);
  } catch (error) {
    onError(error);
  }
};

const handleImageChange = ({ fileList }) => {
  formState.images = fileList;
};


const handleEditorImageUpload = async (file) => {
  try {
    const response = await uploadImageApi(file);
    const imageUrl = `http://123.249.121.26:8801/images/${response.data}`;
    return imageUrl; // 返回完整的图片路径
  } catch (error) {
    message.error('图片上传失败');
    return '';
  }
};

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 getContentListApi(1, 10, classify.value);
    const records = response.data.records.map(record => {
      if (record.img) {
        record.img = 'http://123.249.121.26:8801/images/' + record.img;
      }
      //取前100个字
      record.content1 = record.content.length > 100 ? record.content.substring(0, 100) + '...' : record.content;
      return record;
    });
    data.splice(0, data.length, ...records);
  } catch (error) {
    message.error('获取数据失败');
  }
};

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

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

