import type { ColStruct } from "../../../hooks/type"

import { cloneDeep } from "lodash-es";


export const formatCols = function (cols: ColStruct[]) {
  //新旧系统类型转换
  return cols.map((item: ColStruct) => {
    if (item.Name) {
      item.title = item.Name;
    } else if (item.NameZH) {
      item.title = item.NameZH;
    }
    if (item.Field) {
      item.dataIndex = item.Field;
    }
    if (item.Width) {
      item.width = item.Width;
    }
    return item;
  })
};

//生成显示列信息
export const formatShowCols = function (
  data: ColStruct[],
  treeid?: string,
  treename?: string,
  childName?: string,
  ifshowAction?: boolean,
  isshowInSearchBox?: boolean
) {
  //treeid 作为ID的字段  需要显示的节点名称  childName以哪个字段作为孩子
  if (data.length == 0) {
    return [];
  }

  const tempArray = [];
  if (data.length > 0) {
    const cols = data.filter((item) => {
      return item.Visible == true;
    });
    for (let i = 0; i < cols.length; i++) {
      if (cols[i].Style.toLowerCase() == "combox") {
        const tempItem = {
          title: cols[i].NameZH,
          dataIndex: cols[i].Field,
          width: cols[i].Width ? cols[i].Width : (cols[i].width ? cols[i].width : NaN),
          resizable: true,
          hideInSearch: cols[i].ifshowInQueryForm ? false : true, //是否生成到最终的查询面板中
          Style: cols[i].Style,
          formItemProps: isshowInSearchBox
            ? {
              component: "Select",
              componentProps: ({ tableInstance }: any) => ({
                options: forMatShowOption(cols[i].Option),
                size: "small",
                allowClear: true,
                onChange() {
                  //console.log("tableInstance", tableInstance?.reload());
                },
              }),
            }
            : "",
          editable: true,
          defaultEditable: false,
          customRender: ({ record }: any) => {
            return _getComBoxlabel(record, cols[i]);
          },
        };
        // const copy = deepClone(tempItem);
        const copy = cloneDeep(tempItem)
        tempArray.push(copy);
      } else if (cols[i].Style.toLowerCase() == "tree") {
        const tempItem = {
          title: cols[i].NameZH,
          dataIndex: cols[i].Field,
          width: cols[i].Width ? cols[i].Width : (cols[i].width ? cols[i].width : NaN),
          resizable: true,
          Style: cols[i].Style,
          formItemProps: isshowInSearchBox
            ? {
              component: "Select",
              componentProps: ({ tableInstance }: any) => ({
                size: "small",
                fieldNames: {
                  label: treename ? treename : "name",
                  value: treename ? treename : "id",
                  options: childName ? childName : "children",
                },
                mode: cols[i].Mode ? cols[i].Mode : "combobox",
                options: cols[i].treeOption ? cols[i].treeOption : [],
                allowClear: true,
                onChange() {
                  console.log("tableInstance", tableInstance?.reload());
                },
              }),
            }
            : "",
          editable: true,
          defaultEditable: false,
          customRender: ({ record }: any) => {
            if (treeid && treename && childName)
              return _getTreeLabel(record, cols[i], treeid, treename, childName);
          },
          hideInSearch: cols[i].ifshowInQueryForm ? false : true,
        };
        const copy = cloneDeep(tempItem)
        tempArray.push(copy);
      } else if (cols[i].Style.toLowerCase() == "checkbox") {
        const tempItem = {
          title: cols[i].NameZH,
          dataIndex: cols[i].Field,
          width: cols[i].Width ? cols[i].Width : (cols[i].width ? cols[i].width : NaN),
          resizable: true,
          formItemProps: isshowInSearchBox
            ? {
              size: "small",
              component: "Checkbox",
              componentProps: ({ tableInstance }: any) => ({
                disabled: !cols[i].isEdit,
                onChange() {
                  console.log("tableInstance", tableInstance?.reload());
                },
              }),
            }
            : "",
          editable: true,
          defaultEditable: false,
          Style: cols[i].Style,
          customRender: ({ record }: any) => {
            return _getCheckBox(record, cols[i]);
          },
          hideInSearch: cols[i].ifshowInQueryForm ? false : true,
        };
        const copy = cloneDeep(tempItem)
        tempArray.push(copy);
      } else {
        const tempItem = {
          title: cols[i].NameZH ? cols[i].NameZH : cols[i].Name,
          dataIndex: cols[i].Field,
          width: cols[i].Width ? cols[i].Width : (cols[i].width ? cols[i].width : NaN),
          resizable: true,
          align: "center",
          hideInSearch: cols[i].ifshowInQueryForm ? false : true, //是否生成到最终的查询面板中
          defaultEditable: true,
          editable: false,
          Style: cols[i].Style,
          formItemProps: isshowInSearchBox
            ? {
              rules: [{ required: false, message: "请输入" + (cols[i].NameZH) }],
              componentProps: () => ({
                component: "Input",
                size: "small",
              }),
            }
            : "",
          editFormItemProps: {
            /** 不继承于 `formItemProps`的属性 */
            extendSearchFormProps: false,
            rules: [{ required: false, message: "请输入" + (cols[i].NameZH) }],
          },
        };
        const copy = cloneDeep(tempItem)
        tempArray.push(copy);
      }
    }
  }

  const _getCheckBox = (record: any, col: ColStruct) => {
    return <a-checkbox checked={record[col.Field]} disabled={true}></a-checkbox>;
  };

  //生成树形表格
  const _getTreeLabel = (record: any, col: ColStruct, treeid: string, treename: string, childName: string) => {
    const showLabel = getShowName(record, col, treeid, treename, childName);
    return getReadOnlyData(showLabel);
  };
  const getReadOnlyData = (data: any) => {
    return <span>{data}</span>;
  };
  //获取树形表格显示字段
  const getShowName = (record: any, col: ColStruct, treeid: string, treename: string, childName: string) => {
    let label = "";
    let option = [...col.treeOption];
    const child = childName ? childName : "children";
    const id = treeid ? treeid : "id";
    const name = treename ? treename : "name";
    while (option.length) {
      const target = option.shift();
      if (target) {
        if (target[child]) {
          if (target[child].length > 0) {
            option = [...option, ...target[child]];
          }
        }
        //@ts-ignore
        if (target[id] == record[col.dataIndex]) {
          label = target[name];
          break;
        }
      }

    }
    return label;
  };
  //定义操作列信息
  const actionItem = {
    title: "操作",
    align: "center",
    width: 200,
    dataIndex: "ACTION",
    fixed: "right",
    actions: ({ record }: any, action: any) => {
      const {
        startEditable,
        cancelEditable,
        isEditable,
        getEditFormModel,
        validateRow,
      } = action;
      return isEditable(record.FormulaId)
        ? [
          {
            label: "保存",
            onClick: async () => {
              const result = await validateRow(record.id);
              // message.loading({
              //   content: "保存中...",
              //   key: record.FormulaId,
              // });
              // console.log("result", result);
              // console.log("保存", getEditFormModel(record.FormulaId));
              // await waitTime(2000);
              // cancelEditable(record.id);
              // message.success({
              //   content: "保存成功!",
              //   key: record.FormulaId,
              //   duration: 2,
              // });
            },
          },
          {
            label: "取消",
            onClick: () => {
              cancelEditable(record.FormulaId);
            },
          },
        ]
        : [
          {
            label: "编辑",
            onClick: () => {
              startEditable(record.FormulaId, record);
            },
          },
        ];
    },
  };
  if (ifshowAction) {
    tempArray.push(actionItem);
  }

  return tempArray;
};

export const forMatShowOption = function (Option: any) {
  for (let i = 0; i < Option.length; i++) {
    Option[i].label = Option[i].label || (Option[i].labelZH)
  }
  return Option
}

const _getComBoxlabel = (record: any, col: ColStruct) => {

  let label = "";
  if (typeof col.Option == "undefined") {
    label = record[col.Field];
    return;
  }

  for (let i = 0; i < col.Option.length; i++) {
    if (col.Option[i].value == record[col.Field]) {
      label = col.Option[i].label;
      break;
    }
  }
  return label;
};

//检查当前用户是否有权限操作
export const hasRight = function (name: string) {
  //@ts-ignore
  if (LtConfig && LtConfig.Relations) {
    //@ts-ignore
    for (let i = 0; i < LtConfig.Relations.length; i++) {
      //@ts-ignore
      if (LtConfig.Relations[i].Relation === name) {
        return true;
      }
    }
  }
  return false;
};

export const GuidID = function () {
  let guid = "";
  for (let i = 1; i <= 32; i++) {
    const n = Math.floor(Math.random() * 16.0).toString(16);
    guid += n;
    if (i == 8 || i == 12 || i == 16 || i == 20) guid += "-";
  }
  return guid;
};

export const decode = function (input: string) {
  const _keyStr =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  let output = "";
  let chr1, chr2, chr3;
  let enc1, enc2, enc3, enc4;
  let i = 0;
  /*eslint-disable*/
  input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
  while (i < input.length) {
    enc1 = _keyStr.indexOf(input.charAt(i++));
    enc2 = _keyStr.indexOf(input.charAt(i++));
    enc3 = _keyStr.indexOf(input.charAt(i++));
    enc4 = _keyStr.indexOf(input.charAt(i++));
    chr1 = (enc1 << 2) | (enc2 >> 4);
    chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
    chr3 = ((enc3 & 3) << 6) | enc4;
    output = output + String.fromCharCode(chr1);
    if (enc3 != 64) {
      output = output + String.fromCharCode(chr2);
    }
    if (enc4 != 64) {
      output = output + String.fromCharCode(chr3);
    }
  }
  output = _utf8_decode(output);
  return output;
};

export const _utf8_encode = function (string: string) {
  string = string.replace(/\r\n/g, "\n");
  let utftext = "";
  for (let n = 0; n < string.length; n++) {
    let c = string.charCodeAt(n);
    if (c < 128) {
      utftext += String.fromCharCode(c);
    } else if (c > 127 && c < 2048) {
      utftext += String.fromCharCode((c >> 6) | 192);
      utftext += String.fromCharCode((c & 63) | 128);
    } else {
      utftext += String.fromCharCode((c >> 12) | 224);
      utftext += String.fromCharCode(((c >> 6) & 63) | 128);
      utftext += String.fromCharCode((c & 63) | 128);
    }
  }
  return utftext;
};

export const _utf8_decode = function (utftext: any) {
  let string = "";
  let i = 0;
  let c = 0;

  let c2 = 0;
  let c3 = 0;
  while (i < utftext.length) {
    c = utftext.charCodeAt(i);
    if (c < 128) {
      string += String.fromCharCode(c);
      i++;
    } else if (c > 191 && c < 224) {
      c2 = utftext.charCodeAt(i + 1);
      string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
      i += 2;
    } else {
      c2 = utftext.charCodeAt(i + 1);
      c3 = utftext.charCodeAt(i + 2);
      string += String.fromCharCode(
        ((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)
      );
      i += 3;
    }
  }
  return string;
};

/*在JS中，浮点数的计算容易丢失精度，使用这四个函数，可以实现浮点数的加减乘除 */
// 两数相除
export const accDiv = function (num1: number, num2: number) {
  let t1, t2, r1, r2;
  try {
    t1 = num1.toString().split(".")[1].length;
  } catch (e) {
    t1 = 0;
  }
  try {
    t2 = num2.toString().split(".")[1].length;
  } catch (e) {
    t2 = 0;
  }
  r1 = Number(num1.toString().replace(".", ""));
  r2 = Number(num2.toString().replace(".", ""));
  return (r1 / r2) * Math.pow(10, t2 - t1);
};
//两数相乘
export const accMul = function (num1: number, num2: number) {
  let m = 0,
    s1 = num1.toString(),
    s2 = num2.toString();
  try {
    m += s1.split(".")[1].length;
  } catch (e) { }
  try {
    m += s2.split(".")[1].length;
  } catch (e) { }
  return (
    (Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) /
    Math.pow(10, m)
  );
};
//两数相加
export const accAdd = function (num1: number, num2: number) {
  var r1, r2, m;
  try {
    r1 = num1.toString().split(".")[1].length;
  } catch (e) {
    r1 = 0;
  }
  try {
    r2 = num2.toString().split(".")[1].length;
  } catch (e) {
    r2 = 0;
  }
  m = Math.pow(10, Math.max(r1, r2));
  return (num1 * m + num2 * m) / m;
};
//两数相减
export const accSub = function (num1: number, num2: number) {
  return accAdd(num1, -num2);
};


export const clearMxTooltip = function () {
  //因为鼠标事件可能异常，因此需要增加防护员
  const tooltips = document.querySelectorAll('.mxTooltip');
  // 遍历所有找到的元素并删除它们
  tooltips.forEach(tooltip => {
    tooltip.remove();
  });
}

export const checkNull = function (value: any) {
  return typeof value === "undefined" || value === null || value === "";
}

// 处理时间格式的公共方法 
export const getLocalDate = function (value: any, showTime?: boolean) {
  if (!value) {
    return null
  }
  let dt = new Date(value);
  let y = dt.getUTCFullYear()
  let m = (dt.getUTCMonth() + 1 + '').padStart(2, '0')
  let d = (dt.getUTCDate() + '').padStart(2, '0')
  let hh = (dt.getUTCHours() + '').padStart(2, '0')
  let mm = (dt.getUTCMinutes() + '').padStart(2, '0')
  let ss = (dt.getUTCSeconds() + '').padStart(2, '0')
  return showTime ? `${y}-${m}-${d} ${hh}:${mm}:${ss}` : `${y}-${m}-${d}`
}