<template>
  <div>
    <BasicModal v-bind="$attrs" @register="registerModal" title="分配菜单" @ok="handleSubmit">
      <template #insertFooter>
        <a-button type="primary" @click="upBtn" :disabled="loading" v-if="step == 2"
          >上一步</a-button
        >
      </template>
      <BasicTree
        ref="asyncExpandTreeRef"
        title="菜单树"
        toolbar
        treeWrapperClassName="h-[calc(100%-35px)] overflow-auto"
        :clickRowToExpand="false"
        :treeData="treeData"
        :fieldNames="{ key: 'id', title: 'name' }"
        :defaultExpandAll="true"
        :checkable="true"
        :checkStrictly="true"
        @check="handleSelect"
        v-if="step == 1"
      />
      <BasicTree
        ref="asyncBtnExpandTreeRef"
        title="按钮树"
        toolbar
        treeWrapperClassName="h-[calc(100%-35px)] overflow-auto"
        :clickRowToExpand="false"
        :treeData="btnData"
        :fieldNames="{ key: 'id', title: 'name', children: 'elements' }"
        :defaultExpandAll="true"
        :checkable="true"
        :checkStrictly="true"
        @check="handleBntSelect"
        v-else
      />
    </BasicModal>
  </div>
</template>
<script lang="ts" setup>
  import { ref, unref, onMounted, nextTick } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicTree, TreeItem, TreeActionType } from '@/components/Tree';
  import { getMenuList } from '@/api/sys/menu';
  import { assignModule, loadForRole } from '@/api/demo/system';
  import { useMessage } from '@/hooks/web/useMessage';

  defineOptions({ name: 'ModulesModal' });

  const emit = defineEmits(['success', 'register', 'select']);
  const treeData = ref<TreeItem[]>([]);
  const btnData = ref<any[]>([]);
  const step = ref(1);
  interface dataType {
    moduleIds?: any;
    elementIds?: any;
  }
  const checkData: dataType = {};
  const asyncExpandTreeRef = ref<Nullable<TreeActionType>>(null);
  const asyncBtnExpandTreeRef = ref<Nullable<TreeActionType>>(null);
  const { createMessage } = useMessage();
  function upBtn() {
    step.value = 1;
    getMenusForRol(rowId.value);
  }
  function treeIterator(tree) {
    tree.forEach((node) => {
      node.name = node.item.name;
      node.id = node.item.id;
      node.elements = node.item.elements;
      node.children && treeIterator(node.children);
    });
  }
  function btnIterator(moduleId, tree) {
    tree.forEach((node) => {
      if (moduleId == node.item.id) {
        btnData.value.push({
          name: node.item.name,
          id: node.item.id,
          elements: node.item.elements,
          disabled: true,
        });
      }
      node.children && btnIterator(moduleId, node.children);
    });
  }
  async function fetch() {
    step.value = 1;
    const data = (await getMenuList()) as unknown as TreeItem[];
    treeIterator(data);
    treeData.value = await data;
    // 展开全部
    nextTick(() => {
      unref(asyncExpandTreeRef)?.expandAll(true);
      unref(asyncBtnExpandTreeRef)?.expandAll(true);
    });
  }
  let moduleIds = ref([]);
  let elementIds = ref([]);
  async function getMenusForRol(id) {
    var menusForRol = await loadForRole({
      roleId: id,
    });
    // var forRole = await loadForRole()
    btnData.value = [];
    menusForRol.moduleIds.forEach((element) => {
      btnIterator(element, treeData.value);
    });
    unref(asyncExpandTreeRef)?.setCheckedKeys(menusForRol.moduleIds);
    checkData.moduleIds = menusForRol.moduleIds;
    checkData.elementIds = menusForRol.elementIds;
    unref(asyncBtnExpandTreeRef)?.setCheckedKeys(checkData.elementIds);
    moduleIds.value = menusForRol.moduleIds;
    elementIds.value = menusForRol.elementIds;
  }

  function handleSelect(checkedKeys, e: { checked: boolean; checkedNodes; node; event }) {
    const list = e.checkedNodes;
    moduleIds.value = [];
    list.forEach((element: any) => {
      element.disabled = true;
      element.name = element.item.name;
      element.children = [];
      moduleIds.value.push(element.item.id);
    });
    btnData.value = list;
  }
  function handleBntSelect(checkedKeys, e: { checked: boolean; checkedNodes; node; event }) {
    const list = e.checkedNodes;
    elementIds.value = [];
    list.forEach((element: any) => {
      elementIds.value.push(element.id);
    });
  }

  onMounted(() => {
    fetch();
  });
  const rowId = ref('');
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    rowId.value = data.record.id;
    step.value = 1;
    getMenusForRol(rowId.value);
    setModalProps({ confirmLoading: false });
  });
  async function handleSubmit() {
    try {
      if (step.value == 1) {
        step.value = 2;
        setTimeout(() => {
          unref(asyncBtnExpandTreeRef)?.setCheckedKeys(checkData.elementIds);
        }, 10);
      } else {
        var query = {
          roleId: rowId.value,
          moduleIds: moduleIds.value,
          elementIds: elementIds.value,
        };
        const data = await assignModule(query);
        if (data) {
          setModalProps({ confirmLoading: true });
          closeModal();
          emit('success');
          return createMessage.success('成功');
        } else {
          return createMessage.error('失败');
        }
      }
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
