<template>
  <basicModal
    @register="modalRegister"
    ref="modalRef"
    class="basicModal basicFormModal"
    @on-ok="handleSubmit"
    @on-close="handleClose"
  >
    <template #default>
      <n-form
        class="ls-form"
        ref="formRef"
        :model="formData"
        label-placement="left"
        label-width="85px"
        style="display: flex"
      >
        <div style="width: 880px; flex: none" :style="{ height: fwbHeight + 'px' }">
          <n-form-item label-width="0px" path="content">
            <Editor ref="editorRef" :height="fwbHeight" name="article" />
          </n-form-item>
        </div>
        <div style="flex: 1; margin-left: 10px">
          <n-form-item
            label="文章标题"
            path="title"
            :rule="{ required: true, message: '请输入文章标题', trigger: 'blur' }"
          >
            <n-input placeholder="请输入文章标题" :maxlength="50" v-model:value="formData.title" />
          </n-form-item>
          <n-form-item
            label="文章作者"
            path="author"
            :rule="{ required: true, message: '请输入文章作者', trigger: 'blur' }"
          >
            <n-input placeholder="请输入文章作者" :maxlength="50" v-model:value="formData.author" />
          </n-form-item>
          <n-form-item
            label="文章分类"
            path="categoryId"
            :rule="{ required: true, message: '请选择文章分类', trigger: 'change' }"
          >
            <n-tree-select
              v-model:value="formData.categoryId"
              :tree-data="categoryList"
              :fieldNames="{ children: 'children', label: 'name', value: 'id' }"
              placeholder="请选择文章分类"
            />
          </n-form-item>
          <n-form-item
            label="文章封面"
            path="cover"
            :rule="{ 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>
          </n-form-item>
          <n-form-item
            label="文章图集"
            path="imagesList"
            :rule="{
              key: 'imagesList',
              type: 'array',
              required: true,
              message: '请上传文章图集',
              trigger: 'change',
            }"
          >
            <UploadImgs
              @upload="fileUploads"
              file-type=".jpeg,.png,.jpg,.gif"
              name="article"
              :fileSize="200"
              :multiple="true"
              :fileLists="formData.imagesList"
            />
          </n-form-item>
          <n-form-item
            label="导读"
            path="intro"
            :rule="{ required: true, message: '请输入导读', trigger: 'blur' }"
          >
            <n-input type="textarea" placeholder="请输入导读" v-model:value="formData.intro" />
          </n-form-item>
          <n-form-item
            label="点击率"
            path="click"
            :rule="{ required: true, message: '请输入点击率', trigger: 'blur' }"
          >
            <number-input v-model="formData.click" placeholder="请输入点击率" />
          </n-form-item>
          <n-form-item label="排序" path="sort">
            <n-input-number v-model:value="formData.sort" :max="9999" placeholder="请输入排序" />
          </n-form-item>
          <n-form-item label="状态">
            <n-radio-group v-model:value="formData.status">
              <n-radio :value="0">正常</n-radio>
              <n-radio :value="1">下架</n-radio>
            </n-radio-group>
          </n-form-item>
        </div>
      </n-form>
    </template>
  </basicModal>
</template>
<script lang="ts" setup>
  import { getArticleDetail, articleAdd, articleUpdate } from '@/api/content/article';
  import { getCategoryList } from '@/api/content/category';
  import { onMounted, reactive, ref } from 'vue';
  import { useMessage } from 'naive-ui';
  import { useModal } from '@/components/Modal';
  import UploadImg from '@/components/Upload/Image.vue';
  import UploadImgs from '@/components/Upload/Images.vue';
  import Editor from '@/components/Editor/tinymce.vue';
  import { buildTree } from '@/utils/auth';

  const emit = defineEmits(['success', 'update:visible']);
  const formRef = ref();
  const editorRef = ref();
  const categoryList = ref([]);
  const fwbHeight = document.body.clientHeight - 180;

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

  /**
   * 定义接收的参数
   */
  const props = defineProps({
    visible: {
      type: Boolean,
      required: true,
      default: false,
    },
    articleId: {
      type: Number,
      required: true,
      default: 0,
    },
  });
  const [modalRegister, { openModal, setSubLoading }] = useModal({
    title: props.articleId ? '编辑文章' : '添加文章',
    subBtuText: '确定',
    width: 1350,
  });

  /**
   * 文件上传
   * @param list 列表
   */
  const fileUploads = (list: any) => {
    console.log(list);
    formData.imagesList = list;
    formRef.value?.validate(
      (errors) => {},
      (rule) => {
        return rule?.key === 'imagesList';
      },
    );
    return;
  };
  /**
   * 执行提交
   */
  const handleSubmit = async () => {
    formRef.value
      .validate()
      .then(async () => {
        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('操作成功');
        setSubLoading(false);
        emit('update:visible', false);
        emit('success');
      })
      .catch((error) => {
        setSubLoading(false);
      });
  };

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

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

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

  /**
   * 钩子函数
   */
  onMounted(() => {
    getAllDict();
    if (props.articleId) {
      setFormData();
    }
  });
  //导出方法
  defineExpose({
    openModal,
  });
</script>
