<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    title="分配部门和职级"
    @ok="handleSubmit"
    :okText="okTextVal"
    :destroyOnClose="true"
  >
    <BasicTree
      ref="asyncExpandTreeRef"
      title="部门列表"
      toolbar
      treeWrapperClassName="h-[calc(100%-35px)] overflow-auto"
      loadData
      :clickRowToExpand="false"
      :treeData="treeDeptData"
      :fieldNames="{ key: 'id', title: 'name' }"
      :defaultExpandAll="true"
      :checkable="true"
      :checkStrictly="true"
      @check="handleDeptSelect"
      v-if="okTextVal == '下一步'"
    />
    <BasicTree
      ref="asyncExpandTreePosRef"
      title="职级列表"
      toolbar
      treeWrapperClassName="h-[calc(100%-35px)] overflow-auto"
      loadData
      :clickRowToExpand="false"
      :treeData="treePosData"
      :fieldNames="{ key: 'id', title: 'name' }"
      :defaultExpandAll="true"
      :checkable="true"
      :checkStrictly="true"
      @check="handlePosSelect"
      v-else
    />
  </BasicModal>
</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 { getDeptList, userOrgs, getPositionsTree } from '@/api/demo/system';
  import { useMessage } from '@/hooks/web/useMessage';
  defineOptions({ name: 'OrgPositonModal' });
  const emit = defineEmits(['success', 'register', 'select']);
  const treeDeptData = ref<TreeItem[]>([]);
  const treePosData = ref<TreeItem[]>([]);
  const asyncExpandTreeRef = ref<Nullable<TreeActionType>>(null);
  const asyncExpandTreePosRef = ref<Nullable<TreeActionType>>(null);
  const { createMessage } = useMessage();
  const okTextVal = ref('下一步');
  function treeIterator(tree, orgId) {
    tree.forEach((node) => {
      node.orgId = orgId;
      node.children && treeIterator(node.children, orgId);
    });
  }
  async function fetch() {
    const data = (await getDeptList()) as unknown as TreeItem[];
    treeDeptData.value = data;
    // 展开全部
    nextTick(() => {
      unref(asyncExpandTreeRef)?.expandAll(true);
    });
  }
  let orgList: any = ref([]);
  let posList: any = ref([]);
  async function handleDeptSelect(checkedKeys, e: { checked: boolean; checkedNodes; node; event }) {
    console.log(e.checkedNodes);
    orgList.value = e.checkedNodes;
  }
  async function handlePosSelect(checkedKeys, e: { checked: boolean; checkedNodes; node; event }) {
    posList.value = e.checkedNodes;
  }
  const rowId = ref('');
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    // unref(asyncExpandTreeRef)?.setCheckedKeys([1]);
    setModalProps({ confirmLoading: false });
    orgList.value = []
    posList.value = []
    fetch()
    rowId.value = data.record.id;
    okTextVal.value = '下一步';
  });

  async function handleSubmit() {
    try {
      if (okTextVal.value == '下一步') {
        console.log(orgList)
        if (orgList.value.length == 0) {
          return createMessage.warn('请先选择部门');
        }
        okTextVal.value = '确认';
        // 获取职级
        treePosData.value = [];
        orgList.value.forEach(async (element) => {
          const data = (await getPositionsTree({
            orgId: element.id,
          })) as unknown as TreeItem[];
          treeIterator(data, element.id);
          treePosData.value = treePosData.value.concat(data);
          // 展开全部
          nextTick(() => {
            unref(asyncExpandTreePosRef)?.expandAll(true);
          });
        });
      } else {
        let duplicates = {};
        let arr: any = [];
        for (let i = 0; i < posList.value.length; i++) {
          if (!duplicates[posList.value[i].orgId]) {
            arr.push({
              orgId: posList.value[i].orgId,
              posId: posList.value[i].id,
            });
            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 = {
          userId: rowId.value,
          orgPoses: arr,
        };
        const data = await userOrgs(query);
        if (data) {
          setModalProps({ confirmLoading: true });
          closeModal();
          emit('success');
          return createMessage.success('成功');
        } else {
          return createMessage.error('失败');
        }
      }
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
