import { Checkbox, Input, Radio, Select, Button as AntdButon, message, Modal, Dropdown, MenuProps } from "antd";
import { cloneDeep, isNil } from "lodash";
import React, { useEffect, useRef, useState } from "react";
import { Button } from "../../../components";
import Dialog from "../../../components/DragModal";
import { Icon } from "../../../components/icons";
import { TranslateFn } from "../../../locale";
import { IColumn } from "../../../store/table";
import { Action } from "../../../types";
interface IProps {
  action: Action;
  onBulkReplace: (rowDataList: RowData[]) => void;
  columns: IColumn[];
  data: obj[];//原始数据
  currentCheckIndex: number;
  selectedList: number[];
  updateActiveCell: (row?: number, col?: string) => void;
  container: HTMLElement | null;
  canReplace: boolean;
  translate: TranslateFn<any>;
}
type InsertType = 'add' | 'reduce'; // 删除 or 增加

interface ISelect {
  label: string;
  value: string;
}
export type RowData = {
  index: number;
  rowData: obj;
  fieldName: string;
  updateValue: string;
}
interface IModify {
  index: number;
  field: string;
}
const matchList = [
  { label: "整个字段", value: "all" },
  { label: "字段的任何部分", value: 'part' },
  { label: "字段的开始部分", value: "start" },
  { label: "字段的结束部分", value: "end" },
]
const redirect = [
  { label: "全部", value: "all" },
  { label: "向上", value: "prev" },
  { label: "向下", value: "next" },
]
const FindAndReplace = (props: IProps) => {
  const { action, data, columns, updateActiveCell, container, onBulkReplace, canReplace, translate } = props;
  const [visible, setVisible] = useState(false);
  const [orderIndex, setOrderIndex] = useState(-1);  // 查找顺序
  const [tabType, setTabType] = useState(0);
  const [replaceCon, setReplaceCon] = useState('');
  const [match, setMatch] = useState('all');
  const [field, setField] = useState<string[]>([]);
  const [fieldList, setFieldList] = useState<ISelect[]>([]);
  const [caseValue, setCaseValue] = useState(false);
  const [rangeValue, setRangeValue] = useState('present');
  const [redirectValue, setRedirectValue] = useState('all');
  const [findCon, setFindCon] = useState('');
  // const [insertData, setInsertData] = useState<string[]>([]);
  // const [insertText, setInsertText] = useState<string>('');
  const [modifyData, setModifyData] = useState<IModify[]>([]);
  const [isChangeRow, setIsChangeRow] = useState(true);

  useEffect(() => {
    const mapList: any[] = [];
    let _fields = columns.map(item => {
      //assign类型不允许替换，新平台貌似是autofill
      if (item.type === 'assign') {

      } else if (item.type === 'mapping' && item['map']) {
        mapList.push({ title: item.name, mapData: item['map'], delimiter: (item as any).delimiter || ',' })
      }
      return {
        value: item.name!,
        label: item.label
      }
    })
    curPageLookupList.current = mapList;
    setFieldList([..._fields]);
  }, [columns])
  useEffect(() => {
    document.addEventListener('keydown', onKeydown, false)
    return () => {
      document.removeEventListener('keydown', onKeydown, false)
    }
  }, [])
  const onKeydown = (e: any) => {
    if (e.keyCode == 112) { // F1
      e.preventDefault();
    }
    // 打开快捷键面板 Ctrl + /
    if (e.keyCode == 191 && (e.ctrlKey || e.metaKey)) {
      e.preventDefault()
    }
    if (e.keyCode === 70 && (e.ctrlKey || e.metaKey) && e.shiftKey) {
      e.preventDefault()
    }
    if (e.keyCode === 70 && (e.ctrlKey || e.metaKey)) {
      e.preventDefault()
      handleAction()
    }
  }
  const curPageLookupList = useRef<obj[]>([]);
  const handleChangeFind = (value: string) => {
    setFindCon(value)
    setModifyData([])
    setOrderIndex(-1)
  }
  let failCount: number = 0; // 失败的个数
  let repalceCount: number = 0; // 总共替换的个数计算
  // 高级替换
  // const seniorReplace = (replaceItem: obj, fieldName: string, originData: obj[], index: number, isAll: boolean = true) => {
  //   let replaceText = replaceCon, findText = findCon;
  //   let isInsert = replaceCon?.indexOf('||') > -1;
  //   // 取插入条件之前的字符
  //   let replaceConBefore = replaceCon?.split('[')?.length > 1 ? replaceCon?.split('[')[0] : '';
  //   // 如果条件之前的字符存在 从原数据中暂时移除
  //   replaceConBefore && (replaceText = replaceCon?.replace(replaceConBefore, ''));
  //   // 增加 or 删除
  //   if (isInsert) {
  //     let isEdit = allowEdit(replaceItem, fieldName, isAll);
  //     if (isEdit) {
  //       try {
  //         if (!caseValue) { // 不区分大小写
  //           replaceItem[fieldName] = replaceItem[fieldName] && String(replaceItem[fieldName]).toLocaleLowerCase();
  //         }
  //         findText = replaceItem[fieldName];
  //         // 需要 增加 or 删除的字符
  //         let content = replaceCon?.split("||")[1]?.replace(/\'/g, '');
  //         if (insertType === 'add') {
  //           replaceText = replaceItem[fieldName] + content;
  //         } else {
  //           replaceText = replaceItem[fieldName].replace(content, '');
  //         }
  //         return replaceFn(fieldName, originData, index, findText, replaceText)
  //       } catch (err) {
  //         failCount++;
  //       }
  //     } else {
  //       failCount++;
  //     }
  //   } else {
  //     if (!caseValue) { // 不区分大小写
  //       replaceItem[fieldName] = replaceItem[fieldName] && String(replaceItem[fieldName]).toLocaleLowerCase();
  //     }
  //     findText = replaceItem[fieldName];
  //     let isEdit = allowEdit(replaceItem, fieldName, isAll);
  //     if (isEdit) {
  //       try {
  //         // 数字格式
  //         // const displayFormat = columns.find(col => col.name === fieldName)?.pristine?.precision || 2;
  //         const result = eval(`${replaceConBefore}${replaceItem[fieldName]}${replaceCon.split(']')[1]}`);
  //         //这里需要格式化
  //         replaceText = result ? String(result) : '';
  //         return replaceFn(fieldName, originData, index, findText, replaceText);
  //       } catch (e) {
  //         failCount++;
  //         !isAll && Modal.error({ content: '运算规则错误' })
  //       }
  //     } else {
  //       failCount++;
  //     }
  //   }
  //   return null;
  // }
  // 真正执行数据替换的方法 单个
  const replaceFn = (field: string, originData: obj[], index: number, findText: string = '', replaceText: string): RowData => {
    let replaceItem = Object.assign({}, data[index]);
    if (match === 'all') {
      replaceItem[field] = replaceText;
    } else if (match === 'part') {
      replaceItem[field] = findText ? String(replaceItem[field]).replace(new RegExp(findText, 'g'), replaceText) : replaceText;
    } else if (match === 'start') {
      replaceItem[field] = findText ? String(replaceItem[field]).replace(findText, replaceText) : replaceText;
    } else if (match === 'end') {
      let subLen = replaceItem[field].length - findText.length + 1;
      replaceItem[field] = findText ? String(replaceItem[field]).substr(0, subLen) + replaceText : replaceText;
    }
    if (String(findText || '') != replaceText) {
      repalceCount++;
    } else {
      failCount++;
    }
    return {
      index, rowData: replaceItem, fieldName: field, updateValue: replaceItem[field]
    }
  }
  // 是否允许编辑
  const allowEdit = (rowData: obj<any>, field: string, isReplaceAll?: boolean) => {
    let colItem = columns.find(item => item.name === field);
    //这里判断列是否可编辑
    if (colItem?.type === 'lion-formula') {
      !isReplaceAll && Modal.warn({ content: '当前字段不支持替换' });
      return false
    } else if (!colItem?.pristine?.quickEdit) {
      !isReplaceAll && Modal.warn({ content: '当前字段不可编辑' });
      return false
    }
    //单元格是否可编辑
    // let cellEdit = true;
    // if (!cellEdit) {
    //   !isReplaceAll && Modal.warn({ content: '当前字段不可编辑' });
    //   return false
    // }
    //列是否可编辑
    // else if (RejectReplaceColumnArr.includes(field)) {
    //   !isReplaceAll && Modal.warn({ content: '当前字段不支持替换' });
    //   return false
    // }
    return true;
  }
  // fieldName caption 互转
  const fieldName2Caption = (get: 'name' | 'label', value: string, colList: IColumn[]): string => {
    return colList?.find(item => item[get === 'name' ? 'label' : 'name'] === value)?.[get]
  }
  // 高级 修改 Insert 的替换内容
  // const handleInsertSetContent = (flag: boolean) => {
  //   let { columns } = props;
  //   let replaceStr = replaceCon;
  //   if (!flag) {
  //     // 如果已经有插入内容 先移除掉之前的插入内容
  //     replaceStr = replaceStr?.indexOf("||'") > -1 ? replaceStr?.split("||'")[0] : replaceStr;
  //     setReplaceCon(`${replaceStr}||'${insertText}'`)
  //   } else {
  //     // 替换所有中文符号 增强兼容性
  //     replaceStr = replaceStr.replace(/\（/g, '(').replace(/\）/g, ')');
  //     // 取插入条件之前的字符
  //     let replaceConBefore = replaceStr?.split('[')?.length > 1 ? replaceStr?.split('[')[0] : '';
  //     // 如果条件之前的字符存在 从原数据中暂时移除
  //     replaceConBefore && (replaceStr = replaceStr.replace(replaceConBefore, ''));
  //     // 移除所有的插入字段
  //     replaceStr = replaceStr?.replace(/\[.*?\]/g, '') || '';
  //     // 是否包含运算符
  //     let hasOperation = /\+|\*|-|\//g.test(replaceStr);
  //     let insertCaptions = `[${insertData?.map(item => fieldName2Caption('label', item, columns))?.toString()}]`;
  //     setReplaceCon(replaceStr ? (hasOperation ? `${replaceConBefore}${insertCaptions}${replaceStr}` : `${replaceConBefore}${insertCaptions}${replaceStr?.indexOf('||') > -1 ? replaceStr : '||' + replaceStr}`) : `${replaceConBefore}${insertCaptions}`);
  //   }
  // }
  // 查找字段
  const handleFindSelect = (value: Array<string>) => {
    setField(value)
    setOrderIndex(-1)
  }
  // 匹配字段
  const handleMatchSelect = (value: string) => {
    setMatch(value)
    setOrderIndex(-1)
  }
  // 区分大小写
  const handleCaseSensitive = (value: boolean) => {
    setCaseValue(value)
    setOrderIndex(-1)
  }
  // 查找范围
  const handleChangeRange = (value: string) => {
    setRangeValue(value)
    setOrderIndex(-1)
  }

  /**
 * 查找内容
 *
 */
  const findReplaceData = (): Promise<{ modifyData: IModify[] }> => {
    return new Promise((resolve, reject) => {
      let { data, selectedList, currentCheckIndex } = props;
      let findContent = findCon, isChangeRowContent = isChangeRow;
      // let fieldNames = replaceCon?.match(/\[(.+?)\]/g)?.[0]?.replace(/\[|]/g, '').split(',') as string[];
      // let replaceFields = fieldNames?.map(item => fieldName2Caption('name', item, columns));
      let originData = cloneDeep(data);
      let tableSelectRow = Number(currentCheckIndex);
      let orderIndex = 0;
      let modifyArr: IModify[] = []; // 查找到的数据
      let isGetOrderIndex = false; // 是否可以获取选中数据索引的指标之一

      const setArr = (index: number, fieldName: string) => {
        // if (Array.isArray(replaceFields) && replaceFields.length > 0) {
        //   replaceFields.forEach(item => {
        //     modifyArr.push(Object.assign({}, { index: index, field: item }));
        //   })
        // } else {
        modifyArr.push(Object.assign({}, { index: index, field: fieldName }));
        // }
        isGetOrderIndex = true;
      }

      // 查找匹配的数据
      if (findContent) {
        originData.map((item, index) => {
          if (rangeValue === 'some' && !selectedList.includes(index)) {
            return
          }
          // 如果查找列字段为空
          if (field === undefined || (field && !field.length)) {
            for (let fieldName of Object.keys(item)) {
              let str = isNil(item[fieldName]) ? undefined : String(item[fieldName]);
              // mapping 取值
              const lookupItem = curPageLookupList.current.find(lookCol => lookCol.title === fieldName);
              if (lookupItem) {
                let options = str?.split(lookupItem.delimiter);
                str = options?.map((opt: string | number) => lookupItem.mapData[opt])?.join(lookupItem.delimiter)
              }
              str = str || '';
              isGetOrderIndex = false;
              if (!caseValue) {
                str = str.toLocaleLowerCase();
                findContent = findContent && findContent.toLocaleLowerCase();
              }
              if (match === 'all') {
                if (str === findContent) {
                  setArr(index, fieldName);
                }
              } else if (match === 'part') {
                if (str.indexOf(findContent) !== -1) {
                  setArr(index, fieldName);
                }
              } else if (match === 'start') {
                if (str.substr(0, findContent.length) === findContent) {
                  setArr(index, fieldName);
                }
              } else if (match === 'end') {
                if (str.substr(-findContent.length, findContent.length) === findContent) {
                  setArr(index, fieldName);
                }
              }
              if (isGetOrderIndex && isChangeRowContent) {
                orderIndex++;
                if (redirectValue !== 'prev') { // 方向不是向上查找的
                  if (tableSelectRow <= index) {
                    orderIndex--;
                    orderIndex = orderIndex === 0 ? -1 : orderIndex;
                    isChangeRowContent = false;
                  }
                } else {// 方向是向上查找的
                  if (tableSelectRow < index) {
                    orderIndex--;
                    isChangeRowContent = false;
                  }
                }
              }
            }
          }
          //  如果查找列字段不为空
          else {
            field.map((fieldName: string) => {
              let str = isNil(item[fieldName]) ? undefined : String(item[fieldName]);
              // mapping 取值
              const lookupItem = curPageLookupList.current.find(lookCol => lookCol.title === fieldName);
              if (lookupItem) {
                let options = str?.split(lookupItem.delimiter);
                str = options?.map((opt: string | number) => lookupItem.mapData[opt])?.join(lookupItem.delimiter)
              }
              str = str || '';
              isGetOrderIndex = false;
              if (!caseValue) {
                str = str.toLocaleLowerCase();
                findContent = findContent && findContent.toLocaleLowerCase();
              }
              if (match === 'all') {
                if (str === findContent) {
                  setArr(index, fieldName);
                }
              } else if (match === 'part') {
                if (str.indexOf(findContent) !== -1) {
                  setArr(index, fieldName);
                }
              } else if (match === 'start') {
                if (str.substr(0, findContent.length) === findContent) {
                  setArr(index, fieldName);
                }
              } else if (match === 'end') {
                if (str.substr(-findContent.length, findContent.length) === findContent) {
                  setArr(index, fieldName);
                }
              }
              if (isGetOrderIndex && isChangeRowContent) {
                orderIndex++;
                if (redirectValue !== 'prev') { // 方向不是向上查找的
                  if (tableSelectRow <= index) {
                    orderIndex--;
                    orderIndex = orderIndex === 0 ? -1 : orderIndex;
                    isChangeRowContent = false;
                  }
                } else {// 方向是向上查找的
                  if (tableSelectRow < index) {
                    orderIndex--;
                    isChangeRowContent = false;
                  }
                }
              }
            })
          }
          return Object.assign({}, item);
        })
      } else {
        // 如果查找内容为空
        originData.map((item, index) => {
          if (rangeValue === 'some' && !selectedList.includes(index)) {
            return
          }
          if (field === undefined || (field && !field.length)) {
            for (let fieldName of Object.keys(item)) {
              let str = item[fieldName];
              isGetOrderIndex = false;
              if((isNil(str) || str === '') && columns.some(column => column.name === fieldName)) {
                setArr(index, fieldName);
              }
              if (isGetOrderIndex && isChangeRowContent) {
                orderIndex++;
                if (redirectValue !== 'prev') { // 方向不是向上查找的
                  if (tableSelectRow <= index) {
                    orderIndex--;
                    orderIndex = orderIndex === 0 ? -1 : orderIndex;
                    isChangeRowContent = false;
                  }
                } else {// 方向是向上查找的
                  if (tableSelectRow < index) {
                    orderIndex--;
                    isChangeRowContent = false;
                  }
                }
              }
            }
          } else {
            field.map((fieldName: string) => {
              let str = item[fieldName];
              isGetOrderIndex = false;
              if(isNil(str) || str === '') {
                setArr(index, fieldName)
              }
              if (isGetOrderIndex && isChangeRowContent) {
                orderIndex++;
                if (redirectValue !== 'prev') { // 方向不是向上查找的
                  if (tableSelectRow <= index) {
                    orderIndex--;
                    orderIndex = orderIndex === 0 ? -1 : orderIndex;
                    isChangeRowContent = false;
                  }
                } else {// 方向是向上查找的
                  if (tableSelectRow < index) {
                    orderIndex--;
                    isChangeRowContent = false;
                  }
                }
              }
            })
          }
        })
      }
      if (orderIndex > 0) {
        setOrderIndex(orderIndex)
      }
      if (isChangeRowContent) {
        setIsChangeRow(false)
      }
      setModifyData(modifyArr)
      resolve({ modifyData: modifyArr })
    })
  }
  /**
 * 查找下一个/上一个
 * @param isReplace  是否是替换 - 调用的该事件
 */
  const handleFindNext = async (isReplace: boolean = false, fieldLength: number = 1, autoFind = false) => {
    let { modifyData } = await findReplaceData();
    let newOrderIndex = orderIndex // 上一个匹配值的下标
    // 判断是否查找到内容
    if (!modifyData.length && !isReplace) {
      !autoFind && message.info({ content: '未查找到相关内容' })
      return false;
    }
    if (!modifyData.length) {
      return false;
    };

    switch (redirectValue) {
      case "all": // 全部
        if (newOrderIndex < modifyData.length - 1) {
          newOrderIndex = newOrderIndex + fieldLength;
        } else {
          newOrderIndex = 0;
        }
        break;
      case "next": // 向下
        if (newOrderIndex < modifyData.length - 1) {
          newOrderIndex = newOrderIndex + fieldLength;
        } else {
          !isReplace && message.info({ content: "已完成搜索" });
          return false;
        }
        break;
      case "prev": // 向上
        if (newOrderIndex > 0) {
          newOrderIndex = newOrderIndex - fieldLength;
        } else {
          !isReplace && message.info({ content: "已完成搜索" })
          return false;
        }
        break;
      default:
        break;
    }
    if (modifyData.length === 1 && orderIndex === newOrderIndex) return;
    setOrderIndex(newOrderIndex)
    newOrderIndex = newOrderIndex > -1 ? newOrderIndex : 0;
    let index = modifyData[newOrderIndex].index;
    let fieldName = modifyData[newOrderIndex].field;
    updateActiveCell(index, fieldName);
    let timer;
    for (let i = 0; i < 20; i++) {
      timer = setTimeout(() => {
        let ketSelect = container?.querySelector(`.active-cell`) as HTMLDivElement;
        if (ketSelect) {
          (ketSelect as any).scrollIntoViewIfNeeded();
          timer = null;
          return;
        }
      }, 300);
    }
  }
  // 单个替换事件
  const replaceHandle = async () => {
    let originData = cloneDeep(data);
    if (replaceCon?.split('||')?.length > 2) {
      Modal.error({ content: '替换内容不合法' })
      return
    }
    if (!modifyData[orderIndex]) {
      handleFindNext();
      return false;
    }
    let { field, index } = modifyData[orderIndex];
    let replaceItem = originData[index];
    let allModify: any[] = [], replaceFields: string[] = [];

    if (replaceCon?.match(/\[(.+?)\]/g)) { // 当前单元格可以编辑才替换
      const result = calcFormula(replaceItem)
      let isEdit = allowEdit(replaceItem, field, false);
      if (isEdit) {
        try {
          if (!caseValue) { // 不区分大小写
            replaceItem[field] = replaceItem[field] && String(replaceItem[field]).toLocaleLowerCase();
          }
          allModify.push(replaceFn(field, originData, index, findCon, eval(result)));
        } catch (error) {
          Modal.error({ content: '替换内容不合法' })
        }
      }
      // replaceFields = fieldNames?.map(item => fieldName2Caption('name', item, columns));
      // 高级的单个替换 也可能需要替换多个单元格
      // replaceFields?.forEach(item => {
      //   const currentModify = seniorReplace(replaceItem, item, originData, index);
      //   let hasCurrentModify = allModify?.find(item => item?.index === currentModify?.index);
      //   if (hasCurrentModify && currentModify) {
      //     const { fieldName, rowData, index } = currentModify;
      //     allModify.forEach(item => {
      //       if (item.index === index) {
      //         item.rowData[fieldName] = rowData[fieldName]
      //       }
      //     })
      //   } else if (currentModify) {
      //     allModify = [...allModify, currentModify]
      //   }
      // })
    } else {
      // 常规
      let isEdit = allowEdit(replaceItem, field, false);
      if (isEdit) {
        if (!caseValue) { // 不区分大小写
          replaceItem[field] = replaceItem[field] && String(replaceItem[field]).toLocaleLowerCase();
        }
        allModify.push(replaceFn(field, originData, index, findCon, replaceCon));
      }
    }
    //这里进行替换的操作
    onBulkReplace(allModify)
    handleFindNext(false, replaceFields.length, true);
  }
  //计算公式
  const calcFormula = (replaceItem: obj) => {
    let fieldNames = replaceCon?.match(/\[(.+?)\]/g) || [];
    const list = fieldNames.map(str => {
      const coName = columns.find((fcol: any) => fcol.label === str.replace('[', '').replace(']', ''))?.name ?? '';
      const value = replaceItem?.[coName]
      return isNil(value) ? 0 : value
    })
    const result = replaceCon.replace(/\[(.*?)\]/g, (match: any) => {
      let index = replaceCon.match(/\[([^\]]*)\]/g)?.indexOf(match) ?? -1;
      if (index !== -1) {
        return list[index]
      }
      return 0;
    });
    return result;
  }
  // 替换全部的事件
  const replaceAllOk = async () => {
    const { data } = props;
    if (replaceCon?.split('||')?.length > 2) {
      Modal.error({ content: '替换内容不合法' })
      return
    }
    const { modifyData } = await findReplaceData();
    repalceCount = 0;
    failCount = 0;
    let allModify: RowData[] = [];
    try {
      modifyData.map(item => {
        let { index, field } = item;
        let replaceItem = Object.assign({}, data[index]);
        // 高级
        if (replaceCon?.match(/\[(.+?)\]/g)) { // 当前单元格可以编辑才替换
          const result = calcFormula(replaceItem)
          let isEdit = allowEdit(replaceItem, field, true);
          if (isEdit) {
            try {
              if (!caseValue) { // 不区分大小写
                replaceItem[field] = replaceItem[field] && String(replaceItem[field]).toLocaleLowerCase();
              }
              allModify.push(replaceFn(field, data, index, findCon, eval(result)));
            } catch (error) {
              failCount++
              Modal.error({ content: '替换内容不合法' })
            }
          } else {
            failCount++
          }
          // const currentModify = seniorReplace(replaceItem, field, originData, index);
          // let hasCurrentModify = allModify?.find(item => item?.index === currentModify?.index);
          // if (hasCurrentModify && currentModify) {
          //   const { fieldName, rowData, index } = currentModify;
          //   allModify?.forEach(item => {
          //     if (item.index === index) {
          //       item.rowData[fieldName] = rowData[fieldName]
          //     }
          //   })
          // } else {
          //   allModify = [...allModify, currentModify!]
          // }
        } else {
          // 常规
          const isEdit = allowEdit(replaceItem, field, true);
          if (isEdit) {
            if (!caseValue) { // 不区分大小写
              replaceItem[field] = replaceItem[field] && String(replaceItem[field]).toLocaleLowerCase();
            }
            const newModify = replaceFn(field, data, index, findCon, replaceCon);
            let flag = false;
            for(let i = allModify.length - 1; i>=0; i--) {
              if(allModify[i].index === newModify.index) {
                flag = true
                allModify[i].rowData = {...allModify[i].rowData, [field]: newModify.updateValue }
              }
            }
            !flag && allModify.push(newModify)
          } else {
            failCount++;
          }
        }
      });
      onBulkReplace(allModify)
    } catch (err) {
      console.error(err)
    }
    Modal.info({ content: '操作成功' })
    // Modal.info({ content: `执行完成，成功替换${repalceCount}处, 失败：${failCount}处` });
  }
  // 替换全部
  const replaceAllHandle = () => {
    Modal.confirm({
      content: `是否全部进行替换`,
      onOk: replaceAllOk,
      okText: translate('confirm'),
      cancelText: translate('cancel')
    })
  }
  const handleMenuClick: MenuProps['onClick'] = ({ key }) => {
    const label = columns.find(item => item.name === key)?.label ?? ''
    const newValue = replaceCon + `[${label}]`;
    setReplaceCon(newValue);
  }
  const handleAction = () => {
    setVisible(true)
  }
  const handleCloseModal = () => {
    updateActiveCell()
    setTabType(0)
    setFindCon('')
    setReplaceCon('')
    setField([])
    setFieldList([])
    setMatch('all')
    setCaseValue(false)
    setRangeValue('present')
    setRedirectValue('all')
    setModifyData([])
    setIsChangeRow(true)
    setVisible(false)
  }
  const renderButton = () => {
    return <Button onClick={handleAction}>
      <Icon icon={action?.icon ?? "#icon-tooltool_autowidth"} className="icon" symbol />
      {action?.label}
    </Button>
  }
  return <>
    {renderButton()}
    {visible &&
      <Dialog
        dialogVisible={visible}
        drag
        canClickBelowDom={true}
        className="findReplace"
        wrapClassName="findReplaceDialog"
        width={466}
        mask={false}
        onCancel={handleCloseModal}
        title={(
          <div className="find-and-replace-tabs">
            <div
              className={["find-and-replace-tab", tabType == 0 ? "active" : null].join(" ")}
              onClick={() => setTabType(0)}
            >查找</div>
            {canReplace && <div
              className={["find-and-replace-tab", tabType == 1 ? "active" : null].join(" ")}
              onClick={() => setTabType(1)}
            >替换
            </div>}
          </div>
        )}
        footer={false}
        centered
        getContainer={() => container || document.body}
      >
        <div className="find-and-replace-pc-wrapper">
          <div className="wrapper-inner">
            <div className="options-con">
              <div className="option-item">
                <div className="name">查找内容</div>
                <Input
                  placeholder="请输入内容"
                  value={findCon}
                  onChange={(e) => handleChangeFind(e.target.value)}
                  maxLength={1000}
                />
              </div>
              {
                !!tabType &&
                <div className="option-item">
                  <div className="name">替换内容</div>
                  <Dropdown
                    menu={{
                      items: columns.map(item => ({ key: item.name, label: item.label, item })) as any,
                      onClick: handleMenuClick
                    }}
                    trigger={['contextMenu']}
                    overlayStyle={{
                      overflow: 'hidden', maxHeight: 300,
                      boxShadow: 'rgba(0, 0, 0, 0.08) 0px 6px 16px 0px, rgba(0, 0, 0, 0.12) 0px 3px 6px -4px, rgba(0, 0, 0, 0.05) 0px 9px 28px 8px',
                    }}
                  >
                    <Input
                      placeholder="请输入内容"
                      value={replaceCon}
                      onChange={(e) => setReplaceCon(e.target.value)}
                    />
                  </Dropdown>
                  {/* <AntdButon
                  onClick={() => handleChangeData({ replaceType: replaceType === 'normal' ? 'senior' : 'normal' })}
                  className="btn-margin">{replaceType === 'normal' ? '高级' : '常规'}</AntdButon> */}
                </div>
              }
              {/* {
              !!tabType && replaceType === 'senior' &&
              <div className="option-item findField">
                <div className="name">插入字段</div>
                <Select
                  placeholder="请选择字段"
                  value={insertData}
                  mode="multiple"
                  options={fieldList}
                  onChange={(e) => handleChangeData({ insertData: e })}
                />
                <AntdButon
                  onClick={() => handleInsertSetContent(true)}
                  disabled={!insertData?.length} className="btn-margin">添加</AntdButon>
              </div>
            }
            {
              !!tabType && replaceType === 'senior' &&
              <div className="option-item findField">
                <div className="name">修改字符</div>
                <Radio.Group style={{ width: 140 }}
                  onChange={(e) => handleChangeData({ insertType: e.target.value })}
                  value={insertType}>
                  {
                    insertList.map(item => <Radio key={item.value} className="radio" value={item.value}>{item.label}</Radio>)
                  }
                </Radio.Group>
                <Input
                  placeholder="请输入"
                  value={insertText}
                  onChange={(e) => handleChangeData({ insertText: e })}
                />
                <AntdButon
                  onClick={() => handleInsertSetContent(false)}
                  disabled={!insertText} className="btn-margin">添加</AntdButon>
              </div>
            } */}
              <div className="option-item findField">
                <div className="name">查找字段</div>
                <Select
                  placeholder="请选择字段,未选择即为查找所有字段"
                  value={field}
                  mode="multiple"
                  options={fieldList}
                  onChange={(e) => handleFindSelect(e)}
                />
              </div>
              <div className="option-item">
                <div className="match-con">
                  <div className="name">匹配</div>
                  <Select
                    placeholder="请选择内容"
                    value={match}
                    options={matchList}
                    onChange={(e) => handleMatchSelect(e)}
                  />
                </div>
                {/* 区分大小写 */}
                <div className="case-sensitive">
                  <Checkbox
                    checked={caseValue}
                    onChange={(e) => handleCaseSensitive(e.target.checked)}
                  >区分大小写</Checkbox>
                </div>
              </div>
              <div className="option-item range-item">
                <div className="name">查找范围</div>
                <Radio.Group
                  onChange={(e) => handleChangeRange(e.target.value)}
                  value={rangeValue}>
                  <Radio key='present' value='present'>当前页数据</Radio>,
                  <Radio key='some' value='some'>选中数据</Radio>,
                  {/* <Radio key='all' value='all'>全部数据</Radio> */}
                </Radio.Group>
              </div>
              <div className="option-item range-item">
                <div className="name">查找方向</div>
                <Radio.Group
                  onChange={(e) => setRedirectValue(e.target.value)}
                  value={redirectValue}>
                  {
                    redirect.map((item, index) =>
                      <Radio key={index} className="radio" value={item.value}>{item.label}</Radio>
                    )
                  }
                </Radio.Group>
              </div>
            </div>
            <div className="btn-con">
              <AntdButon
                className="btn"
                type="primary"
                onClick={() => handleFindNext()}
              >
                查找下一个
              </AntdButon>
              {
                tabType ? (
                  <>
                    <AntdButon
                      className="btn replace-btn"
                      type="default"
                      disabled={replaceCon ? false : true}
                      onClick={replaceHandle}
                    >
                      替换
                    </AntdButon>
                    <AntdButon
                      className="btn replace-btn"
                      type="default"
                      disabled={replaceCon ? false : true}
                      onClick={replaceAllHandle}
                    >
                      替换全部
                    </AntdButon>
                  </>
                ) : null
              }
              <AntdButon className="btn" type="default" onClick={handleCloseModal}>取消</AntdButon>
            </div>
          </div>
        </div>
      </Dialog>}
  </>
}

export default FindAndReplace;