<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    @ok="handSubmit"
    :title="t('layout.setting.setRoles')"
    @visible-change="handleVisibleChange"
    @cancel="closeModal"
  >
    <div class="pt-3px pr-3px">
      <BasicTree v-if="unref(treeData).length !== 0"
        v-model:value="treeModel"
        :treeData="treeData"
        :replaceFields="{ title: 'name', key: 'id' }"
        :checkable="true"
        toolbar
        :title="t('layout.setting.menuDistribution')"
      />
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { BasicTree } from '/@/components/Tree';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { defineComponent, nextTick, ref, unref, computed } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { makeMenuTree, TreeMenuNode, getTreeId } from '/@/utils/treeUtils';
  import { getMenuList, getMenuIdsByRoleId, giveMenu } from '/@/api/sys/system';
  import { useUserStore } from '/@/store/modules/user';

  const { createMessage } = useMessage();
  interface getMenuListInterf {
    list:TreeMenuNode[]
  }
  export default defineComponent({
    components: { BasicModal, BasicTree },
    props: {
      userData: { type: Object },
    },
    setup(props) {
      const { t } = useI18n();
      const treeModel = ref<number[]>([]);
      const treeData = ref<TreeMenuNode[]>([]);
      const userStore = useUserStore();
      const roles = computed(() => userStore.getUserInfo?.roleId);
      const tableDataId = ref<number>(0)

      const [register, { closeModal }] = useModalInner((data) => {
        data && onDataReceive(data);
      });

      async function onDataReceive(data) {
        // 需要在setFieldsValue之前先填充treeData，否则Tree组件可能会报key not exist警告
        if (unref(treeData).length === 0) {
          const tData = (await getMenuList({roleId:unref(roles)})) as any as getMenuListInterf;
          treeData.value = makeMenuTree(tData.list);
        }
        if(data){
          tableDataId.value = data.id
          const roleData = (await getMenuIdsByRoleId({roleId:data.id||unref(roles)})) as any as TreeMenuNode[];
          treeModel.value = roleData
          console.log('treeModel.value',treeModel.value)
        }
      }
      async function handSubmit() {
        // const { id, password } = await validate();
        await giveMenu({ roleId:tableDataId.value || unref(roles), menuIds: treeModel.value });
        createMessage.success(t('common.optSuccess'));
        closeModal();
      }
      function handleVisibleChange(v) {
        v && props.userData && nextTick(() => onDataReceive(props.userData));
      }

      return {
        handSubmit,
        register,
        t,
        unref,
        treeModel,
        treeData,
        handleVisibleChange,
        closeModal,
      };
    },
  });
</script>
