import React from 'react'
import { connect } from 'dva/index'
import { Input, Icon } from 'antd'
import FormModal from '../form/FormModal'
import {
  extendFilterGroup,
  extendGroupRule,
  extendInclude,
  extendOrder,
  initFilter,
  initFilterGroup
} from '../utils/common'
import moment from 'moment'

class ScannerComponent extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      data: {
        Data: []
      },
      value: '',
      oldValue: ''
    }
    this.handleAutoCompleteKeyDown = this.handleAutoCompleteKeyDown.bind(this)
  };

  componentDidMount () {
    const { value } = this.props
    this.updateStateData({
      value: value,
      oldValue: value,
      isUpdateValue: false
    })
  }

  UNSAFE_componentWillReceiveProps (NextProps) {
    const { value } = NextProps
    if (this.state.oldValue !== value || this.state.isUpdateValue) {
      this.updateStateData({
        value: value,
        oldValue: value,
        isUpdateValue: false
      })
    }
  }

  handleFetchAutoFilterEvent = (params) => {
    const { data } = this.props
    const { onFilter } = data || {}
    if (typeof onFilter === 'function') {
      onFilter({
        params: params,
        colConfig: this.props.colConfig,
        thisRef: this.props.thisRef
      })
    }
  };

  updateStateData = (data, onComplete) => {
    if (this.updateStateDataFunc) {
      this.setState(data, () => {
        this.updateStateDataFunc(data, onComplete)
      })
    } else {
      this.setState(data, () => {
        if (typeof onComplete === 'function') {
          onComplete()
        }
      })
    }
  };

  regUpdateStateData = (regFunc) => {
    this.updateStateDataFunc = regFunc
  };

  getAutoCompleteLoadParam = (params = {}, e) => {
    const { data } = this.props
    const { filterField, sortField, sortOrder, navField, extIncludeFields } = data || {}
    const sortName = filterField ? filterField.split(',') : ['NAME', 'CODE']
    const initParams = initFilter(this.props.login.OrgId, '', sortName[0], 0)
    const sortFields = sortField ? sortField.split(',') : []
    const sortOrders = sortOrder ? sortOrder.split(',') : []

    if (e) {
      if (e.target.value) {
        const group = initFilterGroup(false)
        sortName.forEach((i, n) => {
          extendGroupRule(group, i, 9, e.target.value)
        })
        extendFilterGroup(initParams, group)
      }
      this.updateStateData({
        autoChangeValue: e.target.value
      })
    }
    const loadParam = { ...initParams, ...params }
    // 添加自定义排序
    if (sortFields && sortOrders && sortFields.length && sortFields.length && sortOrders.length) {
      loadParam['Sort'] = ''
      sortFields.forEach((n, i) => {
        extendOrder(loadParam, n, sortOrders[i])
      })
    }
    const navFields = []
    // 添加导航属性
    const tmpNavFields = navField ? navField.split(',') : ['ID']
    if (tmpNavFields && tmpNavFields.length > 0) {
      tmpNavFields.forEach(t => {
        if (t && t.indexOf('.') > 0) {
          const pos = t.lastIndexOf('.')
          const includeField = t.substring(0, pos)
          navFields.push(includeField)
        }
      })
    }
    // 填充导航属性
    if (extIncludeFields) {
      extIncludeFields.forEach(t => {
        navFields.push(t)
      })
    }

    // 去重添加
    if (navFields.length) {
      const tmp = [...new Set(navFields)]
      tmp.forEach((n, i) => {
        extendInclude(loadParam, n)
      })
    }
    return loadParam
  };

  fetchAutoComData = (params = {}, e) => { // 获取autocomplete数据
    const { api, data } = this.props
    if (!api) {
      return
    }
    const loadParam = this.getAutoCompleteLoadParam(params, e)
    if (data && data.filterOrgType) {
      loadParam.OrgType = data.filterOrgType
    }
    this.handleFetchAutoFilterEvent(loadParam)
    this.updateStateData({
      loadParam
    })
    this.props.dispatch({
      type: 'app/getDataByPost',
      payload: loadParam,
      url: api,
      onlyData: false,
      onComplete: (ret) => {
        this.updateStateData({ data: ret }, () => {
          if (ret && ret.Data && ret.Data.length) {
            this.selectAutoItem(ret.Data[0].ID)
          }
          else {
            this.selectAutoItem(null)
          }
        })
      }
    })
  };

  // autoComDataPage = ( num) => {
  //   const { data } = this.props;
  //   const {filterField }=data?data:{};
  //   const arrOBj = filterField ? filterField.split(','):['NAME','CODE'];
  //   const sortName = filterField ? filterField.split(',') : ['NAME','CODE'];
  //   let params = initFilter(this.props.login.OrgId,'',sortName[0],0,num);
  //   if (this.state.autoChangeValue) {
  //     let group=initFilterGroup(false);
  //     arrOBj.forEach((i,n) => {
  //       extendGroupRule(group,i,9,this.state.autoChangeValue);
  //     });
  //     extendFilterGroup(params,group);
  //   }
  //   this.fetchAutoComData( params);
  // };
  // getState=()=> {
  //   return this.state;
  // };

  handleFieldChangeEvent = (value) => {
    const { data } = this.props
    const { onChange } = data || {}
    if (typeof onChange === 'function') {
      onChange({
        value,
        colConfig: this.props.colConfig,
        thisRef: this.props.thisRef
      })
    }
    this.updateStateData({
      value: value
    })
    if (!value) {
      this.selectAutoItem(null)
    }
    else {
      if (!this.isSelectItem) {
        if (value.toString().indexOf('-') === -1) {
          this.isCheckAutoComplete = true
        }
      }
    }

    // this.props.dispatch({
    //   type: 'app/save',
    //   payload: {
    //     drawerComponent: {
    //       open: true,
    //       content: 20,
    //       position: "top",
    //       selfData: {
    //         data: this.state.data,
    //         disabled: this.props.disabled,
    //         loadParam: this.state.loadParam,
    //         autoChangeValue: this.state.autoChangeValue,
    //         selectAutoItem: this.selectAutoItem,
    //         handleChangeAuto: this.handleChangeAuto,
    //         autoComDataPage: this.autoComDataPage
    //       }
    //     },
    //   },
    // });
  };

  getDataByScannerValue = (value) => {
    const { api, onScan } = this.props
    if (!api) {
      if (typeof onScan === 'function') {
        onScan({ value })
      }
      return
    }
    if (this.isSelectItem) {
      return
    }
    const { data } = this.props
    const { filterField, onChangeHandle } = data || {}
    const arrOBj = filterField ? filterField.split(',') : ['NAME', 'CODE']
    const sortName = filterField ? filterField.split(',') : ['NAME', 'CODE']
    const params = initFilter(this.props.login.OrgId, '', sortName[0], 0)
    if (value) {
      const group = initFilterGroup(false)
      arrOBj.forEach((i, n) => {
        extendGroupRule(group, i, 9, value)
      })
      extendFilterGroup(params, group)
    }
    const nowT = moment().format('x')
    if (!this.autoCompleteChangeT || nowT - this.autoCompleteChangeT > 200) {
      this.fetchAutoComData(params)
    }
    this.updateStateData({
      autoChangeValue: value
    })
    this.autoCompleteChangeT = moment().format('x')
    this.handleFieldChangeEvent(value)
    if (onChangeHandle && typeof onChangeHandle === 'function') {
      onChangeHandle(value)
    }
  };

  handleAutoCompleteKeyDown (event) {
    if (event.keyCode === 13) {
      this.isCheckAutoComplete = true
      // this.checkAutoComplete();
      this.getDataByScannerValue(this.state.autoChangeValue)
    }
  }

  checkAutoComplete = () => {
    if (this.isCheckAutoComplete) {
      this.getDataByScannerValue(this.state.autoChangeValue)
    }
  };

  selectAutoItem = (value, option) => {
    const { data, onSelect } = this.props
    const { navField } = data || {}
    this.isSelectItem = true
    this.isCheckAutoComplete = false
    if (typeof onSelect === 'function') {
      if (value) {
        if (this.state.data && this.state.data.Data) {
          const navFields = navField ? navField.split(',') : ['ID']
          this.state.data.Data.forEach(t => {
            if (value === t.ID) {
              const saveValues = []
              for (let j = 0; j < navFields.length; j++) {
                saveValues.push(t[navFields[j]])
              }
              onSelect({
                data: saveValues,
                record: t,
                complete: () => {
                  this.isSelectItem = false
                },
                colConfig: this.props.colConfig,
                thisRef: this.props.thisRef
              })
            }
          })
        }
      }
      else {
        onSelect({
          data: [],
          record: null,
          isClear: true,
          complete: () => {
            this.isSelectItem = false
          },
          colConfig: this.props.colConfig,
          thisRef: this.props.thisRef
        })
        this.updateStateData({
          isUpdateValue: true
        })
      }
    }
  };

  render () {
    const { disabled, onChange, onBlur, placeholder, showFormCode, showFormId } = this.props
    const isShowSrcBtn = showFormCode && showFormId
    const value = this.state.value
    return (
      <>
        <Input
          placeholder={placeholder}
          clear
          value={value}
          disabled={disabled}
          style={isShowSrcBtn ? { width: '80%' } : { width: '100%' }}
          onBlur={() => {
            if (typeof onBlur === 'function') {
              onBlur()
            }
            this.checkAutoComplete()
          }}
          onChange={(e) => {
            if (e !== null && e !== undefined) {
              const tmpValue = (e && e.target && e.target.value ? e.target.value : (typeof e === 'object' ? null : e))
              // if(tmpValue&&caseType&&caseType===1){
              //   tmpValue=tmpValue.toString().toUpperCase();
              // }
              // else if(tmpValue&&caseType&&caseType===2){
              //   tmpValue=tmpValue.toString().toLowerCase();
              // }
              this.isCheckAutoComplete = true
              this.updateStateData({
                autoChangeValue: tmpValue
              })
              if (typeof onChange === 'function') {
                onChange({
                  value: tmpValue
                })
              }
            }
          }}
          onKeyDown={(e) => { this.handleAutoCompleteKeyDown(e) }}
          addonAfter={<Icon type='enter' onClick={() => { this.checkAutoComplete() }} />}
        />
        {
          isShowSrcBtn
            ? (
              <FormModal formCode={showFormCode} data={{ id: showFormId, isShow: true }}>
                <Icon type='info-circle' style={{ marginLeft: 8, fontSize: 20 }} />
              </FormModal>
            ) : null
        }
      </>
    )
  }
}

export default connect(({ app, loading, login }) => ({ app, loading, login }))(ScannerComponent)
