<script setup lang="ts">
import { onMounted, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { useBeforeCloseDiff } from '#/utils/popup';
import type { TreeProps } from 'ant-design-vue';
import { Switch, Transfer, Tree } from 'ant-design-vue';
import { queryTree } from '#/api/sis/accessControl';
import type { TreeNode } from '#/api/common';

const emit = defineEmits<{ reload: [] }>();
const title = ref('门禁授权');

const { onBeforeClose } = useBeforeCloseDiff({});

const [BasicModal, modalApi] = useVbenModal({
  // 在这里更改宽度
  class: 'w-[700px]',
  fullscreenButton: false,
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
});

async function handleConfirm() {
  try {
    modalApi.lock(true);

    /*const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    const data = cloneDeep(await formApi.getValues());
    await (isUpdate.value ? personLibImgUpdate(data) : personLibImgAdd(data));*/

    // resetInitialized();
    emit('reload');
    modalApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.lock(false);
  }
}

async function handleClosed() {
  // await formApi.resetForm();
  // resetInitialized();
}

const checked = ref(false);
const targetKeys = ref<string[]>([]);
const dataSource = ref<TreeNode[]>([]);
const treeData = ref<TreeNode[]>([]);

onMounted(() => {
  queryAcTree();
});

function handleTreeData(treeData: TreeNode[], datasource: TreeNode[]) {
  treeData.forEach((item) => {
    item.title = item.label;
    item.key = item.code;
    datasource.push(item);
    if (item.children) {
      handleTreeData(item.children, datasource);
    }
  });
}

function queryAcTree() {
  queryTree().then((res = []) => {
    const datasource: TreeNode[] = [];
    handleTreeData(res, datasource);
    dataSource.value = datasource;
    treeData.value = res;
  });
}

const onChecked = (
  e: Parameters<TreeProps['onCheck']>[1] | Parameters<TreeProps['onSelect']>[1],
  checkedKeys: string[],
  onItemSelect: (n: any, c: boolean) => void,
) => {
  const { eventKey } = e.node;
  onItemSelect(eventKey, !isChecked(checkedKeys, eventKey));
};

function isChecked(
  selectedKeys: (string | number)[],
  eventKey: string | number,
) {
  return selectedKeys.indexOf(eventKey) !== -1;
}
</script>

<template>
  <BasicModal :title="title">
    <div class="p-4">
      <span>AI盒子授权: </span>
      <Switch v-model:checked="checked" />
    </div>
    <div class="p-4">
      <Transfer
        v-model:target-keys="targetKeys"
        class="tree-transfer h-[400px]"
        :data-source="dataSource"
        :render="(item) => item.title"
      >
        <template #children="{ direction, selectedKeys, onItemSelect }">
          <Tree
            v-if="direction === 'left'"
            block-node
            checkable
            check-strictly
            :show-line="true"
            default-expand-all
            :checked-keys="[...selectedKeys, ...targetKeys]"
            :tree-data="treeData"
            @check="
              (_, props) => {
                onChecked(
                  props,
                  [...selectedKeys, ...targetKeys],
                  onItemSelect,
                );
              }
            "
            @select="
              (_, props) => {
                onChecked(
                  props,
                  [...selectedKeys, ...targetKeys],
                  onItemSelect,
                );
              }
            "
          />
        </template>
      </Transfer>
    </div>
  </BasicModal>
</template>
