<template>
  <BasicModal v-bind="$attrs" @register="registerModal" title="分配部门和职级" @ok="handleSubmit">
    <BasicTree ref="asyncExpandTreeRef" title="部门和职级列表" toolbar treeWrapperClassName="h-[calc(100%-35px)] overflow-auto"
      loadData :clickRowToExpand="false" :treeData="treeData" :fieldNames="{ key: 'id', title: 'name' }" 
      :defaultExpandAll="true" :checkable="true" :checkStrictly="true" @check="handleSelect" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, onMounted, nextTick } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { accountFormSchema } from './account.data';
  import { BasicTree, TreeItem } from '@/components/Tree';
  import { getOrgPositonTree,userOrgs } from '@/api/demo/system';
  import { useMessage } from '/@/hooks/web/useMessage';

  defineOptions({ name: 'OrgPositonModal' });

  const emit = defineEmits(['success', 'register', 'select']);
  const treeData = ref < TreeItem[] > ([]);
  const asyncExpandTreeRef = ref < Nullable < TreeActionType >> (null);
  const { createConfirm, createMessage } = useMessage();
  const checkedKeys =  ref<number[]>([]);
  function treeIterator(tree) {
    tree.forEach((node) => {
      if (node.key == 0) {
        node.name = "部门--" + node.name
      } else {
        node.name = "职级--" + node.name
      }
      node.children && treeIterator(node.children)
    })
  }
  async function fetch() {
    const data = (await getOrgPositonTree()) as unknown as TreeItem[];
    treeIterator(data)
    treeData.value = await data
    // 展开全部
    nextTick(() => {
      unref(asyncExpandTreeRef)?.expandAll(true);
    });
  }
  let orgList = ref([])
  let posList = ref([])
  function handleSelect(checkedKeys, e: { checked: bool, checkedNodes, node, event }) {
    const list = e.checkedNodes
    orgList.value = []
    posList.value = []
    list.forEach(element => {
      if (element.key > 0) {
        posList.value.push({
          orgId: Number(element.tag),
          posId: element.id,
        })
      } else {
        orgList.value.push({
          orgId: element.id,
          posId: 0,
        })
      }
    });
  }

  onMounted(() => {
    fetch();
  });
  const rowId = ref('');
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    // unref(asyncExpandTreeRef)?.setCheckedKeys([1]);
    setModalProps({ confirmLoading: false });
    rowId.value = data.record.id;
  });
  async function handleSubmit() {
    try {
      let duplicates = {};
      for (let i = 0; i < posList.value.length; i++) {
        if (!duplicates[posList.value[i].orgId]) {
          duplicates[posList.value[i].orgId] = 1;
        } else {
          duplicates[posList.value[i].orgId]++;
        }
      }
      for (let key in duplicates) {
        if (duplicates[key] > 1) {
          return createMessage.warn('一个部门只能选择一个职级');
        }
      }
      var query = {}
      const arrs = posList.value.map(item => {
        const data = orgList.value.find(i => item.orgId == i.orgId)
        return {
          ...data,
          ...item,
        }
      })
      if (posList.value.length == 0) {
        query = {
          userId: rowId.value,
          orgPoses: orgList.value
        }
      } else if (orgList.length == 0) {
        query = {
          userId: rowId.value,
          orgPoses: posList.value
        }
      } else {
        query = {
          userId: rowId.value,
          orgPoses: arrs
        }
      }
      const data = await userOrgs(query)
      setModalProps({ confirmLoading: true });
      closeModal();
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>