<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :showDetailBack="false"
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #menu="{ model, field }">
        <BasicTree
          v-model:value="model[field]"
          :treeData="treeData"
          :replaceFields="{ title: 'name', key: 'id' }"
          :checkable="true"
          toolbar
          :title="t('layout.setting.menuDistribution')"
        />
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref, } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './role.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  // TreeItem;
  import { BasicTree } from '/@/components/Tree';
  import { makeMenuTree, TreeMenuNode } from '/@/utils/treeUtils';
  import { getMenuList, saveRoleApi, updateRoleApi } from '/@/api/sys/system';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useUserStore } from '/@/store/modules/user';

  export default defineComponent({
    name: 'RoleDrawer',
    components: { BasicDrawer, BasicForm, BasicTree },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const treeData = ref<TreeMenuNode[]>([]);
      const userStore = useUserStore();
      const roles = computed(() => userStore.getUserInfo?.roleId);
      const { t } = useI18n();
      const roleId = ref(0);
      const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
        labelWidth: 90,
        schemas: formSchema,
        showActionButtonGroup: false,
      });

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        // 需要在setFieldsValue之前先填充treeData，否则Tree组件可能会报key not exist警告
        if (unref(treeData).length === 0) {
          const tData = (await getMenuList({roleId:unref(roles)})) as any as TreeMenuNode[];
          const list = tData.list.sort((a, b) => {
            return (a.meta?.orderNo || 0) - (b.meta?.orderNo || 0);
          });
          treeData.value = makeMenuTree(list);
        }
        isUpdate.value = !!data?.isUpdate;
        console.log('isUpdate',!!data?.isUpdate)
        updateSchema({
          field: 'status',
          ifShow: unref(isUpdate),
        })
        if (unref(isUpdate)) {
          roleId.value = data.record.roleId;
          setFieldsValue({
            ...data.record,
          });
        }
      });

      const getTitle = computed(() =>
        !unref(isUpdate) ? t('common.addRoleName') : t('common.editRoleName'),
      );

      async function handleSubmit() {
        try {
          const values = await validate();
          setDrawerProps({ confirmLoading: true });
          // let result;
          console.log('values', values,unref(isUpdate));
          if (!unref(isUpdate)) {
            await saveRoleApi(values);
          } else {
            values.roleId = roleId.value;
            await updateRoleApi(values);
          }

          closeDrawer();
          emit('success');
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      return {
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
        treeData,
        t,
      };
    },
  });
</script>
