import moment from 'moment';
import React, { useState, useEffect } from 'react';
import { useMount, useUnmount } from 'ahooks';
// import reactComponentDebounce from 'react-component-debounce';
// import '@ant-design/compatible/assets/index.css';
import {
  InputNumber,
  Checkbox,
  DatePicker,
  Input,
  Cascader,
  Select,
  AutoComplete,
  Spin,
  message,
  Form,
} from 'antd-v4';
import * as commonUtils from '@/utils/utils';
import styles from '@/index.less';
import Provinces from '@/assets/provinces.json';
import Cities from '@/assets/cities.json';
import Areas from '@/assets/areas.json';
import commonConfig from '@/utils/config';
import { VirtualKeyboard } from '@/oee/common/oeeKeyBoard';

const FormItem = Form.Item;
const { Option } = Select;
const { TextArea } = Input;
const { Search } = Input;
// const InputNumberA = reactComponentDebounce(500)(InputNumber);
// const InputA = reactComponentDebounce(500)(Input);
// const AutoCompleteA = reactComponentDebounce(50)(AutoComplete);
// const TextAreaA = reactComponentDebounce(500)(TextArea);
const InputNumberA = InputNumber;
const InputA = Input;
const AutoCompleteA = AutoComplete;
const TextAreaA = TextArea;
const { RangePicker, MonthPicker } = DatePicker;

function CommonComponent(props) {
  const [dataValue, setDataValue] = useState(props.dataValue);
  const [enabled, setEnabled] = useState(props.enabled);
  const [showName, setShowName] = useState('');
  const [dropDownData, setDropDownData] = useState([]);
  const [conditonValues, setConditonValues] = useState({});
  const [sFieldName, setSFieldName] = useState(props.showConfig.sName);
  const [bNotEmpty, setBNotEmpty] = useState(props.showConfig.bNotEmpty);
  const [sDropDownType, setSDropDownType] = useState('');
  const [sActiveDisplay, setSActiveDisplay] = useState(true);
  const [pageNum, setPageNum] = useState(0);
  const [totalPageCount, setTotalPageCount] = useState(1);
  const [searchValue, setSearchValue] = useState('');
  const [searchDropDownData, setSearchDropDownData] = useState([]);
  const [searchTotalPageCount, setSearchTotalPageCount] = useState(1);
  const [searchPageNum, setSearchPageNum] = useState(0);
  const [spinState, setSpinState] = useState(false);

  let firstDataIndex = props.showConfig.sName.substring(0, 1);
  const mode = props.showConfig.bMultipleChoice ? 'multiple' : 'default';
  const { bNewRecord } = props.showConfig;
  const max = props.showConfig.sMaxValue;
  const min = props.showConfig.sMinValue;
  const getFieldDecorator = commonUtils.isUndefined(props.form) ? undefined : props.form.getFieldDecorator; /*   字段验证(数据格式:数字)   */
  const floatNum = props.getFloatNum(props.showConfig.sName);
  // const floatPrice = getFloatPrice(floatNum);
  const formItemLayout = commonUtils.isNotEmptyObject(props.formItemLayout) ?
    props.formItemLayout :
    { labelCol: { span: 7 }, wrapperCol: { span: 15 } };
  let isDropdownFilter = false;
  // const V = { value: props.dataValue };
  let mounted = false;
  let dropDownTimer = null;

  useMount(() => {
    mounted = true;
    let showDropDown = [];
    if (props.showConfig.sDropDownType === 'const') {
      showDropDown = commonUtils.isNotEmptyArr(props.showConfig.dropDownData) ? props.showConfig.dropDownData :
        (typeof props.showConfig.showDropDown === 'object') ? props.showConfig.showDropDown : commonUtils.objectToArr(commonUtils.convertStrToObj(props.showConfig.showDropDown));
    } else if (props.showConfig.sDropDownType === 'sql' && !commonUtils.isEmptyArrNew(props.showConfig.dropDownData)) {
      showDropDown = props.showConfig.dropDownData;
    }
    setDropDownData(showDropDown);
  });

  useUnmount(() => {
    mounted = false;
  });

  useEffect(() => {
    if (props.showConfig === undefined || props.showConfig === undefined) return;
    firstDataIndex = props.showConfig.sName.substring(0, 1);
    if (props.showConfig.sDropDownType === 'const') {
      const showDropDown = commonUtils.isNotEmptyArr(props.showConfig.dropDownData) ? props.showConfig.dropDownData :
        (typeof props.showConfig.showDropDown === 'object') ? props.showConfig.showDropDown : commonUtils.objectToArr(commonUtils.convertStrToObj(props.showConfig.showDropDown));
      if (mounted) {
        setDropDownData(showDropDown);
      }
    } else if (props.showConfig.sDropDownType === 'sql' && !commonUtils.isEmptyArr(props.showConfig.dropDownData)) {
      if (mounted) {
        setDropDownData(props.showConfig.dropDownData);
      }
    }

    if (dataValue !== props.dataValue || enabled !== props.enabled || bNotEmpty !== props.showConfig.bNotEmpty || sFieldName !== props.showConfig.sName || showName !== props.showConfig.showName || sDropDownType !== props.showConfig.sDropDownType) {
      if (mounted) {
        setDataValue(props.dataValue);
        setEnabled(props.enabled);
        setSFieldName(props.showConfig.sName);
        setSDropDownType(props.showConfig.sDropDownType);
        setBNotEmpty(props.showConfig.bNotEmpty);
        setShowName(props.showConfig.showName);
      }
    }
  }, [props]);

  const onFocus = () => {
    isDropdownFilter = false;
    setSActiveDisplay(false);
  };

  const onBlur = () => {
    isDropdownFilter = false;
    if (searchValue !== '' && props.showConfig.sDropDownType === 'sql' && commonUtils.isEmptyArr(props.showConfig.dropDownData)) {
      if (!props.showConfig.bCanInput) {
        handleSelectOptionEvent('');
      }
      setSearchPageNum(1);
      setSearchTotalPageCount(1);
      setSearchDropDownData([]);
      setSearchValue('');
      setSpinState(false);
      setSActiveDisplay(true);
    }
  };

  const onDropdownVisibleChange = (open) => {
    if (mounted && open) {
      const conditonValuesNew = props.getSqlCondition(props.showConfig, props.name, props.record);
      const pageNumNew = JSON.stringify(conditonValuesNew) !== JSON.stringify(conditonValues) ? 1 : pageNum === 0 ? 1 : pageNum;
      const totalPageCountNew = conditonValuesNew !== conditonValues ? 1 : totalPageCount;
      if (pageNum === 1 && props.showConfig.sDropDownType === 'sql' && commonUtils.isEmptyArr(props.showConfig.dropDownData)) {
        setSpinState(true);
        getDropDownData(pageNumNew, totalPageCountNew, searchValue);
      }
    } else {
      isDropdownFilter = false;
    }
    if (props.onDropdownVisibleChange !== undefined) {
      if (dropDownData.length === 0 && !bNewRecord) {
        open = false;
      }
      props.onDropdownVisibleChange(open);
    }
  };

  const onDoubleClick = () => {
    const sMemo = props.showConfig.sName;
    const title = props.showConfig.showName;
    if (commonUtils.isNotEmptyObject(sMemo) && sMemo.indexOf('Memo') > -1) {
      const sCurrMemoProps = {
        title,
        name: props.name,
        sValue: props.dataValue,
        sMemoField: sMemo,
        bVisibleMemo: true,
        sRecord: props.record,
        sMemoConfig: props.showConfig,
      };
      props.onSaveState({ sCurrMemoProps });
    }
  };

  const onKeyUp = (e) => {
    if (props.onKeyUp) {
      props.onKeyUp(e);
    }
  };

  // const { onKeyDown } = useDebounceFn(
  //   (e) => {
  //     console.log(1111);
  //     if (props.onKeyDown) {
  //       const { showConfig, record } = props;
  //       props.onKeyDown(e, record, showConfig.sName);
  //     }
  //     if (e.key === 'F10') {
  //       message.info(props.showConfig.sName);
  //     }
  //   },
  //   {
  //     wait: 500,
  //   },
  // );

  const onKeyDown = (e) => {
    if (props.onKeyDown) {
      const { showConfig, record } = props;
      props.onKeyDown(e, record, showConfig.sName);
    }
    if (e.key === 'F10') {
      message.info(props.showConfig.sName);
    }
  };

  // const onKeyDownDiv = (e) => {
  //   if (props.onKeyDown) {
  //     props.onKeyDown(e);
  //   }
  //   if (e.key === 'F10') {
  //     message.info(props.showConfig.sName);
  //   } else {
  //     e.preventDefault();
  //     return false;
  //   }
  // };

  const onContextMenu = (e) => {
    if (enabled && commonUtils.isNotEmptyObject(props) && props.name !== 'master' && commonUtils.isNotEmptyObject(props.showConfig)) {
      const { showConfig, name } = props;
      const { bReadonly } = showConfig;
      if (bReadonly) {
        return;
      }
      e.preventDefault(); /* 阻止浏览器本身的右击事件 */
      if (props.onContextMenu) {
        const { showConfig, record } = props;
        props.onContextMenu(e, record, showConfig, name);
      }
    }
  };

  const onFieldPopupModal = (showConfig, name, open) => {
    if (open) {
      props.onFieldPopupModal(showConfig, name);
    }
  };

  const getSelectProps = () => {
    /*   返回值声明   */
    const obj = {
      showSearch: true,
      onChange: handleSelectOptionEvent,
      filterOption,
      onDropdownVisibleChange,
      onPopupScroll: handlePopupScroll,
      onSearch: handleSearch,
      notFoundContent: spinState ? <Spin /> : '暂无数据',
      onFocus,
      onBlur,
      mode,
    };
    if (props.showConfig.sDropDownType === 'sql') {
      obj.optionLabelProp = 'title';
    }
    if (props.readOnly) {
      obj.readOnly = 'readOnly';
    } else {
      obj.disabled = !enabled;
    }
    obj.placeholder = props.showConfig.placeholder;
    obj.dropdownStyle = commonUtils.isNotEmptyObject(location.pathname) && location.pathname.toLowerCase().indexOf('oee') > -1 ? { fontSize: '1.3rem' } : { fontSize: '12px' };
    if (props.bTable) {
      obj.value = props.showConfig.bMultipleChoice && !commonUtils.isEmpty(dataValue) ? dataValue.split(',') : dataValue;
      obj.className = styles.editSelect;
    }
    if (props.showConfig.iDropWidth > 0) {
      obj.dropdownMatchSelectWidth = false;
      obj.dropdownStyle.width = props.showConfig.iDropWidth;
    }
    obj.onInputKeyDown = onKeyDown;
    obj.onKeyUp = onKeyUp;
    /*   返回值   */
    return obj;
  };

  const getSearchProps = () => {
    const obj = {
      onChange: e => handleSelectOptionEvent(e.target.value), /*   数据改变回带到父组件   */
      value: commonUtils.isUndefined(dataValue) ? '选择' : commonUtils.strUndefinedToEmpty(dataValue), /*   数据值   */
    };
    return obj;
  };

  const getOptionValues = (data) => {
    let res = '';
    let count = 1;
    const iVisCount = commonUtils.isEmpty(props.showConfig.iVisCount) || props.showConfig.iVisCount === 0 ? 1 : props.showConfig.iVisCount;
    if (commonUtils.isNotEmptyStr(props.showConfig.sVisColumnName)) {
      res = data[props.showConfig.sVisColumnName];
    } else {
      for (const key of Object.keys(data)) {
        if (count <= iVisCount && key !== 'sId') {
          if (res === '') {
            res = data[key];
          } else {
            res = res.concat('-').concat(data[key]);
          }
          count += 1;
        }
      }
    }
    return res;
  };

  const getInnerInput = (innerInputProps) => {
    // console.log(innerInputProps, 'innerInputProps');
    if ((props.showConfig.sDropDownType === 'sql' || props.showConfig.sDropDownType === 'const')
      && (firstDataIndex === 'i' || firstDataIndex === 'd' || firstDataIndex === 's')) {
      if (props.showConfig.bCanInput) {
        return <AutoCompleteA {...getSelectProps()} >{getSelectOption()}</AutoCompleteA>;
      } else {
        return <Select {...getSelectProps()} >{getSelectOption()}</Select>;
      }
    } else if (enabled && commonUtils.isNotEmptyObject(props.showConfig.sName) && props.showConfig.sDropDownType === 'popup') { /* 通用弹窗 */
      return (<Search placeholder="选择" defaultValue="选择" {...getSearchProps()} onSearch={onFieldPopupModal(props.showConfig, props.name)} />);
    } else if (firstDataIndex === 'i' || firstDataIndex === 'd') { /*   数字输入框(整形i和浮点型d)   */
      return innerInputProps.readOnly ? <span onKeyDown={onKeyDown} suppressContentEditableWarning contentEditable="true"><InputNumberA {...innerInputProps} /></span> : <InputNumberA {...innerInputProps} />;
    } else if (firstDataIndex === 'b') { /*   选择框(布尔类型b)   */
      return <Checkbox {...innerInputProps}>{showName}</Checkbox>;
    } else if (firstDataIndex === 't') { /*   时间选择框(时间类型t)   */
      return props.bTable ? <span onKeyDown={onKeyDown} suppressContentEditableWarning contentEditable="true"><DatePicker {...innerInputProps} /></span> : <DatePicker {...innerInputProps} />;
    } else if (firstDataIndex === 'm') { /*   月份选择框(月份类型m)   */
      return props.bTable ? <span onKeyDown={onKeyDown} suppressContentEditableWarning contentEditable="true"><MonthPicker {...innerInputProps} /></span> : <MonthPicker {...innerInputProps} />;
    } else if (firstDataIndex === 'p') { /*   时间选择框(时间类型t)   */
      return <RangePicker {...innerInputProps} />;
    } else if (firstDataIndex === 's') { /*   文本输入框(文本s)   */
      if (props.textArea) {
        return <TextAreaA {...innerInputProps} />;
      } else {
        return <InputA {...innerInputProps} />;
      }
    } else if (firstDataIndex === 'c') { /*   地址联动框(联动下拉类型c)   */
      return <Cascader {...innerInputProps} />;
    } else {
      return <InputA {...innerInputProps} />;
    }
  };

  const getSelectOption = () => {
    const options = [];
    const dropDownDataNew = commonUtils.isEmpty(searchValue) ? dropDownData : searchDropDownData;
    if (commonUtils.isNotEmptyArr(dropDownDataNew)) {
      for (const each of dropDownDataNew) {
        if (commonUtils.isNotEmptyObject(each)) {
          let keyValue = !commonUtils.isEmpty(each.sSlaveId) ? each.sSlaveId : each.sId;
          if (firstDataIndex === 'i') {
            keyValue = parseInt(keyValue, 0);
          } else if (firstDataIndex === 'd') {
            keyValue = parseFloat(keyValue);
          }
          let res = '';
          if (commonUtils.isNotEmptyStr(props.showConfig.sVisColumnName)) {
            res = each[props.showConfig.sVisColumnName];
          } else {
            res = Object.keys(each).length > 0 ? each[Object.keys(each)[0]] : '';
          }
          keyValue = commonUtils.isEmpty(keyValue) ? '' : keyValue;
          const option = props.showConfig.bCanInput ?
            (<Option key={keyValue.toString()} label={res} value={keyValue.toString()} title={res}>{getOptionValues(each)}</Option>) :
            (<Option key={keyValue} value={keyValue} label={res} title={res}>{getOptionValues(each)}</Option>);
          options.push(option);
        }
      }
    }
    if (searchValue === '') {
      if (props.showConfig.bFirstEmpty) {
        options.unshift(<Option className="dropdown-empty" key=" " value="=+@" />);/* 解决销售订单-产品名称,五笔输入法输入不支持直接输入中文 */
      }
      if (props.showConfig.bNewRecord) {
        options.unshift(<Option key="@#*000@">New Record</Option>);
      }
    }
    return options;
  };

  // const getFloatPrice = (floatNum) => {
  //   let floatPrice = '';
  //   if (!commonUtils.isUndefined(floatNum)) {
  //     for (let i = 0; i < floatNum; i += 1) {
  //       floatPrice += '\\d';
  //     }
  //   }
  //   return floatPrice;
  // };

  const getDropDownData = async (pageNum, totalPageCount, searchValue) => {
    /**   下拉类型区分
     1、判断是否直接传下拉，如果传了就直接用,并存储到store中去
     2、没有传看 getStoreDropDownData有没有存储，存储后直接取用
     3、 没有存储时直接调用后台SQL语句去下拉 */
    if (props.showConfig.sDropDownType === 'sql') {
      if (pageNum <= totalPageCount) {
        const sqlDropDownData = await props.getSqlDropDownData(props.formId, props.name, props.showConfig, props.record, searchValue, pageNum);
        if (mounted) {
          const dropDownDataNew = [];
          if (commonUtils.isNotEmptyArr(sqlDropDownData.dropDownData)) {
            if (pageNum !== 1) {
              if (searchValue !== '') {
                dropDownDataNew.push(...searchDropDownData);
              } else {
                dropDownDataNew.push(...dropDownData);
              }
            }
            dropDownDataNew.push(...sqlDropDownData.dropDownData);
          }
          if (searchValue !== '') {
            setSearchDropDownData(dropDownDataNew);
            setSearchTotalPageCount(sqlDropDownData.totalPageCount);
            setSearchPageNum(sqlDropDownData.currentPageNo);
            setSearchValue(searchValue);
          } else {
            setDropDownData(dropDownDataNew);
            setTotalPageCount(sqlDropDownData.totalPageCount);
            setPageNum(sqlDropDownData.currentPageNo);
            setSearchValue('');
          }
          setConditonValues(sqlDropDownData.conditonValues);
          setSpinState(false);
        }
      }
    }
  };

  const getInnerInputProps = () => {
    if (!props.bTable) {
      /*   主表   */
      return getInnerInputPropsMaster();
    } else {
      /*   主从表   */
      return getInnerInputPropsSlave();
    }
  };

  const getInnerInputPropsSlave = () => {
    let obj = {};
    if (firstDataIndex === 'i' || firstDataIndex === 'd') { /*   数字输入框(整形i和浮点型d)   */
      obj = getNumberInnerInputPropsSlave();
    } else if (firstDataIndex === 'b') { /*   选择框(布尔类型b)   */
      obj = getBooleanInnerInputPropsSlave();
    } else if (firstDataIndex === 't' || firstDataIndex === 'p' || firstDataIndex === 'm') { /*   时间选择框(时间类型t)   */
      obj = getDateInnerInputPropsSlave();
    } else if (firstDataIndex === 's') { /*   文本输入框(文本s)   */
      obj = getTextInnerInputPropsSlave();
      obj.onDoubleClick = onDoubleClick;
    } else if (firstDataIndex === 'c') { /*   地址联动框(联动下拉类型c)   */
      obj = getAddressInnerInputPropsSlave();
    }
    obj.onKeyDown = onKeyDown;
    obj.onFocus = onFocus;
    obj.onBlur = onBlur;
    obj.onMouseEnter = onFocus;
    obj.id = `${props.showConfig.sName}${props.record ? props.record.sId : commonUtils.createSid()}`;
    return obj;
  };

  const getAddressInnerInputPropsSlave = () => {
    const obj = {
      placeholder: '请选择省市区',
      options: getProvinceCityAreaData(),
      changeOnSelect: true,
      onChange: handleSelectOptionEvent,
      value: commonUtils.isUndefined(dataValue) ? [] : typeof dataValue === 'string' ?
        dataValue.split(',') : commonUtils.convertUndefinedToEmptyArr(dataValue),
    };
    if (props.readOnly) {
      obj.readOnly = 'readOnly';
    } else {
      obj.disabled = !enabled;
    }
    return obj;
  };

  const getTextInnerInputPropsSlave = () => {
    const obj = {
      id: `${props.showConfig.sName}${commonUtils.createSid()}`,
      onChange: e => handleSelectOptionEvent(e),
      value: commonUtils.isUndefined(dataValue) ? '' : commonUtils.strUndefinedToEmpty(dataValue),
      // ref: (ref) => {
      //   // [props.showConfig.sName] = ref;
      //   console.log(ref);
      // },
      onClick: handleInputOnClick(props.showConfig.sName),
    };
    if (props.readOnly) {
      obj.readOnly = 'readOnly';
    } else {
      obj.disabled = !enabled;
    }
    if (typeof commonUtils.convertStrToNumber(max) === 'number' && commonUtils.convertStrToNumber(max) !== 0 && max.indexOf('.d') === -1 && max.indexOf('.i') === -1) {
      obj.maxLength = max;
    }
    obj.placeholder = props.showConfig.placeholder;
    return obj;
  };

  const getDateInnerInputPropsSlave = () => {
    let { sDateFormat } = props.showConfig;
    if (commonUtils.isEmptyStr(sDateFormat)) {
      if (firstDataIndex === 'm') {
        sDateFormat = 'YYYY-MM';
      } else {
        sDateFormat = props.getDateFormat();
      }
    }
    const obj = {
      placeholder: '',
      disabled: !enabled,
      onChange: handleSelectOptionEvent,
      format: sDateFormat,
      disabledDate: getDataMaxAndMin,
    };
    if (!enabled) {
      obj.suffixIcon = <span />;
    }
    obj.value = commonUtils.isEmpty(dataValue) ? null : moment(dataValue);
    return obj;
  };

  const getBooleanInnerInputPropsSlave = () => {
    const obj = {
      disabled: !enabled,
      onChange: handleSelectOptionEvent,
      checked: commonUtils.isUndefined(dataValue) ? false : commonUtils.converNumStrToBoolean(dataValue),
    };
    return obj;
  };

  const getNumberInnerInputPropsSlave = () => {
    const obj = {
      id: `${props.showConfig.sName}${props.showConfig.sId}`,
      className: styles.inputNum,
      onChange: value => handleSelectOptionEvent(value),
      // ref: (ref) => {
      //   console.log(ref);
      //   // [props.showConfig.sName] = ref;
      // },
      onClick: handleInputOnClick(props.showConfig.sName),
    };
    if (props.readOnly) {
      obj.readOnly = true;
    } else {
      obj.disabled = !enabled;
    }
    if (typeof commonUtils.convertStrToNumber(max) === 'number' && commonUtils.convertStrToNumber(max) !== 0 && max.indexOf('.d') === -1 && max.indexOf('.i') === -1) {
      obj.max = max;
    } else if (!commonUtils.isEmpty(max) && max.indexOf('.') > -1 && commonUtils.isNotEmptyObject(props.record)) {
      obj.max = props.record[max.substring(max.indexOf('.') + 1)];
    }
    if (typeof commonUtils.convertStrToNumber(min) === 'number' && commonUtils.convertStrToNumber(min) !== 0) {
      obj.min = min;
    }
    if (obj.max < 0) { /* 为解决收付款单据未收款为负数时收款金额不能大于未收款问题，当最大值小于0时，变更为设为最小值 */
      obj.min = obj.max;
      obj.max = 0;
    }
    const numCheck = /^(-?\d+)(\.?)(\d{1,6})?$/;
    if (!numCheck.test(dataValue) && dataValue) {
      message.warning('最多6位小数');
    }
    obj.value = dataValue;
    obj.step = 0;
    return obj;
  };

  const getInnerInputPropsMaster = () => {
    let obj = {};
    if (firstDataIndex === 'i' || firstDataIndex === 'd') { /*   数字输入框(整形i和浮点型d)   */
      obj = getNumberInnerInputPropsMaster();
    } else if (firstDataIndex === 'b') { /*   选择框(布尔类型b)   */
      obj = getBooleanInnerInputPropsMaster();
    } else if (firstDataIndex === 't' || firstDataIndex === 'p' || firstDataIndex === 'm') { /*   时间选择框(时间类型t)   */
      obj = getDateInnerInputPropsMaster();
    } else if (firstDataIndex === 's') { /*   文本输入框(文本s)   */
      if (props.textArea) { /*   大文本输入框   */
        obj = getTextAreaInnerInputPropsMaster();
        obj.onDoubleClick = onDoubleClick;
      } else { /*   普通文本输入框   */
        obj = getTextInnerInputPropsMaster();
      }
    } else if (firstDataIndex === 'c') { /*   地址联动框(联动下拉类型c)   */
      obj = getAddressInnerInputPropsMaster();
    }
    obj.onKeyDown = onKeyDown;
    obj.onKeyUp = onKeyUp;
    obj.onContextMenu = onContextMenu;
    return obj;
  };

  const getAddressInnerInputPropsMaster = () => {
    const obj = {
      placeholder: '请选择省市区',
      options: getProvinceCityAreaData(),
      changeOnSelect: true,
      onChange: handleSelectOptionEvent,
    };
    if (props.readOnly) {
      obj.readOnly = 'readOnly';
    } else {
      obj.disabled = !enabled;
    }
    return obj;
  };

  const getTextInnerInputPropsMaster = () => {
    /*   返回值声明   */
    const obj = {
      id: `${props.showConfig.sName}${commonUtils.createSid()}`,
      onChange: e => handleSelectOptionEvent(e),
      // ref: (ref) => {
      //   // this[props.showConfig.sName] = ref
      //   console.log(ref);
      // },
      onClick: handleInputOnClick(props.showConfig.sName), /*   虚拟数字键盘 第二个参数必须id  */
    };
    if (props.readOnly) {
      obj.readOnly = 'readOnly';
    } else {
      obj.disabled = !enabled;
    }
    if (props.bPassWord) {
      obj.type = 'password'; /* 文本密码类型 */
      obj.autocomplete = 'off'; /* 禁止浏览器自动填充到表单 */
    }
    if (typeof commonUtils.convertStrToNumber(max) === 'number' && commonUtils.convertStrToNumber(max) !== 0 && max.indexOf('.d') === -1 && max.indexOf('.i') === -1) {
      obj.maxLength = max;
    }
    return obj;
  };

  const getTextAreaInnerInputPropsMaster = () => {
    const obj = {
      id: `${props.showConfig.sName}${commonUtils.createSid()}`,
      rows: 1,
      onChange: handleSelectOptionEvent,
      // ref: (ref) => {
      //   // this[props.showConfig.sName] = ref;
      //   console.log(ref);
      // },
      onClick: handleInputOnClick.bind(this, props.showConfig.sName),
    };
    if (props.readOnly) {
      obj.readOnly = 'readOnly';
    } else {
      obj.disabled = !enabled;
    }
    if (typeof commonUtils.convertStrToNumber(max) === 'number' && commonUtils.convertStrToNumber(max) !== 0 && max.indexOf('.d') === -1 && max.indexOf('.i') === -1) {
      obj.maxLength = max;
    }
    return obj;
  };

  const getDataMaxAndMin = (current) => {
    return getDataMax(current) || getDataMin(current);
  };


  const getDataMax = (current) => {
    const tDate = props.showConfig.sMaxValue === 'now' ? moment() : moment(props.showConfig.sMaxValue);
    return commonUtils.isNotEmptyStr(props.showConfig.sMinValue) && current.endOf('day') > tDate.endOf('day');
  };

  const getDataMin = (current) => {
    const tDate = props.showConfig.sMinValue === 'now' ? moment() : moment(props.showConfig.sMinValue);
    return commonUtils.isNotEmptyStr(props.showConfig.sMinValue) && current.endOf('day') < tDate.endOf('day');
  };

  const getDateInnerInputPropsMaster = () => {
    let { sDateFormat } = props.showConfig;
    if (commonUtils.isEmptyStr(sDateFormat)) {
      if (firstDataIndex === 'm') {
        sDateFormat = 'YYYY-MM';
      } else {
        sDateFormat = props.getDateFormat();
      }
    }
    const obj = {
      placeholder: '',
      disabled: !enabled,
      style: { width: '100%' },
      showTime: props.showTime,
      format: props.showTime ? 'YYYY-MM-DD HH:mm:ss' : sDateFormat,
      onChange: handleSelectOptionEvent,
      disabledDate: getDataMaxAndMin,
    };
    return obj;
  };

  const getBooleanInnerInputPropsMaster = () => {
    const obj = {
      disabled: !enabled, /*   是否显示   */
      onChange: handleSelectOptionEvent, /*   数据改变回带到父组件   */
      checked: commonUtils.isUndefined(dataValue) ? false : commonUtils.converNumStrToBoolean(dataValue),
    };
    return obj;
  };

  const handleInputOnClick = (id) => {
    // 判断是否是oee系统，否则不显示虚拟键盘
    if (commonUtils.isNotEmptyObject(props.formRoute) && props.formRoute.indexOf('/indexOee') > -1) {
      if (VirtualKeyboard.isKeyBoard()) { // 关闭上次键盘
        VirtualKeyboard.closeKeyboard();
      }
      const keyboardValue = {};
      if (commonUtils.isNotEmptyObject(props.dataValue)) {
        keyboardValue.value = props.dataValue;
      } else {
        keyboardValue.value = '';
      }
      // 重构，待完成
      VirtualKeyboard.showKeyboardSetState(keyboardValue, this, id);
    }
  };

  const getNumberInnerInputPropsMaster = () => {
    /*   如果是浮点型并且有格式规定,display类型需要变为block   */
    let display = 'inline-block';
    if (firstDataIndex === 'd' && floatNum !== 0) {
      display = 'block';
    }
    const obj = {
      id: `${props.showConfig.sName}${commonUtils.createSid()}`,
      style: { width: 'auto', display, marginRight: 0 },
      onChange: handleSelectOptionEvent,
      // ref: (ref) => {
      //   // this[props.showConfig.sName] = ref;
      //   console.log(ref);
      // },
      onClick: handleInputOnClick(props.showConfig.sName), /*   虚拟数字键盘 第二个参数必须id  */
    };
    if (props.readOnly) {
      obj.readOnly = true;
    } else {
      obj.disabled = !enabled;
    }
    /*   最大值最小值   */
    if (typeof commonUtils.convertStrToNumber(max) === 'number' && commonUtils.convertStrToNumber(max) !== 0 && max.indexOf('.d') === -1 && max.indexOf('.i') === -1) {
      obj.max = max; /*   最大值   */
    } else if (!commonUtils.isEmpty(max) && max.indexOf('.') > -1 && commonUtils.isNotEmptyObject(props.record)) {
      obj.max = props.record[max.substring(max.indexOf('.') + 1)];
    }
    if (typeof commonUtils.convertStrToNumber(min) === 'number' && commonUtils.convertStrToNumber(min) !== 0) {
      obj.min = min; /*   最小值   */
    }
    obj.placeholder = props.showConfig.placeholder;
    return obj;
  };

  const getProvinceCityAreaData = () => {
    const options = [];
    getProvinceData(options);
    getCityData(options);
    getAreaData(options);
    return options;
  };

  const getProvinceData = (options) => {
    Provinces.forEach((childProvince) => {
      options.push({
        value: childProvince.name,
        label: childProvince.name,
        code: childProvince.code,
        children: [],
      });
    });
  };

  const getCityData = (options) => {
    options.forEach((childProvince) => {
      const cities = Cities.filter(item => item.provinceCode === childProvince.code);
      if (cities.length > 0) {
        cities.forEach((childCity) => {
          childProvince.children.push({
            value: childCity.name,
            label: childCity.name,
            code: childCity.code,
            children: [],
          });
        });
      }
    });
  };

  const getAreaData = (options) => {
    options.forEach((childProvince) => {
      const cities = childProvince.children;
      cities.forEach((childCity) => {
        const areas = Areas.filter((item => item.cityCode === childCity.code));
        if (areas.length > 0) {
          areas.forEach((area) => {
            childCity.children.push({
              value: area.name,
              label: area.name,
              code: area.code,
            });
          });
        }
      });
    });
  };

  const getOutFormItemProps = () => {
    if (!props.bTable) {
      /*   主表   */
      return getOutFormItemPropsMaster();
    } else {
      /*   从表   */
      return getOutFormItemPropsSlave();
    }
  };

  const getOutFormItemPropsMaster = () => {
    let obj = {};
    if (firstDataIndex === 'i'
      || firstDataIndex === 'd'
      || firstDataIndex === 'p'
      || firstDataIndex === 't'
      || firstDataIndex === 'm'
      || firstDataIndex === 's'
      || firstDataIndex === 'c') {
      obj = {
        label: props.showConfig.showName,
        className: styles.formItemMargin,
        ...formItemLayout,
      };
    } else if (firstDataIndex === 'b') {
      obj = {
        label: props.showConfig.showName,
        className: styles.formItemMag10,
        ...formItemLayout,
      };
    }
    if (props.itemLabel === 'hide') {
      delete obj.label;
    }
    return obj;
  };

  const getOutFormItemPropsSlave = () => {
    let obj = {};
    if (firstDataIndex === 'i'
      || firstDataIndex === 'd'
      || firstDataIndex === 'c'
      || props.showConfig.sDropDownType === 'sql'
      || props.showConfig.sDropDownType === 'const') {
      obj = {
        className: styles.formItemMargin0,
      };
    } else if (firstDataIndex === 'b') {
      obj = {
        className: styles.tableCheckBox,
      };
    } else if (firstDataIndex === 't' || firstDataIndex === 'p' || firstDataIndex === 'm') {
      obj = {
        className: styles.tableDataPicker,
      };
    } else if (firstDataIndex === 's') {
      obj = {
        className: styles.editInput,
      };
    }
    return obj;
  };

  const getFieldDecoratorProps = () => {
    let obj = {};
    if (firstDataIndex === 'i' || firstDataIndex === 'd' || firstDataIndex === 't' || firstDataIndex === 'p' || firstDataIndex === 's' || firstDataIndex === 'b') {
      obj = { rules: [{ required: props.showConfig.bNotEmpty, message: `${props.showConfig.showName}为必填项` }] };
    } else if (firstDataIndex === 'c') {
      obj = {
        initialValue: ['北京市', '市辖区', '东城区'],
        rules: [{ required: props.showConfig.bNotEmpty, message: `${props.showConfig.showName}为必填项` }],
      };
    }
    return obj;
  };

  // const getPopupContainer = (triggerNode) => {
  //   const trigger = triggerNode;
  //   if (commonUtils.isNotEmptyObject(trigger)) {
  //     return triggerNode;
  //   }
  // };

  const handleSelectOptionEvent = (newValue, dateString) => {
    if (newValue === undefined) return;
    let value = firstDataIndex === 's' && !props.textArea && commonUtils.isEmpty(newValue) ? newValue.replace('--', '') :
      firstDataIndex === 't' ? dateString : (firstDataIndex === 'd' || firstDataIndex === 'i') && commonUtils.isEmpty(newValue) ? 0 : newValue;
    value = props.showConfig.bMultipleChoice ? value.toString() : value;
    isDropdownFilter = true;
    if (props.showConfig.sDropDownType === 'sql' && value === '@#*000@') {
      props.handleSqlDropDownNewRecord(props.showConfig, props.name);
      if (mounted) {
        setDataValue('');
      }
      return;
    }
    if (props.showConfig.sDropDownType === 'sql' && value === '=+@') {
      value = '';
    }
    if (props.showConfig.sDropDownType === 'const' && value === '=+@') {
      value = '';
    }
    const returnValue = {};
    const dropDownDataNew = commonUtils.isEmptyArr(searchValue) ? dropDownData : searchDropDownData;
    /*   回带值赋值(sName:value)   */
    returnValue[props.showConfig.sName] =
      firstDataIndex === 'i' ? commonUtils.isEmpty(value) ? undefined : props.showConfig.sName === 'iOrder' ? value : parseInt(value, 0) :
        firstDataIndex === 'd' ? commonUtils.isEmpty(value) ? undefined : floatNumberCheck(value) :
          firstDataIndex === 't' ? commonUtils.isEmpty(value) ? null : value :
            firstDataIndex === 'b' ? value.target.checked : value === null ? undefined : value;
    if (!props.showConfig.bMultipleChoice) {
      const { sAssignField } = props.showConfig;
      const [changeData] = dropDownDataNew.filter(item => (!commonUtils.isEmpty(item.sSlaveId) ? item.sSlaveId : item.sId) === value.toString());
      if (!commonUtils.isEmpty(sAssignField)) {
        const sAssignFieldObj = sAssignField.split(',');
        if (commonUtils.isNotEmptyObject(changeData)) {
          for (const child of sAssignFieldObj) {
            if (child.indexOf(':') > -1) {
              const sFieldName = child.split(':')[0].trim() === 'self' ? props.showConfig.sName : child.split(':')[0].trim();
              const sValueName = child.split(':')[1].trim();
              returnValue[sFieldName] = changeData[sValueName] || changeData.value;
            }
          }
        } else if (!props.showConfig.bCanInput) {
          for (const child of sAssignFieldObj) {
            if (child.indexOf(':') > -1) {
              const sFieldName = child.split(':')[0].trim() === 'self' ? props.showConfig.sName : child.split(':')[0].trim();
              returnValue[sFieldName] = '';
            }
          }
        }
      }
    } else {
      const { sAssignField } = props.showConfig;
      const changeData = dropDownDataNew.filter(item => (`,${value.toString()},`).includes((!commonUtils.isEmpty(item.sSlaveId) ? `,${item.sSlaveId},` : `,${item.sId},`)));
      if (!commonUtils.isEmpty(sAssignField)) {
        const sAssignFieldObj = sAssignField.split(',');
        if (commonUtils.isNotEmptyArr(changeData)) {
          for (const child of sAssignFieldObj) {
            if (child.indexOf(':') > -1) {
              const sFieldName = child.split(':')[0].trim() === 'self' ? props.showConfig.sName : child.split(':')[0].trim();
              const sValueName = child.split(':')[1].trim();
              const valueArr = [];
              changeData.forEach((itemData) => {
                valueArr.push(itemData[sValueName]);
              });
              returnValue[sFieldName] = valueArr.toString();
            }
          }
        } else if (!props.showConfig.bCanInput) {
          for (const child of sAssignFieldObj) {
            if (child.indexOf(':') > -1) {
              const sFieldName = child.split(':')[0].trim() === 'self' ? props.showConfig.sName : child.split(':')[0].trim();
              returnValue[sFieldName] = '';
            }
          }
        }
      }
    }
    setSearchPageNum(0);
    setSearchTotalPageCount(1);
    setSearchDropDownData([]);
    setSearchValue('');
    setSpinState(false);
    props.onChange(props.name, props.showConfig.sName, returnValue, props.sId, dropDownDataNew);
  };

  const filterOption = (input, option) => {
    const newInput = input.toString().trim();
    if (pageNum <= totalPageCount && props.showConfig.sDropDownType === 'sql' && commonUtils.isEmptyArr(props.showConfig.dropDownData)) {
      return true;
    } else if (commonUtils.isNotEmptyObject(option.props.children)) {
      return !isDropdownFilter && props.showConfig.bCanInput ? true : option.props.children.toLowerCase().indexOf(newInput.toLowerCase()) >= 0;
    }
  };

  const floatNumberCheck = (num) => {
    const checkRule = /^(-?\d+)(\.?)(\d{1,6})?$/;
    if (!checkRule.test(num) && num && num !== '-' && num !== '.') {
      message.warning('最多输入6位小数！');
      return undefined;
    } else {
      return num;
    }
  };

  // const limitDecimals = (values) => {
  //   let reg = '';
  //   if (floatNum > 0) {
  //     reg = `^(\\d+).(${floatPrice})*$`;
  //   } else {
  //     reg = '^(\\d+).(\\d\\d\\d\\d\\d\\d)*$';
  //   }
  //   if (typeof values === 'string') {
  //     if (values !== undefined && values.indexOf('.') <= -1) {
  //       reg = '^(\\d+)*$';
  //       return !isNaN(Number(values)) ? values.replace(new RegExp(reg), '$1') : '';
  //     } else {
  //       return !isNaN(Number(values)) ? values.replace(new RegExp(reg), '$1.$2') : '';
  //     }
  //   } else if (typeof values === 'number') {
  //     if (values !== undefined && String(values).indexOf('.') <= -1) {
  //       reg = '^(\\d+)*$';
  //       return !isNaN(values) ? String(values).replace(new RegExp(reg), '$1') : '';
  //     } else {
  //       return !isNaN(values) ? String(values).replace(new RegExp(reg), '$1.$2') : '';
  //     }
  //   } else {
  //     return '';
  //   }
  // };

  const handleViewClick = () => {
    const { record, app, showConfig } = props;
    const { sControlName, sActiveKey } = showConfig;
    if (commonUtils.isNotEmptyObject(sControlName) && commonUtils.isNotEmptyObject(sActiveKey)) {
      const printPdf = sControlName;
      if (commonUtils.isNotEmptyObject(printPdf) && printPdf === 'printPdf' && commonUtils.isNotEmptyObject(sActiveKey)) {
        const { token } = app;
        const sActiveId = props.showConfig.sActiveId === '1' ? commonUtils.isEmpty(record.sFormId) ? record.sSrcFormId : record.sFormId : props.showConfig.sActiveId;
        const printsId = record[sActiveKey];
        const urlPrint = `${commonConfig.file_host}printReport/printPdfByFromDataId?sModelsId=${sActiveId}&sId=${printsId}&token=${encodeURIComponent(token)}`;
        window.open(urlPrint);
      } else {
        props.onViewClick(props.name, props.showConfig.sName, props.record);
      }
    } else {
      props.onViewClick(props.name, props.showConfig.sName, props.record);
    }
  };

  const handlePreviewImage = (e, dataUrl) => {
    props.onPreviewImage(e, dataUrl);
  };

  const handleViewChoose = () => {
    props.onViewChoose(props.name, props.showConfig.sName, props.record);
  };

  const handlePopupScroll = (e) => {
    e.persist();
    const { target } = e;
    if (Math.ceil(target.scrollTop + target.offsetHeight) >= target.scrollHeight && props.showConfig.sDropDownType === 'sql' && commonUtils.isEmptyArr(props.showConfig.dropDownData)) {
      const nextPageNum = pageNum + 1;
      const nextSearchPageNum = searchPageNum + 1;
      if (searchValue !== '') {
        getDropDownData(nextSearchPageNum, searchTotalPageCount, searchValue);
      } else {
        getDropDownData(nextPageNum, totalPageCount, searchValue);
      }
    }
  };

  const handleSearch = (value) => {
    if (dropDownTimer) {
      clearTimeout(dropDownTimer);
    }
    dropDownTimer = setTimeout(() => {
      if (props.showConfig.sDropDownType === 'sql' && commonUtils.isEmptyArr(props.showConfig.dropDownData)) {
        setSpinState(true);
        getDropDownData(1, 1, value);
      }
    }, 500);
  };

  // 处理渲染函数
  const innerInputProps = getInnerInputProps();
  const innerInput = getInnerInput(innerInputProps);
  const { sName } = props.showConfig;
  let viewInfo = '';
  if (props.showConfig.sDropDownType !== 'popup' && !commonUtils.isEmpty(props.showConfig.sActiveId) && !commonUtils.isEmpty(props.showConfig.sActiveKey) && (commonUtils.isNotEmptyObject(props.dataValue) || commonUtils.isNotEmptyNumber(props.dataValue))) {
    viewInfo = (
      <div
        className="sActiveIdStyle"
        title={props.dataValue}
        style={{
          display: sActiveDisplay ? 'block' : 'none',
          top: props.name === 'slaveInfo' ? '1px' : '',
          left: props.name === 'slaveInfo' ? '2px' : props.name === 'master' ? '1px' : '',
          position: 'absolute',
        }}
      >
        <span
          onClick={handleViewClick}
          style={{
              width: '100%', overflow: 'hidden', color: '#2f54eb', background: 'transparent',
            }}
        > {props.dataValue}
        </span>
      </div>);
  }
  const sModelsType = commonUtils.isNotEmptyObject(props) && commonUtils.isNotEmptyObject(props.app) ? props.app.currentPane.sModelsType : '';
  if (sName === 'sCombinedMemo' || sName === 'sColorSerialMemo' || (commonUtils.isNotEmptyObject(sModelsType) && !sModelsType.includes('Set') && sName === 'sCombinePartsNameNew')) {
    let sValue = '';
    /* 将合版信息json解析成需要的字符串形式 */
    if (sName === 'sCombinedMemo') {
      let JsonData = [];
      if (commonUtils.isNotEmptyObject(props.dataValue)) {
        try {
          JsonData = JSON.parse(props.dataValue);
        } catch (e) {
          JsonData = [];
        }
      }
      if (commonUtils.isNotEmptyArr(JsonData)) {
        JsonData.forEach((item) => {
          sValue += `${item.sProductNo}:排${item.dCombineQty}个,`;
        });
        sValue = commonUtils.isNotEmptyObject(sValue) ? sValue.substr(0, sValue.length - 1) : '';
      }
    } else if (sName === 'sColorSerialMemo') {
      let JsonData = [];
      if (commonUtils.isNotEmptyObject(props.dataValue)) {
        try {
          JsonData = JSON.parse(props.dataValue);
        } catch (e) {
          JsonData = [];
        }
      }
      if (commonUtils.isNotEmptyArr(JsonData)) {
        JsonData.forEach((item) => {
          sValue += `${item.sName}+`;
        });
        sValue = commonUtils.isNotEmptyObject(sValue) ? sValue.substr(0, sValue.length - 1) : '';
      }
    } else {
      sValue = props.dataValue;
    }
    viewInfo = (
      <div
        className="sActiveIdStyle"
        title={sValue}
        style={{
          display: 'block',
          position: 'relative',
          top: props.name === 'slaveInfo' ? '1px' : '',
          left: props.name === 'slaveInfo' ? '2px' : props.name === 'master' ? '1px' : '',
        }}
      >
        <span
          onClick={handleViewChoose}
          className="viewChooseSpan"
          style={{
              width: '100%', overflow: 'hidden', color: '#2f54eb', background: 'transparent',
            }}
        > {commonUtils.isNotEmptyObject(sValue) ? sValue : sName === 'sCombinedMemo' ? '合版信息' : '请选择'}
        </span>
      </div>);
  }
  let speacilNote = '';
  const { record } = props;
  const afterSave = commonUtils.isNotEmptyObject(this.props) && commonUtils.isNotEmptyObject(this.props.app) ?  commonFunc.showMessage(this.props.app.commonConst, 'afterSave') : '保存后自动生成';
  if (commonUtils.isNotEmptyObject(record) && commonUtils.isEmptyObject(record[sName]) && commonUtils.isNotEmptyObject(sName) && (sName === 'tCreateDate' || sName === 'sMakePerson')) {
    speacilNote = (<div className="speacialNote" style={{ position: 'absolute', padding: '0px 4px' }}> {afterSave}</div>);
  }
  let imgBox = '';
  if (commonUtils.isNotEmptyObject(sName) && sName.indexOf('picture') > -1) {
    const picAddr = commonUtils.isNotEmptyObject(record[sName]) ? record[sName].split(',') : '';
    if (commonUtils.isNotEmptyObject(picAddr)) {
      const { token } = props.app;
      const dataUrl = `${commonConfig.server_host}file/download?savePathStr=${picAddr}&scale=0.1&sModelsId=100&token=${token}`; /* 缩略图 */
      imgBox = (
        <div
          className="sActiveIdStyle"
          title={props.dataValue}
          style={{
            position: 'absolute', width: '100%',
          }}
        >
          <span style={{ width: '100%', overflow: 'hidden', background: 'transparent' }}>
            <img src={dataUrl} alt="img" onFocus={() => 0} onMouseOver={e => handlePreviewImage(e, picAddr)} style={{ width: '30px', height: '20px' }} />
          </span>
        </div>);
    }
  }
  const outFormItemProps = getOutFormItemProps();
  const fieldDecoratorProps = getFieldDecoratorProps();
  const commonAssembly = (<FormItem {...outFormItemProps}> {viewInfo}{speacilNote}{imgBox}{!props.bTable ? getFieldDecorator(props.showConfig.sName, fieldDecoratorProps)(innerInput) : innerInput} </FormItem>);
  const { iColValue } = props;
  return (
    <div className={iColValue === 24 ? 'input24' : iColValue === 18 ? styles.input18 : iColValue === 12 ? styles.input12 : 'changeClassName'}>
      <div className={props.className}>
        {commonAssembly}
      </div>
    </div>
  );
}
export default CommonComponent;
