<template>
  <n-drawer v-model:show="props.visible" @after-leave="handleClose" :width="800">
    <n-drawer-content :title="props.layoutId ? '编辑' : '新增'">
      <template #default>
        <n-form
          class="ls-form"
          ref="formRef"
          :model="formData"
          label-placement="left"
          label-width="85px"
        >
          <n-form-item
            label="页面布局"
            path="layoutId"
            class="flex-1"
            :rule="{ type: 'number', required: true, message: '请选择页面布局', trigger: 'change' }"
          >
            <n-select
              v-model:value="formData.layoutId"
              class="flex-1"
              clearable
              placeholder="请选择页面布局"
              :options="layoutList"
              label-field="description"
              value-field="id"
            />
          </n-form-item>
          <n-form-item
            label="页面类型"
            path="type"
            :rule="{ type: 'number', required: true, message: '请选择页面类型', trigger: 'change' }"
          >
            <n-select
              v-model:value="formData.type"
              placeholder="请选择页面类型"
              @update:value="handleType"
              :options="typeList"
            />
          </n-form-item>
          <n-form-item
            label="推荐文章"
            path="typeId"
            :rule="{
              key: 'typeId',
              type: 'number',
              required: true,
              message: '请选择推荐文章',
              trigger: 'blur',
            }"
          >
            <n-input
              v-model:value="formData.typeText"
              placeholder="请选择推荐文章"
              @click="getLayoutItem"
            />
          </n-form-item>
          <n-form-item label="图片路径" path="image">
            <UploadImg
              :fileType="['image/jpeg', 'image/png', 'image/jpg', 'image/gif']"
              name="article"
              :fileSize="200"
              v-model:image-url="formData.image"
            >
              <template #tip>支持扩展名: jpg png jpeg;文件大小不超过200M</template>
            </UploadImg>
          </n-form-item>
          <n-form-item label="排序" path="sort">
            <n-input-number v-model:value="formData.sort" />
          </n-form-item>
        </n-form>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <n-button @click="handleClose">取消</n-button>
          <n-button :loading="subLoading" type="primary" @click="submit"> 确定 </n-button>
        </span>
      </template>
    </n-drawer-content>
    <chooseArticle
      v-if="chooseVisible"
      v-model:visible="chooseVisible"
      :type="formData.type"
      ref="articleRef"
      @success="selectedCallback"
    />
  </n-drawer>
</template>
<script lang="ts" setup>
  import { getLayoutDetail, layoutAdd, layoutUpdate } from '@/api/content/layoutItem';
  import { getLayoutAllList } from '@/api/content/layout';
  import { onMounted, reactive, ref, nextTick } from 'vue';
  import { useMessage } from 'naive-ui';
  import UploadImg from '@/components/Upload/Image.vue';
  import chooseArticle from './layout/index.vue';
  import { useLockFn } from '@/utils/useLockFn';

  const emit = defineEmits(['success', 'update:visible']);
  const formRef = ref();
  const articleRef = ref();

  /**
   * 定义表单参数
   */
  const message = useMessage();
  const chooseVisible = ref(false);
  const layoutList = ref([]);
  const formData = reactive({
    id: '',
    layoutId: undefined,
    type: undefined,
    typeText: '',
    typeId: '',
    image: '',
    sort: 0,
  });

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

  const typeList = [
    { label: 'CMS文章', value: 1 },
    { label: '通知公告', value: 2 },
  ];

  /**
   * 获取推荐类型
   */
  const getLayoutItem = async () => {
    if (!formData.type) {
      message.warning('请选择页面类型');
      return;
    }
    chooseVisible.value = true;
    await nextTick();
    articleRef.value.openModal();
  };

  /**
   * 执行选择类型
   */
  const handleType = () => {
    formData.typeId = '';
    formData.typeText = '';
  };

  /**
   * 执行提交
   */
  const handleSubmit = async () => {
    formRef.value
      .validate()
      .then(async () => {
        props.layoutId ? await layoutUpdate(formData) : await layoutAdd(formData);
        message.success('操作成功');
        emit('update:visible', false);
        emit('success');
      })
      .catch((error) => {});
  };
  const { isLock: subLoading, lockFn: submit } = useLockFn(handleSubmit);
  /**
   * 关闭窗体
   */
  const handleClose = () => {
    emit('update:visible', false);
  };

  /**
   * 设置表单数据
   */
  const setFormData = async () => {
    const data = await getLayoutDetail(props.layoutId);
    for (const key in formData) {
      if (data[key] != null && data[key] != undefined) {
        //@ts-ignore
        formData[key] = data[key];
      }
    }
  };
  /**
   * 选择推荐内容成功回调事件
   */
  const selectedCallback = (row) => {
    console.log(row);
    formData.typeText = row.title;
    formData.typeId = row.id;
    formRef.value?.validate(
      (errors) => {},
      (rule) => {
        return rule?.key === 'typeId';
      },
    );
    return;
  };

  /**
   * 获取全部字典数据
   */
  const getAllDict = async () => {
    let list = await getLayoutAllList();
    layoutList.value = list ? list : [];
  };
  /**
   * 钩子函数
   */
  onMounted(() => {
    getAllDict();
    if (props.layoutId) {
      setFormData();
    }
  });
</script>
