<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" showFooter title="分配数据权限" width="500px" @ok="handleSubmit">
    <BasicForm @register="registerForm">
      <template #menu="{ model, field }">
        <BasicTree
          v-if="treeData.length > 0"
          ref="treeRef"
          v-model:value="model[field]"
          :treeData="treeData"
          :replaceFields="{ title: 'title', key: 'key' }"
          checkable
          toolbar
          title="数据权限"
          @check="onCheck"
        />
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, unref } from 'vue';
  import { BasicForm, useForm, BasicDrawer, useDrawerInner, BasicTree, TreeItem } from '@jdlinker/ui';
  import { dataScopeSchema } from '../role.data';
  import { queryRoleDataPermission, saveRoleDataScope, departTreeList } from '../role.api';

  export default defineComponent({
    name: 'RoleDrawer',
    components: { BasicDrawer, BasicForm, BasicTree },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const treeData = ref<TreeItem[]>([]);
      //树的全部节点信息
      const allTreeKeys = ref([]);
      //树的选择节点信息
      const checkedKeys = ref([]);
      const defaultCheckedKeys = ref([]);
      //树的选中的节点信息
      const selectedKeys = ref([]);
      const roleId = ref('');
      const loading = ref(false);

      const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
        labelWidth: 90,
        schemas: dataScopeSchema,
        showActionButtonGroup: false
      });

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        await reset();
        roleId.value = data.record.id;
        setDrawerProps({ confirmLoading: false, loading: true });
        //初始化数据
        const deptResult = await departTreeList();
        treeData.value = deptResult.treeList;
        allTreeKeys.value = deptResult.ids;
        //初始化角色菜单数据
        const permResult = await queryRoleDataPermission({ roleId: unref(roleId) });
        // checkedKeys.value = permResult;
        defaultCheckedKeys.value = permResult;
        data.record.roleDataScopeListJson = permResult;
        data.record.roleDataScopeListJson = permResult;
        isUpdate.value = !!data?.isUpdate;
        if (unref(isUpdate)) {
          setFieldsValue({
            ...data.record
          });
        }
        setDrawerProps({ loading: false });
      });
      /**
       * 点击选中
       */
      function onCheck(o) {
        checkedKeys.value = o.checked ? o.checked : o;
      }
      /**
       * 数据重置
       */
      function reset() {
        treeData.value = [];
        allTreeKeys.value = [];
        checkedKeys.value = [];
        defaultCheckedKeys.value = [];
        selectedKeys.value = [];
        roleId.value = '';
      }
      async function handleSubmit() {
        loading.value = true;
        try {
          const values = await validate();
          let params = {
            id: unref(values.id),
            dataScope: unref(values.dataScope),
            permissionIds: unref(values.roleDataScopeListJson),
            lastpermissionIds: unref(defaultCheckedKeys).join(',')
          };
          await saveRoleDataScope(params);
          closeDrawer();
          emit('success');
        } finally {
          loading.value = false;
          setDrawerProps({ confirmLoading: false });
        }
      }

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