/* eslint-disable */
import { List, InputItem, Picker, TextareaItem, DatePicker, Checkbox, Toast } from 'antd-mobile-v2';
import moment from 'moment';
import React, { Component } from 'react';
import { debounce } from 'lodash';
import commonConfig from '../../utils/config';
import * as commonUtils from '../../utils/utils';
import styles from '../mobile.less';
import iconSetting from '../../assets/mobile/setting.png';
import scan from '../../assets/mobile/scanning.svg';


// eslint-disable-next-line prefer-destructuring
const CheckboxItem = Checkbox.CheckboxItem;
const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
let moneyKeyboardWrapProps;
if (isIPhone) {
  moneyKeyboardWrapProps = {
    onTouchStart: e => e.preventDefault(),
  };
}

export default class CommonComponent extends Component {
  /**   构造函数   */
  constructor(props) {
    super(props);
    this.state = {
      dataValue: props.dataValue, /*   本showType数据 */
      enabled: props.enabled, /*   是否是查看状态(数据格式:布尔)   */
      dropDownData: [],
      // eslint-disable-next-line react/no-unused-state
      bReGetDropDown: false,
      bOpenKeyboard : props.bOpenKeyboard,

    };
    this.firstDataIndex = props.showConfig.sName.substring(0, 1); /*   控件首字母(数据格式:字符串)   */
    this.max = commonUtils.convertStrToNumber(props.showConfig.sMaxValue); /*   最大值(数据格式:数字)   */
    this.min = commonUtils.convertStrToNumber(props.showConfig.sMinValue); /*   最小值(数据格式:数字)   */
    this.getFieldProps = props.form.getFieldProps;
  }

  /**   渲染前只执行一次   */
  componentWillMount() {
    this.mounted = true;
    /*   如果是下拉控件,则要获取数据   */
    if ((this.props.showConfig.sDropDownType === 'sql' || this.props.showConfig.sDropDownType === 'const')
      && (this.firstDataIndex === 'i' || this.firstDataIndex === 'd' || this.firstDataIndex === 's')) {
      this.getDropDownData(this.props);
    }
  }

  /**   props改变的时候触发   */
  componentWillReceiveProps(nextProps) {
    const {
      dataValue, enabled, sFieldName, bNotEmpty, masterData, dropDownData,
    } = this.state;
    if ((nextProps.showConfig.sDropDownType === 'sql') && (this.firstDataIndex === 'i' || this.firstDataIndex === 'd' || this.firstDataIndex === 's')) {
      let newDropDownData = commonUtils.getStoreDropDownData(this.props.formId, this.props.name, this.props.showConfig.sName);
      if (nextProps.onFilterDropDownData && !commonUtils.isEmptyStr(nextProps.showConfig.sSqlCondition)) {
        if (!commonUtils.isEmpty(nextProps.showConfig.sChineseDropDown)) {
          const conditon = nextProps.showConfig.sSqlCondition.split(',');
          const fieldName = conditon[0].indexOf('.') > -1 ? conditon[0].split('.')[1] : '';
          // #参数# SQL where条件过滤数据    *参数* 去除单引号 用于like处理
          if (!nextProps.showConfig.sChineseDropDown.includes(`#${fieldName}`) && !nextProps.showConfig.sChineseDropDown.includes(`*${fieldName}`)) {
            newDropDownData = nextProps.onFilterDropDownData(newDropDownData, nextProps.showConfig, nextProps.name, nextProps.record);
          }
        }
      }
      if (this.mounted && !nextProps.showConfig.bReGetDropDown && nextProps.showConfig.dropDownData !== undefined && JSON.stringify(newDropDownData) !== JSON.stringify(nextProps.showConfig.dropDownData)) {
        let newData = nextProps.showConfig.dropDownData;
        if (nextProps.onFilterDropDownData && !commonUtils.isEmptyStr(nextProps.showConfig.sSqlCondition)) {
          if (!commonUtils.isEmpty(nextProps.showConfig.sChineseDropDown)) {
            const conditon = nextProps.showConfig.sSqlCondition.split(',');
            const fieldName = conditon[0].indexOf('.') > -1 ? conditon[0].split('.')[1] : '';
            if (!nextProps.showConfig.sChineseDropDown.includes(`#${fieldName}`) && !nextProps.showConfig.sChineseDropDown.includes(`*${fieldName}`)) {
              newData = newDropDownData;
            }
          }
        }
        this.setState({
          dropDownData: newData,
        });
      } else if (JSON.stringify(newDropDownData) !== JSON.stringify(dropDownData) || this.props.showConfig.sId !== nextProps.showConfig.sId || nextProps.showConfig.bReGetDropDown || nextProps.showConfig.sSqlCondition !== '') {
        if (commonUtils.isEmptyArr(newDropDownData) || this.props.showConfig.sId !== nextProps.showConfig.sId) {
        } else if (this.mounted) {
          this.setState({
            dropDownData: newDropDownData,
          });
        }
      }
    } else if ((nextProps.showConfig.sDropDownType === 'const') && (this.firstDataIndex === 'i' || this.firstDataIndex === 'd' || this.firstDataIndex === 's')) {
      if (nextProps.showConfig.dropDownData !== undefined && JSON.stringify(this.state.dropDownData) !== JSON.stringify(nextProps.showConfig.dropDownData)) {
        if (this.mounted) {
          this.setState({
            dropDownData: nextProps.showConfig.dropDownData,
          });
        }
      }
    }

    if (dataValue !== nextProps.dataValue || enabled !== nextProps.enabled || bNotEmpty !== nextProps.showConfig.bNotEmpty || sFieldName !== nextProps.showConfig.sName ||
      JSON.stringify(masterData) !== JSON.stringify(nextProps.masterData)) {
      this.firstDataIndex = nextProps.showConfig.sName.substring(0, 1); /*   控件首字母(数据格式:字符串)   */
      if (this.mounted) {
        this.setState({
          dataValue: nextProps.dataValue,
          enabled: nextProps.enabled,
          sFieldName: nextProps.showConfig.sName,
          bNotEmpty: nextProps.showConfig.bNotEmpty,
          masterData: nextProps.masterData,
          bOpenKeyboard: nextProps.bOpenKeyboard,
        });
      }
    }
  }

  shouldComponentUpdate(nextProps, nextState) {
    const {
      dataValue, enabled, dropDownData, sFieldName, bNotEmpty, masterData,
    } = this.state;
    // console.log('bOpenKeyboard:', nextProps.bOpenKeyboard);
    if(nextProps.bOpenKeyboard !==undefined) {
      return true;
    }
    return nextProps.showConfig !== undefined && (dataValue !== nextState.dataValue || enabled !== nextState.enabled ||
      sFieldName !== nextState.sFieldName || bNotEmpty !== nextState.bNotEmpty || JSON.stringify(dropDownData) !== JSON.stringify(nextState.dropDownData) ||
      JSON.stringify(masterData) !== JSON.stringify(nextState.masterData));
  }

  componentWillUnmount() {
    this.mounted = false;
  }

  /**   获取下拉值   */
  getDropDownData = async (props, bReGetDropDown) => {
    /**   下拉类型区分
     1、判断是否直接传下拉，如果传了就直接用,并存储到store中去
     2、没有传看 getStoreDropDownData有没有存储，存储后直接取用
     3、 没有存储时直接调用后台SQL语句去下拉 */
    if (props.showConfig.sDropDownType === 'sql') { /*   数据下拉   */
      let { dropDownData } = props.showConfig;
      if (commonUtils.isEmptyArr(dropDownData)) {
        dropDownData = commonUtils.getStoreDropDownData(props.formId, props.name, props.showConfig.sName);
        if (commonUtils.isEmptyArr(dropDownData) || bReGetDropDown) {
          dropDownData = await props.getSqlDropDownData(props.formId, props.name, props.showConfig, props.record);
        }
      } else {
        commonUtils.setStoreDropDownData(props.formId, props.name, props.showConfig.sName, dropDownData);
      }
      if (this.mounted) {
        const { sSqlCondition } = props.showConfig;
        if (props.onFilterDropDownData && !commonUtils.isEmptyStr(sSqlCondition)) {
          if (!commonUtils.isEmpty(props.showConfig.sChineseDropDown)) {
            const conditon = props.showConfig.sSqlCondition.split(',');
            const fieldName = conditon[0].indexOf('.') > -1 ? conditon[0].split('.')[1] : '';
            if (!props.showConfig.sChineseDropDown.includes(`#${fieldName}`) && !props.showConfig.sChineseDropDown.includes(`*${fieldName}`)) {
              dropDownData = await props.onFilterDropDownData(dropDownData, props.showConfig, props.name, props.record);
            }
          }
        }
        this.setState({
          dropDownData,
          // eslint-disable-next-line react/no-unused-state
          isDropDownLoadFinish: true,
          // eslint-disable-next-line react/no-unused-state
          bReGetDropDown: false,
        });
      }
    } else if (props.showConfig.sDropDownType === 'const') { /*   常量下拉   */
      /*   常量下拉其实只取一次数据就可以啦,去过数据的会给state中的dropDownData赋值,所以dropDownData有值的情况就不需要再获取了   */
      if (commonUtils.isEmptyArr(this.state.dropDownData) || JSON.stringify(this.state.dropDownData) !== JSON.stringify(props.showConfig.showDropDown)) {
        /*   把常量下拉对象转换成数组格式来适配(最终state中dropDownData的值都是数组对象的形式)   */
        let showDropDown;
        if (typeof props.showConfig.showDropDown === 'object') {
          // eslint-disable-next-line prefer-destructuring
          showDropDown = props.showConfig.showDropDown;
        } else {
          showDropDown = commonUtils.objectToArr(commonUtils.convertStrToObj(props.showConfig.showDropDown));
        }
        /*   给state赋值   */
        if (this.mounted) {
          this.setState({
            dropDownData: showDropDown,
            // eslint-disable-next-line react/no-unused-state
            isDropDownLoadFinish: true,
          });
        }
      }
    }
  };

  /**   获取selectOption对象   */
  getSelectOption = () => {
    /*   返回值声明   */
    const options = [];
    /*   执行条件   */
    if (commonUtils.isNotEmptyArr(this.state.dropDownData)) {
      /*   遍历下拉数据   */
      for (const each of this.state.dropDownData) {
        if (commonUtils.isNotEmptyObject(each)) {
          /*   拼接optoin对象   */
          let keyValue = !commonUtils.isEmpty(each.sSlaveId) ? each.sSlaveId : each.sId;
          if (this.firstDataIndex === 'i') {
            // eslint-disable-next-line radix
            keyValue = parseInt(keyValue);
          } else if (this.firstDataIndex === 'd') {
            keyValue = parseFloat(keyValue);
          }
          /*   返回值赋值   */
          options.push({ label: this.getOptionValues(each), value: keyValue });
        }
      }
    }

    /*   下拉空处理   */
    if (this.props.showConfig.bFirstEmpty) {
      options.push({ label: ' ', value: '=+@' });/* 解决销售订单-产品名称,五笔输入法输入不支持直接输入中文 */
    }
    /*   下拉新增处理   */
    if (this.props.showConfig.bNewRecord) {
      options.unshift({ label: 'NEW RECORD', value: '000' });
    }
    /*   返回值   */
    return options;
  };

  /**   获取optionValue对象   */
  getOptionValues = (data) => {
    /*   返回值声明   */
    let res = '';
    /*   计数器   */
    let count = 1;
    /*   遍历每一条数据   */
    const iVisCount = commonUtils.isEmpty(this.props.showConfig.iVisCount) || this.props.showConfig.iVisCount === 0 ? 1 : this.props.showConfig.iVisCount;
    if (commonUtils.isNotEmptyStr(this.props.showConfig.sVisColumnName)) {
      res = data[this.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;
  };

  /**   处理下拉选择事件   */
  handleSelectOptionEvent = (newValue) => {
    /*   下拉新增单独处理   */
    let value = newValue;
    this.isDropdownFilter = true;
    if (this.props.showConfig.sDropDownType === 'sql' && value === '000') {
      this.props.handleSqlDropDownNewRecord(this.props.showConfig, this.props.name);
      if (this.mounted) {
        // eslint-disable-next-line react/no-unused-state
        this.setState({ bReGetDropDown: true, dataValue: '' });
      }
      return;
    }
    if (this.props.showConfig.sDropDownType === 'sql' && value === '=+@') { /* 如果是选择空值，则将特殊字符过滤为空值 */
      value = '';
    }
    if (this.props.showConfig.sDropDownType === 'const' && value !== undefined && Array.isArray(value)) { /* const下拉 默认value [value]形式，需手动去掉[] */
      [value] = newValue;
    }
    if (this.props.showConfig.sDropDownType === 'sql' && value !== undefined && Array.isArray(value) && commonUtils.isNotEmptyObject(this.props.showConfig.sName) && (this.props.showConfig.sName.includes('sParamValue') || this.props.showConfig.sName.includes('sActValue'))) { /* Picker组件 默认[value]形式，需手动去掉[] */
      [value] = newValue;
    }
    /*   回带值声明   */
    const returnValue = {};
    /*   回带值赋值(sName:value)   */
    returnValue[this.props.showConfig.sName] =
        // eslint-disable-next-line radix
        this.firstDataIndex === 'i' ? commonUtils.isEmpty(value) ? undefined : parseInt(value) :
          this.firstDataIndex === 'd' ? commonUtils.isEmpty(value) ? '' : this.floatNumberCheck(value) :
            this.firstDataIndex === 't' ? commonUtils.isEmpty(value) ? null : value :
              this.firstDataIndex === 'b' ? value.target.checked : value === null ? undefined : value;
    const { sAssignField } = this.props.showConfig;
    const [changeData] = this.state.dropDownData.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();
            const sValueName = child.split(':')[1].trim();
            returnValue[sFieldName] = changeData[sValueName];
          }
        }
      } else if (!this.props.showConfig.bCanInput) {
        // 下拉选择空时，需要，  bCanInput一定要为false不然印件名称输入时也被置空了
        for (const child of sAssignFieldObj) {
          if (child.indexOf(':') > -1) {
            const sFieldName = child.split(':')[0].trim();
            returnValue[sFieldName] = '';
          }
        }
      }
    }
    /*   调用父组件的回带函数   */
    this.props.onChange(this.props.name, this.props.showConfig.sName, returnValue, this.props.sId, this.state.dropDownData);
  };

  handleFocus = () => {
    if(this.props.onFocus) {
      this.props.onFocus(this.props.showConfig);
    }
  }

  handleBlur = () => {
    if(this.props.onBlur) {
      this.props.onBlur(this.props.showConfig);
    }
  }

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

  // noinspection JSAnnotator
  // limitDecimals = (value) => {
  //   return commonUtils.filterDisNumberN(value, this.floatNum);
  // };
  // noinspection JSAnnotator
  /**   小数位控制  noinspection JSAnnotator控制 string | number */
  limitDecimals = (values) => {
    let reg = '';
    if (this.floatNum > 0) {
      reg = `^(\\d+).(${this.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 '';
    }
  };

  cancelValue = () => {
    const bClear = this.props.showConfig.sName!=='sLocationId' &&  this.props.showConfig.sName!=='sLocationNo' && this.props.showConfig.sName!=='sLocationName';
    if(bClear) {
      if (this.inputRef) this.inputRef.clearInput();
    }
  }

  handleFieldScan = (newValue) => {
    if (!newValue.trim()) return;
    this.props.onFieldScan(this.props.showConfig, this.props.name, this.props.record, newValue, this.cancelValue);
  }


  handleMobileScan = () => {
    this.props.onMobileScan(this.props.showConfig, this.props.name, this.props.record);
  }

  /**   渲染   */
  render() {
    const { sDateFormat: sDateFormatOld, sFieldValidation, bNotEmpty, bOpenKeyboard } = this.props.showConfig;
    let newValue = this.props.dataValue;
    if(commonUtils.isNotEmptyObject(sFieldValidation)) {
      const [length1, length2] = commonUtils.isNotEmptyObject(sFieldValidation) ?  sFieldValidation.split(',') :[];
      if (length2 !== undefined) {
        newValue = commonUtils.convertFixNum(this.props.dataValue, Number(length2));
      }
    }
    let sTitle = this.props.showConfig.showName;
    if (bNotEmpty) { /* 必填加星号 */
      sTitle = <div className='th-div' ><span className={styles.requireStyle}>*</span> {this.props.showConfig.showName}</div>;
    }else {
      sTitle = <div className='th-div' > {this.props.showConfig.showName}</div>;
    }
    const outFormItemProps = {
      ...this.getFieldProps(this.props.showConfig.sName),
      placeholder: this.props.showConfig.placeholder || '请输入',
      value: newValue,
      onChange: this.handleSelectOptionEvent, /*   数据改变回带到父组件   */
      disabled: !this.state.enabled,
    };
    if (this.props.showConfig.bNotSearch && !bOpenKeyboard) {
      outFormItemProps.virtualkeyboardpolicy = 'manual';
      outFormItemProps.inputmode = commonConfig.sMode === 1 ? 'none' : commonConfig.sMode === 2 ? 'numeric' : commonConfig.sMode === 3 ? 'search' : 'text';
    }
    let input = '';
    const isText = commonUtils.isNotEmptyObject(this.props.record) ? this.props.record.isText : false; /* 下拉框情况下 若record的isText为true则不渲染下拉框 */
    if ((this.props.showConfig.sDropDownType === 'sql' || this.props.showConfig.sDropDownType === 'const')
      && (this.firstDataIndex === 'i' || this.firstDataIndex === 'd' || this.firstDataIndex === 's') && !isText) { /*   下拉选择框(数字和文本选择框才会下拉)   */
      outFormItemProps.value = commonUtils.isEmpty(this.props.dataValue) ? [''] : [this.props.dataValue]; /* i、d也须是[this.props.dataValue]，否则会选择不上去 */
      outFormItemProps.onVisibleChange = (visible) => {
        if (!visible) return;
        Toast.loading('加载中 ....', 0);
        this.getDropDownData(this.props, false).finally( () => {
          Toast.hide();
        });
      }
      input = (
        <Picker data={this.getSelectOption()} cols={1} {...outFormItemProps} className="forss">
          <List.Item arrow="horizontal">
            {this.props.iconSettingShow ?
              // eslint-disable-next-line jsx-a11y/alt-text
              <img src={iconSetting} style={{ verticalAlign: 'sub', marginRight: '15px' }} alt="" /> : ''}
            {sTitle}
          </List.Item>
        </Picker>
      );
    } else if (this.firstDataIndex === 's') {
      if (this.props.textArea) { /*   大文本输入框   */
        input = (<TextareaItem title={this.props.showConfig.showName} {...outFormItemProps} autoHeight />);
      } else {
        const pdaPro = {
          disabled: !this.state.enabled,
          placeholder: this.props.showConfig.placeholder || '请输入或扫码',
          onFocus:this.handleFocus,
          virtualkeyboardpolicy: 'manual',
          inputmode: 'none',
        };
        // if(commonUtils.isNotEmptyObject(this.props.showConfig.sControlName) && this.props.showConfig.sControlName?.includes('Self')) {
        //   pdaPro.value = newValue;
        // }
        // console.log('bOpenKeyboard',this.props.showConfig.sName, bOpenKeyboard);
        const is_Pda = this.props.showConfig.sControlName && this.props.showConfig.sControlName.includes('_pda');
        const pdaInput = <InputItem id={this.props.showConfig.sName} {...pdaPro} ref={(el) => { this.inputRef = el; }} clear onChange={debounce(this.handleFieldScan, 1000)} >{sTitle}</InputItem>;
        const is_Scan = this.props.showConfig.sControlName && this.props.showConfig.sControlName.includes('_scan');
        if (is_Pda) {
          input = pdaInput;
        } else if (is_Scan) {
          input = <div style={{ position: 'relative' }}><InputItem clear {...outFormItemProps} >{sTitle}</InputItem><span className={styles.spanStyle} onClick={this.handleMobileScan}><img className={styles.scanStyle} src={scan} style={!this.state.enabled ? { opacity: 0.8 } : { opacity: 1 }} alt="scan" /></span></div>;
        } else {
          input = (<InputItem id={this.props.showConfig.sName} clear {...outFormItemProps} >{sTitle}</InputItem>);
        }
      }
    } else if (this.firstDataIndex === 'd') {
      outFormItemProps.moneyKeyboardAlign = 'left';
      outFormItemProps.moneyKeyboardWrapProps = moneyKeyboardWrapProps;
      input = (<InputItem clear {...outFormItemProps} type="digit" >{sTitle}</InputItem>);
    } else if (this.firstDataIndex === 't') {
      outFormItemProps.value = new Date(moment(this.state.dataValue).year(), moment(this.state.dataValue).month(), moment(this.state.dataValue).date());
      input = (<DatePicker mode="date" title="Select Date" extra="Optional" {...outFormItemProps}><List.Item arrow="horizontal">{sTitle}</List.Item></DatePicker>);
    } else if (this.firstDataIndex === 'b') {
      input = (<CheckboxItem {...outFormItemProps}>{this.props.showConfig.showName}</CheckboxItem>);
    }
    return (
      <div key={this.props.showConfig.sId} className={`${commonUtils.isEmpty(this.props.className) ? '' : this.props.className} ${this.props.formId === '100' ? styles.borderRadius : ''}`}>
        {input}
      </div>
    );
  }
}
