<template>
  <el-dialog
    v-model="props.visible"
    :title="props.categoryId ? '编辑' : '新增'"
    width="600"
    :close-on-click-modal="false"
    :before-close="dialogClose"
  >
    <el-form ref="formRef" :model="formData" label-width="80px">
      <el-form-item
        label="上级分类"
        prop="parentId"
        :rules="{ required: true, message: '请选择上级分类', trigger: 'change' }"
      >
        <el-tree-select
          class="flex-1"
          v-model="formData.parentId"
          :data="categoryOptions"
          clearable
          node-key="id"
          :props="{
            label: 'name',
          }"
          :default-expand-all="true"
          placeholder="请选择上级分类"
          check-strictly
        />
      </el-form-item>
      <el-form-item
        label="分类名称"
        prop="name"
        :rules="{ required: true, message: '请输入分类名称', trigger: 'blur' }"
      >
        <el-input v-model="formData.name" placeholder="请输入分类名称" clearable />
      </el-form-item>
      <el-form-item label="分类排序" prop="sort" class="flex-1">
        <div>
          <el-input-number v-model="formData.sort" :max="9999" placeholder="请输入分类排序" />
          <div class="form-tips">数值越小越排前</div>
        </div>
      </el-form-item>
      <el-form-item label="分类备注" prop="note">
        <el-input
          class="flex-1"
          v-model="formData.note"
          type="textarea"
          placeholder="请输入分类备注"
          clearable
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogClose">取消</el-button>
        <el-button :loading="subLoading" type="primary" @click="submit"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
  import type { FormInstance } from 'element-plus';
  import {
    categoryAdd,
    categoryUpdate,
    getCategoryList,
    getCategoryDetail,
  } from '@/api/content/category';
  import { onMounted, reactive, ref, shallowRef } from 'vue';
  import { message, buildTree } from '@/utils/auth';
  import { useLockFn } from '@/utils/useLockFn';

  /**
   * 定义接收的参数
   */
  const props = defineProps({
    visible: {
      type: Boolean,
      required: true,
      default: false,
    },
    categoryId: {
      type: Number,
      required: true,
      default: 0,
    },
    pid: {
      type: Number,
      default: 0,
    },
  });
  const emit = defineEmits(['success', 'update:visible']);
  const formRef = shallowRef<FormInstance>();

  /**
   * 定义表单参数
   */
  const formData = reactive({
    id: '',
    //父级id
    parentId: 0,
    //名称
    name: '',
    //排序
    sort: 0,
    note: '',
  });

  const dialogClose = () => {
    emit('update:visible', false);
  };

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

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

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

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

  /**
   * 设置表单数据
   */
  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(() => {
    getCategoryData();
    if (props.categoryId) {
      getDetail();
    } else {
      formData.parentId = props.pid;
    }
  });
</script>
