<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    title="分配部门和职级"
    @ok="handleSubmit"
    :okText="okTextVal"
    :destroyOnClose="true"
    width="1000px"
  >
    <div class="dept-box" v-if="okTextVal == '确认'">
      <div class="dept-left">
        <BasicTree
          ref="asyncExpandTreeRef"
          title="部门列表"
          toolbar
          treeWrapperClassName="h-[calc(100%-35px)] overflow-auto"
          loadData
          :clickRowToExpand="false"
          :treeData="treeDeptData"
          :fieldNames="{ key: 'id', title: 'name' }"
          :checkable="true"
          :checkStrictly="true"
          @check="handleDeptSelect"
          :expandedKeys="expandedKeys"
          @expand="expand"
        />
      </div>
      <div class="dept-right">
        <a-divider>选中部门({{ orgList.length }}个)</a-divider>
        <div class="dept-right-content">
          <a-tag
            color="processing"
            closable
            v-for="item in orgList"
            :key="item.id"
            @close="closeTag(item)"
          >
            {{ item.name }}
          </a-tag>
        </div>
        <!-- <CollapseContainer title="选中部门" :canExpan="false">
          
        </CollapseContainer> -->
      </div>
    </div>
    <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, nextTick } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicTree, TreeItem, TreeActionType } from '@/components/Tree';
  import { getDeptList, userOrgs, getLoadPositionByOrg, getUserOrgs } from '@/api/demo/system';
  import { useMessage } from '@/hooks/web/useMessage';
  import { CollapseContainer } from '@/components/Container/index';

  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('确认');
  const defaultOrg = ref([]);
  const defaultPos = ref([]);
  const expandedKeys = ref<any>([]);
  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[];
    data.forEach((element) => {
      element.title = element.name;
    });
    treeDeptData.value = data;
    // 展开全部
    nextTick(() => {
      // unref(asyncExpandTreeRef)?.expandAll(true);
      unref(asyncExpandTreeRef)?.filterByLevel(1);
      unref(asyncExpandTreeRef)?.setCheckedKeys(defaultOrg.value);
      const keys = defaultOrg.value;
      var arr: any = [];
      keys.forEach((element) => {
        arr.push(unref(asyncExpandTreeRef)?.getSelectedNode(element));
      });
      orgList.value = arr;
    });
  }
  let orgList: any = ref([]);
  let posList: any = ref([]);
  // 部门选择
  async function handleDeptSelect(checkedKeys) {
    const keys = checkedKeys.checked ? checkedKeys.checked : checkedKeys;
    var arr: any = [];
    keys.forEach((element) => {
      arr.push(unref(asyncExpandTreeRef)?.getSelectedNode(element));
    });
    orgList.value = arr;
  }
  async function handlePosSelect(checkedKeys, e: { checked: boolean; checkedNodes; node; event }) {
    posList.value = e.checkedNodes;
  }
  const rowId = ref('');
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({ confirmLoading: false });
    orgList.value = [];
    posList.value = [];
    rowId.value = data.record.id;
    getOrgPos();
    fetch();
    okTextVal.value = '确认';
  });
  async function getOrgPos() {
    const data = await getUserOrgs({
      userId: rowId.value,
    });
    defaultOrg.value = [];
    defaultPos.value = [];
    data.forEach((element) => {
      defaultOrg.value.push(element.orgId);
      defaultPos.value.push(element.positionId);
      posList.value.push({
        id: element.positionId,
        orgId: element.orgId,
      });
    });
  }
  async function handleSubmit() {
    try {
      // 保存部门和职级
      // if (okTextVal.value == '下一步') {
      //   if (orgList.value.length == 0) {
      //     return createMessage.warn('请先选择部门');
      //   }
      //   okTextVal.value = '下一步';
      //   // 获取职级
      //   treePosData.value = [];
      //   orgList.value.forEach(async (element) => {
      //     const data = (await getLoadPositionByOrg({
      //       orgid: element.id,
      //     })) as unknown as TreeItem[];
      //     treeIterator(data, element.id);
      //     treePosData.value = treePosData.value.concat(data);
      //     // 展开全部
      //     nextTick(() => {
      //       unref(asyncExpandTreePosRef)?.setCheckedKeys(defaultPos.value);
      //       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('失败');
      //   }
      // }
      // 保存部门（天空地暂定）
      let arr: any = [];
      orgList.value.forEach((element) => {
        arr.push({
          orgId: element.id,
          posId: 0,
          level: element.level,
        });
      });
      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 });
    }
  }
  function expand(expandedKeys, { expanded, node }) {
    if (expanded) {
      if (node.parent && node.parent.children) {
        for (let i = 0; i < expandedKeys.length; i++) {
          for (let j = 0; j < node.parent.children.length; j++) {
            if (expandedKeys[i] == node.parent.children[j].key) {
              expandedKeys.splice(i, 1);
            }
          }
        }
      }
      expandedKeys.push(node.key);
    }
  }
  // tag关闭，取消对应的部门选择
  function closeTag(data) {
    var currentIndex = (orgList.value || []).findIndex((element) => element.id === data.id);
    orgList.value.splice(currentIndex, 1);
    const keys = orgList.value.map((item) => item.id);
    unref(asyncExpandTreeRef)?.setCheckedKeys(keys);
  }
</script>
<style lang="less" scoped>
  .dept-box {
    display: flex;
    height: 60vh;
    .dept-left {
      width: 60%;
      height: 100%;
    }
    .dept-right {
      width: 38%;
      padding-top: 10px;
      margin-left: 2%;
      height: 100%;
      ::v-deep .ant-tag {
        margin-top: 10px;
        padding: 4px;
      }
      .dept-right-content {
        height: 90%;
        overflow: auto;
      }
    }
  }
</style>
