<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    destroyOnClose
    :title="getTitle"
    :width="adaptiveWidth"
    @ok="handleSubmit"
    :showFooter="showFooter"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>

<script lang="ts" setup>
  import { ref, unref, computed } from 'vue';
  import { BasicDrawer, useDrawerInner } from '@jdlinker/ui';
  import { BasicForm, useForm } from '@jdlinker/ui';
  import { formSchema } from '../data';
  import { loadTreeData, saveOrUpdateDict } from '../../../../api/device/category';
  import { useDrawerAdaptiveWidth } from '@jdlinker/func';
  // Emits声明
  const emit = defineEmits(['register', 'success']);
  const isUpdate = ref();
  const showFooter = ref(false);
  const expandedRowKeys = ref<any[]>([]);
  const treeData = ref([]);
  // 当前编辑的数据
  let drawer: any = null;
  //表单配置
  const [registerForm, { setProps, resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 90,
    schemas: formSchema,
    showActionButtonGroup: false
  });
  //表单赋值
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    await resetFields();
    expandedRowKeys.value = [];
    showFooter.value = data.showFooter;
    setDrawerProps({ confirmLoading: false, showFooter: showFooter.value });
    isUpdate.value = data.isUpdate;
    // 无论新增还是编辑，都可以设置表单值
    if (typeof data.record === 'object') {
      drawer = data.record;
      await setFieldsValue({ ...data.record });
    } else {
      drawer = null;
    }
    //父级节点树信息
    treeData.value = await loadTreeData({ async: false, pcode: '' });
    // 隐藏底部时禁用整个表单
    setProps({ disabled: !showFooter.value });
  });
  //设置标题
  const getTitle = computed(() => (isUpdate.value == 0 ? '新增' : isUpdate.value == 1 ? '编辑' : '详情'));
  const { adaptiveWidth } = useDrawerAdaptiveWidth();

  /**
   * 根据pid获取展开的节点
   * @param pid
   * @param arr
   */
  function getExpandKeysByPid(pid, arr) {
    if (pid && arr && arr.length > 0) {
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].key == pid && unref(expandedRowKeys).indexOf(pid) < 0) {
          expandedRowKeys.value.push(arr[i].key);
          getExpandKeysByPid(arr[i]['parentId'], unref(treeData));
        } else {
          getExpandKeysByPid(pid, arr[i].children);
        }
      }
    }
  }

  //表单提交事件
  async function handleSubmit() {
    try {
      let values = await validate();
      setDrawerProps({ confirmLoading: true });
      //提交表单
      await saveOrUpdateDict(values, isUpdate.value);
      //关闭弹窗
      closeDrawer();
      //展开的节点信息
      await getExpandKeysByPid(values['pid'], unref(treeData));
      //刷新列表(isUpdate:是否编辑;values:表单信息;expandedArr:展开的节点信息)
      emit('success', {
        isUpdate: unref(isUpdate),
        values: { ...values },
        expandedArr: unref(expandedRowKeys).reverse(),
        // 是否更改了父级节点
        changeParent: drawer != null && drawer['pid'] != values['pid']
      });
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
<style lang="less" scoped>
  /** 时间和数字输入框样式 */
  :deep(.ant-input-number) {
    width: 100%;
  }

  :deep(.ant-calendar-picker) {
    width: 100%;
  }
</style>
