<!-- 编辑弹窗 -->
<template>
  <ele-modal
    :width="550"
    :visible="visible"
    :maskClosable="false"
    :title="isUpdate ? '编辑书籍' : '添加书籍'"
    :body-style="{ paddingBottom: '28px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="styleResponsive ? { md: 5, sm: 7, xs: 24 } : { flex: '90px' }"
      :wrapper-col="
        styleResponsive ? { md: 18, sm: 19, xs: 24 } : { flex: '1' }
      "
    >
      <a-form-item label="书籍名称" name="name">
        <a-input
          allow-clear
          :maxlength="100"
          placeholder="书籍名称"
          v-model:value="form.name"
        />
      </a-form-item>
      <a-form-item label="英文标识" name="code">
        <a-input
          allow-clear
          :maxlength="100"
          placeholder="cms"
          v-model:value="form.code"
        />
      </a-form-item>
      <a-form-item label="排序号" name="sortNumber" v-if="isUpdate">
        <a-input-number
          :min="0"
          :max="9999"
          class="ele-fluid"
          placeholder="请输入排序号"
          v-model:value="form.sortNumber"
        />
      </a-form-item>
      <a-form-item label="状态" name="status" v-if="isUpdate">
        <a-radio-group v-model:value="form.status">
          <a-radio :value="0">开启</a-radio>
          <a-radio :value="1">关闭</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="备注">
        <a-textarea
          :rows="4"
          :maxlength="200"
          placeholder="请输入备注"
          v-model:value="form.comments"
        />
      </a-form-item>
      <a-form-item label="封面图" name="photo">
        <SelectFile
          :placeholder="`请选择图片`"
          :limit="1"
          :data="images"
          @done="chooseFile"
          @del="onDeleteItem"
        />
<!--        <ele-image-upload-->
<!--          v-model:value="images"-->
<!--          :limit="1"-->
<!--          :accept="'image/png,image/jpeg'"-->
<!--          :drag="true"-->
<!--          :upload-handler="uploadHandler"-->
<!--          @upload="onUpload"-->
<!--        />-->
      </a-form-item>
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { message } from 'ant-design-vue';
  import { uuid } from 'ele-admin-pro';
  import { addDocsBook, updateDocsBook } from '@/api/cms/docs-book';
  import { DocsBook } from '@/api/cms/docs-book/model';
  import { useThemeStore } from '@/store/modules/theme';
  import { storeToRefs } from 'pinia';
  import { FormInstance } from 'ant-design-vue/es/form';
  import { ItemType } from 'ele-admin-pro/es/ele-image-upload/types';
  import useFormData from '@/utils/use-form-data';
  import { uploadFile } from '@/api/system/file';
  import {FileRecord} from "@/api/system/file/model";

  // 是否是修改
  const isUpdate = ref(false);
  // 是否开启响应式布局
  const themeStore = useThemeStore();
  const { styleResponsive } = storeToRefs(themeStore);
  // 编辑器内容，双向绑定
  const content = ref<any>('');

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: DocsBook | null;
  }>();

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  // 提交状态
  const loading = ref(false);
  // 已上传数据
  const images = ref<ItemType[]>([]);
  // 表格选中数据
  const formRef = ref<FormInstance | null>(null);

  // 表单数据
  const { form, resetFields, assignFields } = useFormData<DocsBook>({
    bookId: undefined,
    name: '',
    code: '',
    photo: '',
    status: 0,
    comments: '',
    sortNumber: 100
  });

  /* 更新visible */
  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  // 表单验证规则
  const rules = reactive({
    name: [
      {
        required: true,
        type: 'string',
        message: '请填写书籍名称',
        trigger: 'blur'
      }
    ],
    code: [
      {
        required: true,
        type: 'string',
        message: '请填写英文标识',
        trigger: 'blur'
      }
    ]
  });

  /* 上传事件 */
  const uploadHandler = (file: File) => {
    const item: ItemType = {
      file,
      uid: (file as any).uid,
      name: file.name
    };
    if (file.type.startsWith('video')) {
      return;
    }
    if (file.type.startsWith('image')) {
      if (file.size / 1024 / 1024 > 1) {
        message.error('大小不能超过 1MB');
        return;
      }
    }
    onUpload(item);
  };

  // 上传文件
  const onUpload = (item: any) => {
    const { file } = item;
    uploadFile(file)
      .then((data) => {
        form.photo = data.path;
        images.value.push({
          uid: data.id,
          url:
            file.type == 'video/mp4'
              ? 'https://oss.wsdns.cn/20240301/6e4e32cb808245d4be336b9486961145.png'
              : data.path,
          status: 'done'
        });
      })
      .catch((e) => {
        message.error(e.message);
      });
  };

  const chooseFile = (data: FileRecord) => {
    images.value.push({
      uid: data.id,
      url: data.path,
      status: 'done'
    });
    form.photo = data.path;
  }

  const onDeleteItem = (index: number) => {
    images.value.splice(index,1)
    form.photo = '';
  }

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        const formData = {
          ...form,
          content: content.value
        };
        const saveOrUpdate = isUpdate.value ? updateDocsBook : addDocsBook;
        saveOrUpdate(formData)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        images.value = [];
        if (props.data) {
          assignFields(props.data);
          if (props.data.photo) {
            images.value.push({
              uid: uuid(),
              url: props.data.photo,
              status: 'done'
            });
          }
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
          content.value = '';
        }
      } else {
        resetFields();
        formRef.value?.clearValidate();
      }
    },
    { immediate: true }
  );
</script>
