<template>
  <a-modal
    v-model:visible="props.visible"
    :title="dialogTitle"
    width="1350px"
    @cancel="dialogClose"
    style="top: 20px"
  >
    <a-form
      style="display: flex"
      ref="formRef"
      :model="formData"
      :label-col="{ style: { width: '80px' } }"
    >
      <div style="width: 880px; flex: none" :style="{ height: fwbHeight + 'px' }">
        <a-form-item label-width="0px" name="content">
          <Editor ref="editorRef" :height="fwbHeight" name="article" />
        </a-form-item>
      </div>
      <div style="flex: 1; margin-left: 10px">
        <a-form-item
          label="文章标题"
          name="title"
          :rules="{ required: true, message: '请输入文章标题', trigger: 'blur' }"
        >
          <a-input placeholder="请输入文章标题" :maxlength="50" v-model:value="formData.title" />
        </a-form-item>
        <a-form-item
          label="文章作者"
          name="author"
          :rules="{ required: true, message: '请输入文章作者', trigger: 'blur' }"
        >
          <a-input placeholder="请输入文章作者" :maxlength="50" v-model:value="formData.author" />
        </a-form-item>
        <a-form-item
          label="文章分类"
          name="categoryId"
          :rules="{ required: true, message: '请选择文章分类', trigger: 'change' }"
        >
          <a-tree-select
            v-model:value="formData.categoryId"
            :tree-data="categoryList"
            :fieldNames="{ children: 'children', label: 'name', value: 'id' }"
            placeholder="请选择文章分类"
          />
        </a-form-item>
        <a-form-item
          label="文章封面"
          name="cover"
          :rules="{ required: true, message: '请上传文章封面', trigger: 'change' }"
        >
          <UploadImg
            @change-file-name="(name) => (formData.coverImgName = name)"
            :fileType="['image/jpeg', 'image/png', 'image/jpg', 'image/gif']"
            name="article"
            :fileSize="200"
            v-model:image-url="formData.cover"
          >
            <template #tip>支持扩展名: jpg png jpeg;文件大小不超过200M</template>
          </UploadImg>
        </a-form-item>
        <a-form-item
          label="文章图集"
          name="imagesList"
          :rules="{ required: true, message: '请上传文章图集', trigger: 'change' }"
        >
          <UploadImgs
            @upload="fileUploads"
            file-type=".jpeg,.png,.jpg,.gif"
            name="article"
            :fileSize="200"
            :multiple="true"
            :fileList="formData.imagesList"
          />
        </a-form-item>
        <a-form-item
          label="导读"
          name="intro"
          :rules="{ required: true, message: '请输入导读', trigger: 'blur' }"
        >
          <a-textarea placeholder="请输入导读" v-model:value="formData.intro" />
        </a-form-item>
        <a-form-item
          label="点击率"
          name="click"
          :rules="{ required: true, message: '请输入点击率', trigger: 'blur' }"
        >
          <number-input v-model="formData.click" placeholder="请输入点击率" />
        </a-form-item>
        <a-form-item label="排序" name="sort">
          <a-input-number v-model:value="formData.sort" :max="9999" placeholder="请输入排序" />
        </a-form-item>
        <a-form-item label="状态">
          <a-radio-group v-model:value="formData.status">
            <a-radio :value="0">正常</a-radio>
            <a-radio :value="1">下架</a-radio>
          </a-radio-group>
        </a-form-item>
      </div>
    </a-form>
    <template #footer>
      <span class="dialog-footer">
        <a-button @click="dialogClose">取消</a-button>
        <a-button :loading="subLoading" type="primary" @click="submit"> 确定 </a-button>
      </span>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
  import { getCategoryList } from '@/api/content/category';
  import { articleAdd, articleUpdate, getArticleDetail } from '@/api/content/article';
  import type { FormInstance } from 'ant-design-vue';
  import { computed, onMounted, ref, shallowRef, reactive } from 'vue';
  import UploadImg from '@/components/Upload/Image.vue';
  import UploadImgs from '@/components/Upload/Images.vue';
  import { useLockFn } from '@/utils/useLockFn';
  import Editor from '@/components/Editor/tinymce.vue';
  import { message } from 'ant-design-vue';
  import { buildTree } from '@/utils/auth';

  /**
   * 定义接收的参数
   */
  const props = defineProps({
    visible: {
      type: Boolean,
      required: true,
      default: false,
    },
    articleId: {
      type: Number,
      required: true,
      default: 0,
    },
    searchParamData: {
      type: Object,
      default: {},
    },
  });

  /**
   * 定义参数变量
   */
  const formRef = shallowRef<FormInstance>();
  const categoryList = ref([]);
  const emit = defineEmits(['success', 'update:visible']);

  /**
   * 定义弹窗标题
   */
  const dialogTitle = computed(() => {
    return props.articleId ? '编辑内容' : '新增内容';
  });

  const fwbHeight = document.body.clientHeight - 180;

  /**
   * 定义表单参数
   */
  const formData = reactive({
    id: '',
    categoryId: undefined,
    title: '',
    author: '',
    cover: '',
    intro: '',
    content: '',
    status: 0,
    click: '',
    sort: 0,
    images: '',
    imagesList: [],
  });

  /**
   * 关闭窗体
   */
  const dialogClose = () => {
    emit('update:visible', false);
  };

  /**
   * 设置表单数据
   * @param row 参数
   */
  const setFormData = async (row: any) => {
    const data = await getArticleDetail(props.articleId);
    for (const key in formData) {
      if (data[key] != null && data[key] != undefined) {
        formData[key] = data[key];
      }
    }
    let list = formData.imagesList;
    formData.imagesList = list.map((item) => ({ filePath: item }));
    editorRef.value.myValue = formData.content;
  };

  const editorRef = ref();

  /**
   * 文件上传
   * @param list 列表
   */
  const fileUploads = (list: any) => {
    formData.imagesList = list;
    formRef.value.validateFields('imagesList');
  };

  /**
   * 执行提交表单
   */
  const handleSubmit = async () => {
    await formRef.value?.validate();
    formData.images = '';
    formData.imagesList.map((item, index) => {
      formData.images += `${item.filePath}${index < formData.imagesList.length - 1 ? ',' : ''}`;
    });
    let ruleForm = JSON.parse(JSON.stringify(formData));
    ruleForm.content = editorRef.value.myValue;
    if (!ruleForm.content) {
      message.error('请添加文章内容');
      return;
    }
    props.articleId ? await articleUpdate(ruleForm) : await articleAdd(ruleForm);
    message.success('操作成功');
    emit('update:visible', false);
    emit('success');
  };

  const { isLock: subLoading, lockFn: submit } = useLockFn(handleSubmit);

  /**
   * 获取全部字典数据
   */
  const getAllDict = async () => {
    let list = await getCategoryList();
    categoryList.value = list ? buildTree(list) : [];
  };

  /**
   * 钩子函数
   */
  onMounted(() => {
    getAllDict();
    if (props.articleId) {
      setFormData();
    }
  });
</script>
