<template>
  <basicModal
    @register="modalRegister"
    ref="modalRef"
    class="basicModal basicFormModal"
    @on-ok="handleSubmit"
    @on-close="handleClose"
  >
    <template #default>
      <n-form ref="formRef" :model="formData" label-placement="left" label-width="80px">
        <n-form-item
          label="上级分类"
          path="parentId"
          :rule="{ required: true, message: '请选择上级分类', trigger: 'change' }"
        >
          <n-tree-select
            class="flex-1"
            v-model:value="formData.parentId"
            :options="categoryOptions"
            clearable
            default-expand-all
            label-field="name"
            key-field="id"
            placeholder="请选择上级分类"
          />
        </n-form-item>
        <n-form-item
          label="分类名称"
          path="name"
          :rule="{ required: true, message: '请输入分类名称', trigger: 'blur' }"
        >
          <n-input v-model:value="formData.name" placeholder="请输入分类名称" clearable />
        </n-form-item>
        <n-form-item label="分类排序" path="sort" class="flex-1">
          <div>
            <n-input-number v-model:value="formData.sort" :max="9999" />
            <div class="form-tips">数值越小越排前</div>
          </div>
        </n-form-item>
        <n-form-item label="分类备注" path="note">
          <n-input
            type="textarea"
            class="flex-1"
            v-model:value="formData.note"
            placeholder="请输入分类备注"
            clearable
          />
        </n-form-item>
      </n-form>
    </template>
  </basicModal>
</template>
<script lang="ts" setup>
  import {
    categoryAdd,
    categoryUpdate,
    getCategoryList,
    getCategoryDetail,
  } from '@/api/content/category';
  import { onMounted, reactive, ref, shallowRef } from 'vue';
  import { buildTree } from '@/utils/auth';
  import { useMessage, useDialog } from 'naive-ui';
  import { useModal } from '@/components/Modal';

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

  /**
   * 定义参数变量
   */
  const message = useMessage();
  const expandedKeys = ref([]);
  const emit = defineEmits(['success', 'update:visible']);
  const formRef = ref();

  /**
   * 定义表单参数
   */
  const formData = reactive({
    id: '',
    //父级id
    parentId: 0,
    //类型
    type: 1,
    //名称
    name: '',
    //排序
    sort: 0,
    note: '',
  });
  const [modalRegister, { openModal, setSubLoading }] = useModal({
    title: props.categoryId ? '编辑分类' : '添加分类',
    subBtuText: '确定',
    width: 600,
  });
  /**
   * 关闭窗体
   */
  const handleClose = () => {
    emit('update:visible', false);
  };

  const categoryOptions = ref<any[]>([]);

  /**
   * 获取分类数据
   */
  const getcategory = async () => {
    const data: any = await getCategoryList();
    data.map((item) => {
      expandedKeys.value.push(item.id);
    });
    const menu: any = [{ id: 0, name: '顶级', children: [] }];
    const lists = buildTree(data);
    menu[0].children.push(...lists);
    categoryOptions.value = menu;
  };

  /**
   * 执行提交表单
   */
  const handleSubmit = async () => {
    formRef.value
      .validate()
      .then(async () => {
        props.categoryId ? await categoryUpdate(formData) : await categoryAdd(formData);
        message.success('操作成功');
        setSubLoading(false);
        emit('update:visible', false);
        emit('success');
      })
      .catch((error) => {
        setSubLoading(false);
      });
  };

  /**
   * 设置表单数据
   */
  const setFormData = (data: Record<any, any>) => {
    for (const key in formData) {
      if (data[key] != null && data[key] != undefined) {
        formData[key] = data[key];
      }
    }
  };

  const getDetail = async () => {
    const data = await getCategoryDetail(props.categoryId);
    setFormData(data);
  };

  /**
   * 钩子函数
   */
  onMounted(() => {
    getcategory();
    if (props.categoryId) {
      getDetail();
    } else {
      formData.parentId = props.pid;
    }
  });
  //导出方法
  defineExpose({
    openModal,
  });
</script>
