import { unref, nextTick, createVNode, render, Ref } from "vue";
import { isObject, isString } from "lodash-es";
import type { VNode } from "vue";
import type {
  DynamicTableProps,
  DynamicTableEmitFn,
  autoColsItem,
} from "../dynamic-table";
import type { OnChangeCallbackParams, TableColumn } from "../types/";
import type { TableState, Pagination } from "./useTableState";
import type {
  orderParamaItem,
  optionItem,
  tdStyle,
  queryGroup,
} from "../types/table";
import ltRest from "lt-request"; //基础数据请求方法
export type TableMethods = ReturnType<typeof useTableMethods>;
import { queryParamAdapter, getFixedCols } from "./commonMethods";
import colFilter from "../components/col-filter.vue";
import type { cloumnFilterItem } from "../dynamic-table";
import { isArray, isTreeTableData, isBoolean } from "../../../../utils/is";
import * as signalR from "@microsoft/signalr";
import { useEditable } from "./useEditable";
import { i18n } from "../../../../locales/index";

const LtRest = new ltRest();
let currentHeight = 0; //当前需要滚动的高度
let queryGroupData = {
  ScruSubcribeId: "",
  MethonParam: "",
  ServiceMethod: "",
  Headers: {
    token: "",
  },
} as queryGroup;
let localconnection: signalR.HubConnection;

export type UseTableMethodsContext = {
  state: TableState;
  props: DynamicTableProps;
  emit: DynamicTableEmitFn;
  lastCurrentKey: number;
  currentKey: Ref<number>;
  visible: Ref<boolean>;
  currentRowData: Ref<Recordable>;
};

let retryFetchCount = 2;

export const useTableMethods = ({
  state,
  props,
  emit,
  lastCurrentKey,
  currentKey,
  visible,
  currentRowData,
}: UseTableMethodsContext) => {
  let filterParmasLocal = {}; //本地模糊查询参数
  let filterParmas = {}; //动态模糊查询参数
  let tableID = ""; //表格ID参数
  //let originTableHeight = 0;
  let originTableData: any = []; //存储外部给的原始数据，用来进行模糊查询过滤
  let isCleanFilterWithLoad = true;
  let lastFilterParama = {}; //用于记录上一次模糊查询参数
  let queryOrderParam = [] as orderParamaItem[]; //查询参数
  let isUnion = false; //是否是联合查询模式
  let hadleTimeOut: NodeJS.Timeout | null = null;
  let localQueryID: string;
  let complexQueryCondition = [] as optionItem[]; //由高级查询控件传递过来的基础组件信息
  let allTableData: any = [];

  const {
    innerPropsRef,
    tableData,
    loadingRef,
    queryFormRef,
    paginationRef,
    editFormErrorMsgs,
  } = state;

  const editableMethods = useEditable({ state, props });

  const setProps = (props: Partial<DynamicTableProps>) => {
    innerPropsRef.value = { ...unref(innerPropsRef), ...props };
  };

  const getComponent = (comp: VNode | string) => {
    return isString(comp) ? <>{comp}</> : comp;
  };

  /**
   * @description 表格查询
   */
  const handleSubmit = (params, page = 1) => {
    params.page = page;
    getTableData(params);
  };

  /**
   * @param {object} params 表格查询参数
   * @param {boolean} flush 是否将页数重置到第一页
   * @description 获取表格数据
   */
  const fetchData = async (params = {}, rest?: OnChangeCallbackParams) => {
    // 如果用户没有提供dataSource并且dataRequest是一个函数，那就进行接口请求
    const [pagination] = rest || [];

    if (
      Object.is(props.dataSource, undefined) &&
      Object.prototype.toString.call(props.dataRequest).includes("Function")
    ) {
      //外部有函数传进来，则用外部函数取数
      getTableDataBuOut(props, pagination, params, rest);
    } else if (isArray(props.dataSource)) {
      originTableData = props.dataSource;
      let queryParamas = {};
      if (queryFormRef.value) {
        const values = await queryFormRef.value.validate();
        queryParamas = {
          ...queryFormRef.value.handleFormValues(values),
          ...queryParamas,
        };
      }
      tableData.value = [];
      let tempData = [] as any[];
      const complexParama = formatQueryParama(); //将复杂条件查询参数进行扁平化处理

      queryParamas = Object.assign(
        queryParamas,
        filterParmasLocal,
        complexParama
      );
      if (props.columnFilter.length) {
        //非树形表格过滤
        if (
          Object.is(props.childrenColumnName, undefined) &&
          !isTreeTableData(originTableData)
        ) {
          for (const i in props.dataSource) {
            const d = props.dataSource[i];
            let ok = true; //筛选成功标识
            for (const j in queryParamas) {
              const queryParam = queryParamas[j];
              if (queryParam && queryParam != "") {
                if ((d[j] + "").indexOf(queryParam) == -1) ok = false;
              }
            }
            if (ok) tempData.push(d);
          }
        } else {
          //树形表格过滤方式
          for (const k in queryParamas) {
            const temp = {};
            temp[k] = queryParamas[k];
            if (queryParamas[k] != "" && queryParamas[k] != null) {
              tempData = formatTreeData(tempData, temp);
            }
            //从过滤列中逐一排查
          }
        }
      } else {
        tempData = props.dataSource;
      }
      //如果有排序的话，则要处理排序
      tempData = setDataOrder(tempData);

      if (props.dataFilter) {
        tableData.value = setTableKey(props.dataFilter(tempData));
      } else {
        tableData.value = setTableKey(tempData);
      }
    }
    setCellTtitle(tableID);
    setSuccessData(tableData.value);

    initColumnFilter(tableID, props);
    return tableData;
  };

  const getTableDataBuOut = async function (
    props,
    pagination,
    params,
    rest?: OnChangeCallbackParams
  ) {
    await nextTick();
    if (queryFormRef.value) {
      const values = await queryFormRef.value.validate();
      params = {
        ...queryFormRef.value.handleFormValues(values),
        ...params,
      };
    }
    const _pagination = unref(paginationRef)!;
    // 是否启用了分页
    const enablePagination = isObject(_pagination);
    const queryParams = {
      ...params,
    };
    if (enablePagination) {
      Object.assign(queryParams, {
        page: !isBoolean(_pagination) ? _pagination.current : 1,
        limit: !isBoolean(_pagination) ? _pagination.pageSize : 25,
        ...queryParams,
      });
    }
    let condition = formatCondition();
    condition = condition.concat(complexQueryCondition); //将复杂条件合并到查询条件中
    //目前只处理2和3的情况 0和1 其他情况下，默认不做处理
    if (props.remoteQueryMode == 2) {
      const temp = {
        Conditions: condition,
        OrderParam: [] as orderParamaItem[],
      };
      if (queryOrderParam.length > 0) {
        temp.OrderParam = queryOrderParam;
      }
      Object.assign(queryParams, temp);
    } else if (props.remoteQueryMode == 3) {
      const temp = {
        Request: {
          Conditions: condition,
          OrderParam: [] as orderParamaItem[],
        },
      };
      if (queryOrderParam.length > 0) {
        temp.Request.OrderParam = queryOrderParam;
      }
      Object.assign(queryParams, temp);
    }
    Object.assign(queryParams, props.queryParams);
    loadingRef.value = true;
    const data = await props
      ?.dataRequest?.(queryParams, rest)
      .finally(() => (loadingRef.value = false));
    // data.Datas = data.list
    if (data?.pagination) {
      const { page, size, total } = data.pagination;
      if (!isBoolean(_pagination)) {
        if (enablePagination && _pagination?.current && retryFetchCount-- > 0) {
          // 有分页时,删除当前页最后一条数据时 自动往前一页查询
          if (
            (data?.Datas.length === 0 || data[props.dataName].length == 0) &&
            total > 0 &&
            page > 1
          ) {
            _pagination.current--;
            return reload();
          }
        }
      }
      updatePagination({
        current: page,
        pageSize: size,
        total,
      });
    } else {
      updatePagination(pagination);
    }

    let tempData = [] as any[];
    if (Array.isArray(data?.Datas)) {
      tempData = data!.Datas;
    } else if (Array.isArray(data)) {
      tempData = data;
    } else if (props.dataName) {
      if (typeof data != "undefined") {
        tempData = data[props.dataName];
      } else {
        tempData = [];
      }
    } else {
      tempData = [];
    }
    if (props.dataFilter) {
      tableData.value = setTableKey(props.dataFilter(tempData));
    } else {
      tableData.value = setTableKey(tempData);
    }
    if (Array.isArray(data?.list)) {
      tableData.value = setTableKey(data!.list);
    } else if (Array.isArray(data)) {
      tableData.value = setTableKey(data);
    } else {
      tableData.value = [];
    }
  };

  const setDataOrder = function (data) {
    //如果没有排序参数，则返回原本值
    if (queryOrderParam.length == 0) {
      return data;
    }
    let sorrtedArray = [];
    for (let i = 0; i < queryOrderParam.length; i++) {
      const fieldName = queryOrderParam[i].OrderByFieldName as string;
      const orderType = queryOrderParam[i].OrderType;
      //正序
      sorrtedArray = data.sort((n1, n2) => {
        if (isDataTime(fieldName)) {
          return Date.parse(n1[fieldName]) - Date.parse(n2[fieldName]);
        } else {
          return n1[fieldName] - n2[fieldName];
        }
      });
      if (orderType == "Descending") {
        //如果是倒序，则需要对数据进行翻转
        sorrtedArray = sorrtedArray.reverse();
      }
    }
    return sorrtedArray;
  };

  const isDataTime = function (field) {
    //取出列中的类型
    let bRet = false;
    const target =
      props.columns.length > 0
        ? props.columns.filter((item) => {
            return item.dataIndex == field;
          })
        : props.autoClumns
        ? props.autoClumns?.filter((item) => {
            return item.dataIndex == field;
          })
        : [];
    if (target.length > 0) {
      if ((target[0].Style as string).toLowerCase() == "datetime") {
        bRet = true;
      } else {
        bRet = false;
      }
    }

    return bRet;
  };

  const formatQueryParama = function () {
    const tempParama = {} as any;
    if (complexQueryCondition.length == 0) {
      return tempParama;
    }
    for (let i = 0; i < complexQueryCondition.length; i++) {
      tempParama[complexQueryCondition[i].Key] = complexQueryCondition[i].Value;
    }
    return tempParama;
  };

  const formatTreeData = function (treeData, searchValue) {
    //树形表格过滤方法
    if (!treeData || treeData.length === 0) {
      return [];
    }
    const array = [] as any[];
    const key = Object.keys(searchValue)[0];
    for (let i = 0; i < treeData.length; i += 1) {
      let match = false;
      for (const pro in treeData[i]) {
        let targetVal = "";
        if (treeData[i][pro]) {
          targetVal = treeData[i][pro].toString().toLowerCase();
        }
        match =
          pro == key &&
          (treeData[i][pro] == searchValue[key] ||
            targetVal.indexOf(searchValue[key].toLowerCase()) != -1);
        if (match) break;
      }
      if (
        formatTreeData(treeData[i].children, searchValue).length > 0 ||
        match
      ) {
        array.push({
          ...treeData[i],
          children: formatTreeData(treeData[i].children, searchValue),
        });
      }
    }
    return array;
  };
  const formatCondition = function () {
    const temp = { Key: "", Value: "" };
    const condition = [] as optionItem[];
    for (const i in filterParmas) {
      temp.Key = i;
      temp.Value = filterParmas[i];
      const copy1 = {} as optionItem;
      $.extend(true, copy1, temp);
      let filterItem = {} as cloumnFilterItem;
      for (let k = 0; k < props.columnFilter.length; k++) {
        const field = props.columnFilter[k];
        if (typeof field == "object") {
          if (field[k].prop == i) {
            filterItem = field[k];
          }
          break;
        } else if (typeof field == "string") {
          if (field[k] == i) {
            filterItem.prop = field[k];
          }
          break;
        }
      }
      if (filterItem.prop == undefined) {
        copy1.MatchCase = "Like"; //如果不配置的话，默认是模糊查询
      } else {
        copy1.MatchCase = filterItem.MatchCase ? filterItem.MatchCase : "Like";
      }
      condition.push(copy1);
    }
    //将复杂条件查询参数合并进来
    return condition;
  };
  /**
   * @param {object} params 表格查询参数
   * @description 通过内置函数，获取表格数据
   */
  const fetchDataByURL = async (params = {}) => {
    let request: any;
    let queryParams = {
      ...params,
    };
    //将外部查询参数插入进来
    if (queryFormRef.value) {
      //将表单的查询参数插入进来
      const values = await queryFormRef.value.validate();
      queryParams = {
        ...queryFormRef.value.handleFormValues(values),
        ...queryParams,
      };
    }
    Object.assign(queryParams, props.queryParams); //外部参数先带进来

    if (Object.keys(filterParmas).length == 0) {
      if (props.columnFilter.length > 0) {
        const tempValue = {};
        const temp = props.columnFilter;
        for (let i = 0; i < temp.length; i++) {
          const item = temp[i];
          if (typeof item == "string") {
            tempValue[item] = "";
          } else if (typeof item == "object") {
            if (typeof item.prop != "undefined") {
              if (item.defaultValue) {
                tempValue[item.prop] = item.defaultValue;
              } else {
                tempValue[item.prop] = "";
              }
            }
          }
        }
        filterParmas = Object.assign(filterParmas, tempValue);
      }
    }

    switch (props.remoteQueryMode) {
      case 0: {
        if (props.ifMonitor) {
          queryGroupData = {
            ScruSubcribeId: localQueryID, //请求ID
            MethonParam: JSON.stringify(queryParams),
            ServiceMethod: props.url ? props.url : "",
            Headers: { token: props.accessToken ? props.accessToken : "" },
          };
          if (localconnection) {
            if (localconnection.state === "Connected") {
              localconnection.send(props.queryMethods, queryGroupData);
            }
          }
        } else {
          emit("get-query-data", queryParams);
          request = LtRest.get(props.url, {
            params: queryParams,
          });
        }
        break;
      }
      case 1: {
        if (props.ifMonitor) {
          queryGroupData = {
            ScruSubcribeId: localQueryID, //请求ID
            MethonParam: JSON.stringify(queryParams),
            ServiceMethod: props.url ? props.url : "",
            Headers: { token: props.accessToken ? props.accessToken : "" },
          };
          if (localconnection) {
            if (localconnection.state === "Connected") {
              localconnection.send(props.queryMethods, queryGroupData);
            }
          }
        } else {
          emit("get-query-data", queryParams);
          request = LtRest.post(props.url, queryParams);
        }
        break;
      }
      case 2: {
        const mixParams = {
          Conditions: [] as optionItem[],
          OrderParam: [] as orderParamaItem[],
        };
        if (queryOrderParam.length) {
          mixParams.OrderParam = queryOrderParam;
        }
        const temp = { Key: "", Value: "" };
        for (const i in filterParmas) {
          temp.Key = i;
          temp.Value = filterParmas[i];
          const copy1 = {} as optionItem;
          $.extend(true, copy1, temp);
          const MyIndex = mixParams.Conditions.map((item) => item.Key).indexOf(
            temp.Key
          );
          let filterItem = {} as cloumnFilterItem;
          for (let k = 0; k < props.columnFilter.length; k++) {
            const field = props.columnFilter[k];
            if (typeof field == "object") {
              if (field.prop == i) {
                filterItem = field;
              }
              break;
            } else if (typeof field == "string") {
              if (field == i) {
                filterItem.prop = field;
                break;
              }
            }
          }
          if (isArray(copy1.Value)) {
            //兼容多选情况
            copy1.MatchCase = "In";
            copy1.Value = copy1.Value.join(";"); //将数组转换成字符串
          } else if (isBoolean(copy1.Value)) {
            //如果类型是bool的话，则默认使用equal
            copy1.MatchCase = "Equal";
          } else {
            copy1.MatchCase = filterItem.MatchCase
              ? filterItem.MatchCase
              : "Like";
          }
          if (MyIndex < 0) {
            mixParams.Conditions.push(copy1);
          } else {
            mixParams.Conditions[MyIndex].Value = temp.Value;
          }
        }
        Object.assign(mixParams.Conditions, complexQueryCondition); //将高级查询组件的数据拼接进来
        Object.assign(mixParams, queryParams);
        const autoParams = queryParamAdapter(
          mixParams,
          props,
          unref(paginationRef)
        );
        if (props.ifMonitor) {
          queryGroupData = {
            ScruSubcribeId: localQueryID, //请求ID
            MethonParam: JSON.stringify(autoParams),
            ServiceMethod: props.url ? props.url : "",
            Headers: { token: props.accessToken ? props.accessToken : "" },
          };
          if (localconnection) {
            if (localconnection.state === "Connected") {
              localconnection.send(props.queryMethods, queryGroupData);
            }
          }
        } else {
          emit("get-query-data", autoParams);
          request = LtRest.post(props.url, autoParams);
        }
        break;
      }
      case 3: {
        const mixParams = {
          Request: {
            Conditions: [] as optionItem[],
            OrderParam: [] as orderParamaItem[],
          },
        };
        if (queryOrderParam.length) {
          mixParams.Request.OrderParam = queryOrderParam;
        }
        const temp = { Key: "", Value: "" };
        for (const i in filterParmas) {
          temp.Key = i;
          temp.Value = filterParmas[i];
          const copy1 = {} as optionItem;
          $.extend(true, copy1, temp);
          const MyIndex = mixParams.Request.Conditions.map(
            (item) => item.Key
          ).indexOf(temp.Key);
          let tempItem = {} as cloumnFilterItem;

          for (let k = 0; k < props.columnFilter.length; k++) {
            const field = props.columnFilter[k];
            if (typeof field == "object") {
              if (field.prop == i) {
                tempItem = field;
              }
              break;
            } else if (typeof field == "string") {
              if (field == i) {
                tempItem.prop = field;
                break;
              }
            }
          }
          if (isArray(copy1.Value)) {
            //兼容多选情况
            copy1.MatchCase = "In";
            copy1.Value = copy1.Value.join(";"); //将数组转换成字符串
          } else if (isBoolean(copy1.Value)) {
            //如果类型是bool的话，则默认使用equal
            copy1.MatchCase = "Equal";
          } else {
            copy1.MatchCase = tempItem.MatchCase ? tempItem.MatchCase : "Like";
          }

          if (MyIndex < 0) {
            mixParams.Request.Conditions.push(copy1);
          } else {
            mixParams.Request.Conditions[MyIndex].Value = temp.Value;
          }
        }
        Object.assign(mixParams.Request.Conditions, complexQueryCondition);
        Object.assign(mixParams, queryParams);
        const autoParams = queryParamAdapter(
          mixParams,
          props,
          unref(paginationRef)
        );
        if (props.ifMonitor) {
          queryGroupData = {
            ScruSubcribeId: localQueryID, //请求ID
            MethonParam: JSON.stringify(autoParams),
            ServiceMethod: props.url ? props.url : "",
            Headers: { token: props.accessToken ? props.accessToken : "" },
          };
          if (localconnection) {
            if (localconnection.state === "Connected") {
              localconnection.send(props.queryMethods, queryGroupData);
            }
          }
        } else {
          emit("get-query-data", autoParams);
          request = LtRest.post(props.url, autoParams);
        }
        break;
      }
    }
    if (!request) {
      return;
    }
    await request.then(function (data) {
      //@ts-ignore
      Object.assign(unref(paginationRef), {
        total: data.Total,
      });

      let tempData = [];
      if (props.dataName == undefined) {
        if (typeof data.Datas == "undefined") {
          tempData = data;
        } else {
          tempData = data.Datas;
        }
      } else {
        tempData = data[props.dataName];
      }
      //如果注册了数据过滤事件，则先对数据进行处理
      if (props.dataFilter) {
        tableData.value = setTableKey(props.dataFilter(tempData));
      } else {
        tableData.value = setTableKey(tempData);
      }
    });
    setCellTtitle(tableID);
    setSuccessData(tableData.value);

    return tableData;
  };

  const getAllTableData = async (params = {}) => {
    let request: any;
    let queryParams = {
      ...params,
    };
    //将外部查询参数插入进来
    if (queryFormRef.value) {
      //将表单的查询参数插入进来
      const values = await queryFormRef.value.validate();
      queryParams = {
        ...queryFormRef.value.handleFormValues(values),
        ...queryParams,
      };
    }
    Object.assign(queryParams, props.queryParams); //外部参数先带进来

    if (Object.keys(filterParmas).length == 0) {
      if (props.columnFilter.length > 0) {
        const tempValue = {};
        const temp = props.columnFilter;
        for (let i = 0; i < temp.length; i++) {
          const item = temp[i];
          if (typeof item == "string") {
            tempValue[item] = "";
          } else if (typeof item == "object") {
            if (typeof item.prop != "undefined") {
              if (item.defaultValue) {
                tempValue[item.prop] = item.defaultValue;
              } else {
                tempValue[item.prop] = "";
              }
            }
          }
        }
        filterParmas = Object.assign(filterParmas, tempValue);
      }
    }

    switch (props.remoteQueryMode) {
      case 0: {
        if (props.ifMonitor) {
          queryGroupData = {
            ScruSubcribeId: localQueryID, //请求ID
            MethonParam: JSON.stringify(queryParams),
            ServiceMethod: props.url ? props.url : "",
            Headers: { token: props.accessToken ? props.accessToken : "" },
          };
          if (localconnection) {
            if (localconnection.state === "Connected") {
              localconnection.send(props.queryMethods, queryGroupData);
            }
          }
        } else {
          emit("get-query-data", queryParams);
          request = LtRest.get(props.url, {
            params: queryParams,
          });
        }
        break;
      }
      case 1: {
        if (props.ifMonitor) {
          queryGroupData = {
            ScruSubcribeId: localQueryID, //请求ID
            MethonParam: JSON.stringify(queryParams),
            ServiceMethod: props.url ? props.url : "",
            Headers: { token: props.accessToken ? props.accessToken : "" },
          };
          if (localconnection) {
            if (localconnection.state === "Connected") {
              localconnection.send(props.queryMethods, queryGroupData);
            }
          }
        } else {
          emit("get-query-data", queryParams);
          request = LtRest.post(props.url, queryParams);
        }
        break;
      }
      case 2: {
        const mixParams = {
          Conditions: [] as optionItem[],
          OrderParam: [] as orderParamaItem[],
        };
        if (queryOrderParam.length) {
          mixParams.OrderParam = queryOrderParam;
        }
        const temp = { Key: "", Value: "" };
        for (const i in filterParmas) {
          temp.Key = i;
          temp.Value = filterParmas[i];
          const copy1 = {} as optionItem;
          $.extend(true, copy1, temp);
          const MyIndex = mixParams.Conditions.map((item) => item.Key).indexOf(
            temp.Key
          );
          let filterItem = {} as cloumnFilterItem;
          for (let k = 0; k < props.columnFilter.length; k++) {
            const field = props.columnFilter[k];
            if (typeof field == "object") {
              if (field.prop == i) {
                filterItem = field;
              }
              break;
            } else if (typeof field == "string") {
              if (field == i) {
                filterItem.prop = field;
                break;
              }
            }
          }
          if (isArray(copy1.Value)) {
            //兼容多选情况
            copy1.MatchCase = "In";
            copy1.Value = copy1.Value.join(";"); //将数组转换成字符串
          } else if (isBoolean(copy1.Value)) {
            //如果类型是bool的话，则默认使用equal
            copy1.MatchCase = "Equal";
          } else {
            copy1.MatchCase = filterItem.MatchCase
              ? filterItem.MatchCase
              : "Like";
          }
          if (MyIndex < 0) {
            mixParams.Conditions.push(copy1);
          } else {
            mixParams.Conditions[MyIndex].Value = temp.Value;
          }
        }
        Object.assign(mixParams.Conditions, complexQueryCondition); //将高级查询组件的数据拼接进来
        Object.assign(mixParams, queryParams);
        const autoParams = queryParamAdapter(
          mixParams,
          props,
          unref(paginationRef),
          "all"
        );
        if (props.ifMonitor) {
          queryGroupData = {
            ScruSubcribeId: localQueryID, //请求ID
            MethonParam: JSON.stringify(autoParams),
            ServiceMethod: props.url ? props.url : "",
            Headers: { token: props.accessToken ? props.accessToken : "" },
          };
          if (localconnection) {
            if (localconnection.state === "Connected") {
              localconnection.send(props.queryMethods, queryGroupData);
            }
          }
        } else {
          emit("get-query-data", autoParams);
          request = LtRest.post(props.url, autoParams);
        }
        break;
      }
      case 3: {
        const mixParams = {
          Request: {
            Conditions: [] as optionItem[],
            OrderParam: [] as orderParamaItem[],
          },
        };
        if (queryOrderParam.length) {
          mixParams.Request.OrderParam = queryOrderParam;
        }
        const temp = { Key: "", Value: "" };
        for (const i in filterParmas) {
          temp.Key = i;
          temp.Value = filterParmas[i];
          const copy1 = {} as optionItem;
          $.extend(true, copy1, temp);
          const MyIndex = mixParams.Request.Conditions.map(
            (item) => item.Key
          ).indexOf(temp.Key);
          let tempItem = {} as cloumnFilterItem;

          for (let k = 0; k < props.columnFilter.length; k++) {
            const field = props.columnFilter[k];
            if (typeof field == "object") {
              if (field.prop == i) {
                tempItem = field;
              }
              break;
            } else if (typeof field == "string") {
              if (field == i) {
                tempItem.prop = field;
                break;
              }
            }
          }
          if (isArray(copy1.Value)) {
            //兼容多选情况
            copy1.MatchCase = "In";
            copy1.Value = copy1.Value.join(";"); //将数组转换成字符串
          } else if (isBoolean(copy1.Value)) {
            //如果类型是bool的话，则默认使用equal
            copy1.MatchCase = "Equal";
          } else {
            copy1.MatchCase = tempItem.MatchCase ? tempItem.MatchCase : "Like";
          }

          if (MyIndex < 0) {
            mixParams.Request.Conditions.push(copy1);
          } else {
            mixParams.Request.Conditions[MyIndex].Value = temp.Value;
          }
        }
        Object.assign(mixParams.Request.Conditions, complexQueryCondition);
        Object.assign(mixParams, queryParams);
        const autoParams = queryParamAdapter(
          mixParams,
          props,
          unref(paginationRef),
          "queryParamAdapter"
        );
        if (props.ifMonitor) {
          queryGroupData = {
            ScruSubcribeId: localQueryID, //请求ID
            MethonParam: JSON.stringify(autoParams),
            ServiceMethod: props.url ? props.url : "",
            Headers: { token: props.accessToken ? props.accessToken : "" },
          };
          if (localconnection) {
            if (localconnection.state === "Connected") {
              localconnection.send(props.queryMethods, queryGroupData);
            }
          }
        } else {
          emit("get-query-data", autoParams);
          request = LtRest.post(props.url, autoParams);
        }
        break;
      }
    }
    if (!request) {
      return;
    }
    await request.then(function (data) {
      //@ts-ignore
      let tempData = [];
      if (props.dataName == undefined) {
        if (typeof data.Datas == "undefined") {
          tempData = data;
        } else {
          tempData = data.Datas;
        }
      } else {
        tempData = data[props.dataName];
      }
      //如果注册了数据过滤事件，则先对数据进行处理
      if (props.dataFilter) {
        allTableData = setTableKey(props.dataFilter(tempData));
      } else {
        allTableData = setTableKey(tempData);
      }
    });
    return allTableData;
  };

  const setTableKey = function (data) {
    if (!isArray(data)) {
      return data;
    }
    for (let i = 0; i < data.length; i++) {
      data[i]._tableKey = i + 1;
    }
    return data;
  };

  /**
   * @description 刷新表格
   */
  const reload = async (resetPageIndex = false) => {
    const pagination = unref(paginationRef);
    if (Object.is(resetPageIndex, true) && isObject(pagination)) {
      if (!isBoolean(pagination)) pagination.current = 1;
    }
    console.log("reload过滤事件中调用");
    return await getTableData();
  };

  /**
   * @description 分页改变
   */
  const handleTableChange = async (...rest: OnChangeCallbackParams) => {
    const [pagination, filters, sorter] = rest;
    filters; //过滤参数
    let params = {};

    if (queryFormRef.value) {
      const values = await queryFormRef.value.validate();
      params = queryFormRef.value.handleFormValues(values);
    }
    //@ts-ignore
    Object.assign(unref(paginationRef), pagination || {});
    //解决排序问题，需要后台独自排序
    if (props.OrderParam.length > 0) {
      //需要比较的字段
      //@ts-ignore
      const targetField = sorter.field;
      //@ts-ignore
      const sortDirection = sorter.order;
      if (isUnion) {
        //如果是联合排序的话，则需要更新排序参数
        const target = queryOrderParam.filter((item) => {
          return item.OrderByFieldName == targetField;
        });
        if (target.length > 0) {
          target[0].OrderType =
            sortDirection == "ascend" ? "Ascending" : "Descending";
        } else {
          const temp = {
            OrderByFieldName: targetField,
            OrderType: sortDirection == "ascend" ? "Ascending" : "Descending",
          };
          queryOrderParam.push(temp);
        }
      } else {
        const temp = {
          OrderByFieldName: targetField,
          OrderType: sortDirection == "ascend" ? "Ascending" : "Descending",
        };
        queryOrderParam = [];
        queryOrderParam.push(temp);
      }
    }
    getTableData(params, rest);
    console.log("handleTableChange过滤事件中调用");
    emit("change", ...rest);
  };

  const handleResizeColumn = (w, col) => {
    if (props.ifResizeCloumn) {
      col.width = w;
    }
    if (props.autoClumns) {
      const targetCol = props.autoClumns.filter((item) => {
        return item.dataIndex == col.dataIndex;
      });
      targetCol[0].width = w;
      initColumnFilter(tableID, props, props.autoClumns);
    } else {
      const targetCol = props.columns.filter((item) => {
        return item.dataIndex == col.dataIndex;
      });
      targetCol[0].width = w;
      initColumnFilter(tableID, props, props.columns);
    }
  };

  // dataIndex 可以为 a.b.c
  // const getDataIndexVal = (dataIndex, record) => dataIndex.split('.').reduce((pre, curr) => pre[curr], record)

  // 获取表格列key
  const getColumnKey = (column: TableColumn) => {
    return (column?.key || column?.dataIndex) as string;
  };

  /**
   * @description当外部需要动态改变搜索表单的值或选项时，需要调用此方法获取dynamicFormRef实例
   */
  const getQueryFormRef = () => queryFormRef.value;

  const getTableData = async (params = {}, rest?: OnChangeCallbackParams) => {
    if (props.url) {
      await fetchDataByURL(params);
    } else {
      await fetchData(params, rest);
    }

    if (props.columnFilter.length) {
      nextTick(() => {
        // setTableHeight(originTableHeight, tableID, 26);
      });
    } else {
      // setTableHeight(originTableHeight, tableID);
    }
  };

  //获取未填充数据之前的原始高度
  const getParentHeight = function (id: string) {
    const targetTableDiv = $("#" + id);
    let divHeight = 200;
    if (targetTableDiv.length) {
      divHeight = targetTableDiv[0].clientHeight;
    }
    tableID = id;
    //originTableHeight = divHeight;
    return divHeight;
  };

  const setTableHeight = function (
    divHeight: number,
    ID: string,
    filterHeight?: number
  ) {
    // @ts-ignore $.find在typescript下会偶尔出现报错信息
    filterHeight;
    const target = $("#" + ID);
    let tempHeight = 0;
    if (target.length) {
      tempHeight = target[0].clientHeight;
    }
    if (tempHeight == 0 && divHeight == 0) {
      return;
    }
    const containerHeight = divHeight == 0 ? tempHeight : divHeight; //采用原始高度去计算
    let searFormHeight = 0; //查询面板高度
    let pageHeight = 0; //翻页组件高度
    let searchBoxHeight = 0; //查询工具栏高度

    if (props.searchBox) {
      //如果有查询，则需要获取查询form的高度
      const searchFromRef = $("#" + ID).find(".table-search-form");
      if (searchFromRef.length) {
        searFormHeight = searchFromRef[0].clientHeight;
      }
    }
    if (props.showToolBar) {
      //如果现实工具栏，则需要获取工具栏的高度
      // const searchBoxRef = $(divs[i]).find('.table-tool-bar');
      searchBoxHeight = 24; //暂时先按照固定高度去计算
    }
    if (!Object.is(props.pagination, false)) {
      pageHeight = 44;
      //如果有分页工具，则需要获取分页的高度 //2022-7-12更新为如果有翻页器，则默认翻页器的高度是56
      // const pageRef = $(ID).find('.ant-pagination');
      // if (pageRef.length) {
      //   pageHeight = pageRef[0].clientHeight + 32; //32是上下margin值
      // }
    }
    const targetTable = $("#" + ID).find(".ant-table-container");
    const tableContent = $("#" + ID).find(".ant-table-content");
    const tableHeight =
      containerHeight - searFormHeight - pageHeight - searchBoxHeight - 10;
    currentHeight = tableHeight;
    if (targetTable.length) {
      targetTable[0].style.height = tableHeight + "px!important";
    }
    if (tableContent.length) {
      tableContent[0].style.height = tableHeight + "px";
    }
  };

  const initColumnFilter = function (
    ID: String,
    props: DynamicTableProps,
    cols?: TableColumn[] | autoColsItem[] | undefined
  ) {
    const { t } = i18n.global;
    //自动生成过滤行信息
    if (props.columnFilter.length == 0) {
      //如果过滤列长度为0，则认为不需要生成过滤行控件
      return;
    }
    const targetTable = $("#" + ID);

    nextTick(() => {
      const tableHeaderEL = targetTable.find(".ant-table-thead").get(0);
      if (tableHeaderEL) {
        const targetTR = targetTable.find(".ant-table-thead").find("tr");
        const tds = targetTR[0].children as HTMLCollectionOf<HTMLElement>; //表头生成的列
        const styles = [] as tdStyle[];
        //@ts-ignore
        for (let i = 0; i < tds.length; i++) {
          const tempStyle = {
            class: tds[i].className, //显示类
            left: tds[i].style.left, //相对左侧位置
            position: tds[i].style.position, //位置属性
            zIndex: tds[i].style.zIndex,
            right: tds[i].style.right,
          };
          const copy = Object.assign(tempStyle);
          styles.push(copy);
        }

        if (targetTR.length > 1 && typeof cols == "undefined") {
          //如果已经存在，并且传递进来的cols为空，则不作任何处理，
          return;
        }
        if (cols) {
          //如果cols不为空，则说明是工具栏调整位置引起的，需要根据新的列信息重新生成界面
          if (targetTR.length > 1) {
            const target = targetTable.find(".filterTR");
            target.remove();
          }
        }

        let columns = cols
          ? cols
          : getFixedCols(
              props.columns.length > 0
                ? props.columns
                : getVisiCols(props.autoClumns)
            ); //列信息(如果有配置列信息，则从列信息中来，如果没有的话，则从自动列中来)
        const columnFilter = props.columnFilter; //过滤信息
        // debugger
        if (columns.length > styles.length) {
          columns = getFixedCols(columns).filter((item) => {
            //@ts-ignore
            return item.Visible == true;
          });
        }
        if (props.showEditInDialog == true) {
          const editCols = columns.filter((item) => {
            return item.dataIndex == "SHOW";
          });
          if (editCols.length == 0) {
            columns.push({
              dataIndex: "SHOW",
              title: t("component.table.show"),
              width: 60,
              align: "center",
              fixed: "right",
            } as TableColumn);
          }
        }

        const app = createVNode(colFilter, {
          columns: columns,
          columnFilter: columnFilter,
          tableID: ID,
          showIndex: props.showIndex,
          rowSelection: props.rowSelection,
          mainParmas: lastFilterParama, //如果是列改变的时候，要把原本输入的信息，进行一个重新赋值
          mainStyle: styles,
          externalQueryParama: props.externalQueryParama,
          showEditInDialog: props.showEditInDialog,
          onColumnFilter: (parama) => {
            lastFilterParama = parama;
            filterParmasLocal = Object.assign(filterParmasLocal, parama);
            filterParmas = Object.assign(filterParmas, parama);
            getTableData(); //模糊查询参数改变的时候，需要重新请求数据
            console.log("onColumnFilter过滤事件中调用");
          },
          onColFilterChange: (parama) => {
            filterParmasLocal = Object.assign(filterParmasLocal, parama);
            $.extend(filterParmas, parama); //把清空后的参数赋值给本地筛选参数
            if (isCleanFilterWithLoad) getTableData();
            console.log("onColFilterChange过滤事件中调用");
            isCleanFilterWithLoad = true; //不管怎么样，都恢复true，因为用户手动点击清空按钮都是需要重新加载数据的
          },
          onCleanFilter: () => {},
        });
        //生成实例节点
        const mountNode = document.createElement("tr");
        mountNode.className = "filterTR";
        mountNode.style.height = "26px";
        render(app, mountNode);
        tableHeaderEL.appendChild(mountNode);
      }
    });
  };

  const getVisiCols = function (Cols?: autoColsItem[]) {
    if (Cols) {
      return Cols.filter((item) => {
        return item.Visible == true;
      });
    } else {
      return [];
    }
  };
  //获取原始排序信息
  const getOrderParama = function () {
    if (props.OrderParam.length < 1) {
      return;
    }
    if (props.dataSource) {
      //本地排序的时候，初始化的时候，不进行数据排序
      return;
    }
    Object.assign(queryOrderParam, props.OrderParam);
  };
  //工具栏中，联合排序功能设计
  const orderChangeByForm = function (value, ifUnion: boolean) {
    if (ifUnion) {
      //如果是联合查询状态，则需要将获取到的数据进行一个整理
      for (const i in value) {
        const temp = {
          OrderByFieldName: i,
          OrderType: value[i][0],
        };
        const copy = {} as orderParamaItem;
        Object.assign(copy, temp);
        queryOrderParam.push(copy);
      }
    } else {
      queryOrderParam = [];
    }
    isUnion = ifUnion;
  };

  const getDataByMonitor = function (connection, queryID: string) {
    localQueryID = queryID;
    localconnection = connection;

    connection.on("SendResult", function (id, serveName, data) {
      if (queryID == id) {
        let tmpData = [];
        const temp = $.parseJSON(data);
        originTableData = temp; //接口请求回来的原始数据
        let resultData = [];
        if (typeof props.dataName == "undefined") {
          if (typeof temp.Datas == "undefined") {
            resultData = Object.assign(resultData, temp);
          } else {
            resultData = Object.assign(resultData, temp.Datas);
          }
        } else {
          resultData = Object.assign(resultData, temp[props.dataName]);
        }

        if (props.dataFilter)
          //是否注册了数据筛选事件，是则先调用数据筛选事件
          tmpData = props.dataFilter(resultData);
        else tmpData = resultData;

        tableData.value = setTableKey(tmpData);
        if (typeof temp.Total != "undefined") {
          //@ts-ignore
          Object.assign(unref(paginationRef), {
            //@ts-ignore
            total: resultData.Total,
          });
        }
        loadingRef.value = false;
        //触发加载成功事件
        // setTableKey(tableData.value);
        setCellTtitle(tableID);
        setSuccessData(tableData.value);
      }
    });
  };

  const setSuccessData = (data) => {
    let dataIndex = 0;
    if (props.selectTypeAfterload == 1) {
      dataIndex = 1;
    } else {
      dataIndex = lastCurrentKey;
    }
    emit("loadSuccess", data, dataIndex);
  };

  const startConect = async (connection, props) => {
    if (hadleTimeOut != null) {
      clearTimeout(hadleTimeOut);
      hadleTimeOut = null;
    }
    await connection
      .start()
      .then(() => {
        console.log("连接");
        if (hadleTimeOut != null) {
          clearTimeout(hadleTimeOut);
          hadleTimeOut = null;
        }

        connection.send(props.queryMethods, queryGroupData);
      })
      .catch(function (err) {
        console.log("connect err", err);
        hadleTimeOut = setTimeout(() => startConect(connection, props), 5000);
      });
  };

  const setCellTtitle = (ID: string) => {
    const target = $("#" + ID);
    const targetCell = target.find(".ant-table-cell");
    for (const i in targetCell) {
      if (targetCell[i].innerText) {
        targetCell[i].title = targetCell[i].innerText;
      }
    }
  };

  /** 编辑表单验证失败回调 */
  const handleEditFormValidate = (name: string[], status, errorMsgs) => {
    // console.log('errorInfo', editFormErrorMsgs);
    if (status) {
      editFormErrorMsgs.value.delete(name.join("."));
    } else {
      editFormErrorMsgs.value.set(name.join("."), errorMsgs);
    }
  };

  /** 更新表格分页信息 */
  const updatePagination = (info: Pagination = paginationRef.value) => {
    if (isBoolean(info)) {
      paginationRef.value = info;
    } else if (isObject(paginationRef.value)) {
      paginationRef.value = {
        ...paginationRef.value,
        ...info,
      };
    }
  };

  const getComplexCondition = function (value) {
    complexQueryCondition = value;
    getTableData();
  };

  const editRowDlgOnOK = (value) => {
    //行编辑弹窗确认事件
    const key = props.rowKey ? (props.rowKey as string) : "_tableKey";
    const target = tableData.value.filter((item) => {
      return item[key] == currentKey.value;
    });
    //替换页面显示数据
    for (const i in value) {
      target[0][i] = value[i];
    }
  };

  const rowClick = function (record, index, currentKey) {
    return {
      onClick: (event) => {
        const key = props.rowKey ? (props.rowKey as string) : "_tableKey";
        currentKey.value = record[key];
        lastCurrentKey = currentKey;
        emit("row-click", record, index, event);
      },
      onDblclick: (event) => {
        emit("row-dblclick", record, index, event);
      },
      onContextmenu: (event) => {
        emit("row-contexmenu", record, index, event);
      },
      // 鼠标移入行
      onMouseenter: (event) => {
        emit("row-mouse-enter", record, index, event);
      },
      onMouseleave: (event) => {
        emit("row-mouse-leave", record, index, event);
      },
    };
  };

  //表头点击事件
  const headerClick = function (columns, index) {
    return {
      onClick: (event) => {
        //表头点击事件
        emit("header-click", columns, index, event);
      },
    };
  };
  //单元格点击事件
  const cellClick = function (cells, index) {
    return {
      onClick: (event) => {
        emit("cell-click", cells, index, event);
      },
      onDblclick: (event) => {
        emit("cell-dblclick", cells, index, event);
      },
      onContextmenu: (event) => {
        emit("cell-contexmenu", cells, index, event);
      },
      onMouseenter: (event) => {
        emit("cell-mouse-enter", cells, index, event);
      }, // 鼠标移入行
      onMouseleave: (event) => {
        emit("cell-mouse-leave", cells, index, event);
      },
    };
  };

  const headerCellClick = function (cells, index) {
    return {
      onClick: (event) => {
        //表头点击事件
        emit("header-cell-click", cells, index, event);
      },
    };
  };

  const showEditDlg = function (record) {
    currentRowData.value = {};
    currentRowData.value = record;
    visible.value = true;
  };
  return {
    ...editableMethods,
    setProps,
    getComponent,
    handleSubmit,
    handleTableChange,
    getColumnKey,
    fetchData,
    getQueryFormRef,
    reload,
    fetchDataByURL,
    getTableData,
    handleResizeColumn,
    setTableHeight,
    getParentHeight,
    initColumnFilter,
    getOrderParama,
    orderChangeByForm,
    currentHeight,
    getDataByMonitor,
    startConect,
    queryGroupData,
    setCellTtitle,
    setSuccessData,
    handleEditFormValidate,
    updatePagination,
    getComplexCondition,
    showEditDlg,
    rowClick,
    headerClick,
    cellClick,
    headerCellClick,
    editRowDlgOnOK,
    currentRowData,
    getAllTableData, //获取所有数据(只是取消分页的限制，其他筛选条件保持不变)
  };
};
