<template>
  <div v-if="defaultColumns?.length">
    <h-tree-table-transfer
      ref="transferRef"
      v-model:target-keys="targetKeys"
      v-model:selected-keys="selectedKeys"
      v-bind="transferOptions"
      @selectChange="onSelectChange"
      :isLoading="isLoading"
      :treeNodeWidth="140"
      :pagination="false"
      :showBorder="false"
    ></h-tree-table-transfer>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, reactive, ref, inject, watch, onUpdated } from 'vue';
import type { ITreeTableTransferProps } from '@crami/ui-types';
// import request from '@/utils/request';
import { useMethods } from './useMethods';
import { getInfo, ICP_CONFIG, usePageParams } from '@remote/icpx-platform/utils';
/* import { usePageParams } from '@/utils/usePageData';
import { getInfo, ICP_CONFIG } from '@/utils/commMethods'; */
import { useHttp } from '@crami/http';
import { commonApi } from '@remote/icpx-platform/commonApi';
/* import { commonApi } from '@/api/commonApi/index'; */
import { useI18n } from '@crami/locale';

export default defineComponent({
  name: 'AuthTransfer',
  props: {
    options: {
      type: Object,
      default: () => ({}),
    },
  },
  setup: props => {
    const { t } = useI18n();
    // 通用参数处理
    const pageParams: any = usePageParams();
    const commonParams = computed(() => {
      return { ...getInfo(ICP_CONFIG), ...pageParams.value };
    });
    const paramOptions: any = inject('options');
    const transferRef = ref();
    const targetKeys = ref<string[]>([]);
    const selectedKeys = ref<string[]>([]);
    const treeData: any[] = [];
    const defaultColumns = ref([]);
    async function getTableTitle() {
      const data = {
        // lang: commonParams.value?.lang,
        // connect: commonParams.value?.connect,
        // companyId: commonParams.value?.companyId,
        viewName: paramOptions.value.queryParam.params.viewName,
      };
      const result = await useHttp<any, any>({
        url: '/system/view/getData',
        data: {
          data: JSON.stringify({ ...commonApi().system.getData.params, ...data }),
          type: 'gridTitle',
        },
        method: commonApi().system.getData.method,
      });
      if (result.code == '200') {
        console.log(result.data.titleData);
        let list = result.data.titleData;
        list.forEach((element, index) => {
          if (element.show == false) {
            list.splice(index, 1);
          } else if (element.width == -1) {
            element.width = undefined;
          }
        });
        defaultColumns.value = list;
        transferOptions!.tableColumns = list;
      }
    }

    const transferOptions = reactive<ITreeTableTransferProps>({
      locale: {
        itemUnit: t('permission.common.unit'),
        itemsUnit: t('permission.common.unit'),
        notFoundContent: t('permission.common.notFoundContent'),
        searchPlaceholder: t('permission.common.inputPlaceholder'),
      } as any,
      // titles: ['未选择用户', '已选择用户'],
      // operations: [t('permission.common.addOperations'), t('permission.common.removeOperations')],
      showSelectAll: false,
      showSearch: true,

      //type: 'treeTable',
      listStyle: {
        width: '300px',
        height: '400px',
      },
      isLeafNode(node) {
        return node.value3 === paramOptions.value.attr.transtype[0]; //
      },
      render: item => item.key,
      tableOptions: {
        rowKey: 'EID',
        pagination: false,
        height: '360px',
        bordered: false,
      },
      treeData: treeData.concat([]),
      tableColumns: defaultColumns.value,
      //props.options.queryParam.columns ||
      tableData: [],
      treeOptions: {
        height: '360px',
      },
      searchKey:
        paramOptions?.value?.attr?.transtype[0] === 'P_SYS_USER' ? 'USER_ALL_NAME' : 'ENAME',
      customerTitleStyle: nodeData => {
        return {
          color:
            nodeData.value3 === paramOptions.value.attr.transtype[0] ? '' : 'rgba(0, 0, 0, 0.25)',
        };
      },
    });

    onUpdated(() => {
      console.log(props.options);
      if (props.options.org == 'current') {
        transferRef.value.filterTreeDataByNode({
          value1: window.localStorage.getItem('userGroup') || '',
        });
      } else {
        transferRef.value.filterTreeDataByNode();
      }
    });
    const data = reactive<ITreeTableTransferProps>({
      treeData: treeData.concat([]),
      tableColumns: props.options.queryParam.columns || defaultColumns.value,
      tableData: [],
    });

    // 加载右侧列表
    async function getDeptUserList() {
      if (props.options.data == '') {
        return;
        // eslint-disable-next-line no-empty
      } else {
        console.log(props.options.queryParam);
        const result = await useHttp({
          url: props.options.queryParam.url,
          method: 'post',
          params: {
            lang: commonParams.value?.lang,
            connect: commonParams.value?.connect,
            companyId: commonParams.value?.companyId,
            objIds: props.options.data,
            viewName: paramOptions.value.queryParam.params.viewName,
          },
        });
        if (result.code == '200') {
          const list = result.data.data;
          targetKeys.value = list.map(item => item.EID);
          // 等待组件渲染完（不知道为啥组件会把tasbleList覆盖）
          setTimeout(() => {
            transferOptions!.tableData = list;
          }, 200);
        }
      }
    }

    function refreshData() {
      // 加载右侧列表数据
      getDeptUserList();
    }

    const { getTreeData } = useMethods(transferOptions as any);
    // console.log(paramOptions.value.treeParam.params.treeViewName);
    // getTreeData(paramOptions.value.treeParam.params.treeViewName);

    const onSelectChange = (sourceSelectedKeys: any, targetSelectedKeys: any) => {
      console.log('sourceSelectedKeys', JSON.parse(JSON.stringify(sourceSelectedKeys)));
      console.log('targetSelectedKeys', JSON.parse(JSON.stringify(targetSelectedKeys)));
    };
    // 初始化基本数据
    // refreshData();
    // getTableTitle();

    const getTableKeys = () => {
      return transferRef.value?.getTableKeys();
    };
    const getTableData = () => {
      return transferRef.value?.getTableData();
    };

    let flag = false;

    watch(
      () => paramOptions.value,
      () => {
        getTableTitle();
        if (!flag) {
          getTreeData(
            paramOptions.value.treeParam.params.treeViewName,
            paramOptions.value.org,
            transferRef,
          );
          flag = true;
        }
      },
      {
        deep: true,
        immediate: true,
      },
    );

    watch([() => paramOptions.value, () => transferOptions.treeData], () => {
      if (transferOptions.treeData?.length > 0) {
        refreshData();
      }
    });

    const isLoading = ref(true);
    watch(
      () => transferOptions.treeData,
      () => {
        isLoading.value = false;
      },
    );

    return {
      t,
      transferRef,
      targetKeys,
      selectedKeys,
      //treeData,
      transferOptions,
      onSelectChange,
      data,
      getTableKeys,
      getTableData,
      defaultColumns,
      isLoading,
    };
  },
});
</script>

<style lang="less" scoped>
:deep(.h-transfer .ant-btn .anticon) {
  display: inline-block;
}
</style>
