import type { ITreeNode, ITreeMethods, ITransferProps, ITclTransferItem } from '@crami/ui-types';
import { Http, useHttp } from '@crami/http';
import { ref } from 'vue';
import { getInfo, ICP_CONFIG } from '../../../../utils/commMethods';
import { getUuid } from '@/utils/uuid';
import { commonApi } from '@/api/commonApi/index';

let paramsData: {
  treeView: string;
  link: { [key: string]: any };
  page: { [key: string]: any };
  menu: { [key: string]: any };
} = { treeView: '', link: {}, page: {}, menu: {} };

export function useMethods(data: ITclTransferItem, tabData?: ITransferProps, onSelect?: any) {
  const { lang, connect, companyId, project } = getInfo(ICP_CONFIG);

  // 获取子节点时的取值规则
  const treeRef = ref<ITreeMethods>();
  let filterFlag: string[] = [];
  let treeViewName = '';

  // 请求参数
  const getParams = async () => {
    const result = await useHttp({
      url: commonApi().studioCache.getByProjectAndType.url,
      method: commonApi().studioCache.getByProjectAndType.method,
      params: {
        ...commonApi().studioCache.getByProjectAndType.params,
        type: 'tree',
        treeName: 'P_SYS_DEPT_TREE',
      },
    });
    if (result.code == '200') {
      paramsData = result.data;
      treeViewName = paramsData.treeView;
      getTreeData(paramsData.treeView);
    }
    console.log('请求参数-----', result);
  };

  // 请求根节点数据
  const getTreeData = async (treeViewName: string) => {
    const result = await useHttp({
      params: {
        ...commonApi().system.getGetTreeRootDataList.params,
        loadAll: true,
        treeViewName, //'SysGroupTreeView', //treeName,
      },
      url: commonApi().system.getGetTreeRootDataList.url,
      method: commonApi().system.getGetTreeRootDataList.method,
    });
    if (result.code == '200') {
      data.treeData = formatData((result.data && result.data.rootData) || []);
      data.treeData[0].isLeaf = false;
      filterFlag = (result.data && result.data.filterFlag) || [];
      if (data.treeData.length > 0) {
        onSelect &&
          onSelect({
            data: {
              node: {
                dataRef: data.treeData[0],
              },
            },
          });
      }
    }
  };

  // 格式化树节点的数据
  function formatData(dataList: any[]) {
    const myData: any[] = [];
    for (const dataListElement of dataList) {
      const child = { ...dataListElement };
      //child.key = dataListElement.value1 || dataListElement.value3;
      child.key = dataListElement.key || getUuid(16, 16);
      // 判断是否存在子节点的数据
      if (dataListElement.children && dataListElement.children.length > 0) {
        child.children = formatData(dataListElement.children);
      }
      myData.push(child);
    }
    return myData;
  }

  const onExpandLoad = async ({ callback, node }) => {
    const target = node.dataRef || {};

    console.log('需要异步加载的节点', target);

    if (target) {
      const source = await useHttp({
        params: {
          ...commonApi().system.getGetTreeChildDataList.params,
          ...target,
          treeViewName,
          // treeViewName: 'SysGroupTreeView',
          paraList: getParaList(target),
        },
        url: commonApi().system.getGetTreeChildDataList.url,
        method: commonApi().system.getGetTreeChildDataList.method,
      });
      const treeData = (source.data && source.data.childData) || [];
      callback(treeData);
    } else {
      callback([]);
    }
  };

  /** 根据filterFlag，拼凑获取子节点的参数,fliterFlag的类型一共有6种
   * tree_Current_*   获取当前节点的指定属性
   * tree_Parent_*    获取当前节点的父节点的指定属性
   * tree_root_*      获取当前节点所属根节点的指定属性
   * tree_current_Tag_*  获取当前节点某个属性对象的指定属性
   * tree_Parent_tag_*    获取当前节点所属父节点某个属性对象的指定属性
   * tree_Root_tag_*     获取当前节点所属根节点某个属性对象的指定属性
   * */
  const getParaList = (nodeData: ITreeNode | undefined) => {
    if (!nodeData) return;
    const paraObj = {};
    for (let i = 0; i < filterFlag.length; i++) {
      const rulerList = filterFlag[i].toLowerCase().split('_');
      const value = getObjectData(nodeData, rulerList);
      paraObj[filterFlag[i]] = [value];
    }
    return JSON.stringify(paraObj);
  };

  const getObjectData = (nodeData: ITreeNode, rulerList: string[]) => {
    if (rulerList.length < 3) return null;
    let node: ITreeNode | undefined = nodeData;
    if (rulerList[1] == 'parent') {
      // 获取当前节点的父节点
      node = treeRef.value?.getParentNode(nodeData);
    } else if (rulerList[1] == 'root') {
      // 获取当前节点的根节点
      node = treeRef.value?.getRootNode(nodeData);
    }
    if (!node) return '';
    if (rulerList.length == 4) {
      return node[rulerList[2]][rulerList[3]] || '';
    } else {
      return node[rulerList[2]] || '';
    }
  };

  // 设置link数据
  const setPageLink = (node: ITreeNode) => {
    const key = node.value3 || '';
    // 通过value3获取在link中的键值
    const linkKey = paramsData.page[key] || '';
    const linkObj: { pageLinkList: any[] } = paramsData.link[linkKey] || { pageLinkList: [] };
    const items = analyPageLink(linkObj.pageLinkList);
    tabData!.items = items;
    tabData!.activeKey = items[0].key;
  };

  // 解析pageLink
  const analyPageLink = (list: any[]) => {
    const items: any[] = list.map(v => {
      return {
        key: v.pageName,
        tab: v.name,
        closable: false,
      };
    });
    return items;
  };

  return {
    formatData,
    getParams,
    getTreeData,
    onExpandLoad,
    setPageLink,
  };
}

export function useTableMethods() {
  // 初始化列表
  const initTable = (activeKey: string, currNode: ITreeNode) => {
    if (!activeKey) return { listView: '', menuName: '' };
    const key = currNode.value3 || '';
    // 通过value3获取在link中的键值
    const linkKey = paramsData.page[key] || '';
    const linkObj: { pageLinkList: any[] } = paramsData.link[linkKey] || { pageLinkList: [] };
    const currentPageLink = linkObj.pageLinkList.find(item => item.pageName === activeKey) || {
      paraList: [],
    };
    const result = { listView: '', menuName: '' };
    for (const para of currentPageLink.paraList) {
      if (['listView', 'menuName'].includes(para.name)) {
        result[para.name] = para.value;
      }
    }
    return result;
  };

  // 获取路由参数
  const getRouterParams = (data, name) => {
    for (let i = 0; i < data.length; i++) {
      if (data[i]?.name == name) {
        return data[i];
      }

      if (data[i]?.children && data[i]?.children.length) {
        const val = getRouterParams(data[i].children, name);
        if (val) return val;
      }
    }
  };

  return { initTable, getRouterParams };
}
