import React from 'react'
import { connect } from 'dva'
import { Cascader, message } from 'antd'
import {
  extendInclude,
  extendOrder,
  extendRule,
  getDataFieldValue,
  initFilter,
  getParseValue,
  constructStandardTreeData
} from '../utils/common'
import { isEqual, uniq } from 'lodash'

class CascaderInput extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      options: [],
      isadd: false
    }
  };

  componentDidMount () {
    this.fetchDatas()
  }

  componentDidUpdate (prevProps, prevState) {
    if (!isEqual(prevState.options, this.state.options)) {
      const { data, onLoadData } = this.props
      onLoadData instanceof Function && onLoadData(data.id, this.state.options)
    }
  }

  getPramas = (value) => {
    const { data, record, app } = this.props
    const { sortField, showField, sortOrder, navField, extIncludeFields, showLevel } = data || {}
    const loadParam = initFilter(this.props.login.OrgId, '', '', 0)
    const sortFields = sortField ? sortField.split(',') : []
    const sortOrders = sortOrder ? sortOrder.split(',') : []
    const arrShowField = showField ? showField.split(',') : ['CODE', 'NAME']
    loadParam['Level'] = value ? 1 : (showLevel || 0)
    loadParam['MenuParameter'] = app.currActivatedMenu && app.currActivatedMenu.MENU_FORM_PARAMS ? app.currActivatedMenu.MENU_FORM_PARAMS : ''
    // 添加自定义排序
    if (sortFields && sortOrders && sortFields.length && sortOrders.length) {
      loadParam['Sort'] = ''
      sortFields.forEach((n, i) => {
        extendOrder(loadParam, n, sortOrders[i])
      })
    }
    if (value) {
      extendRule(loadParam, 'PARENT_ID', 1, value)
    }

    const { colConfig, thisRef } = this.props
    if (colConfig && colConfig.column) {
      const getRowFieldValue = (field) => {
        return getDataFieldValue(record, field)
      }
      if (colConfig.column.Nav_Filters && colConfig.column.Nav_Filters.length) {
        colConfig.column.Nav_Filters.forEach(t => {
          const v = getParseValue(t.VALUE, thisRef.props.login.user, (field) => { return thisRef.getFieldValue(field, thisRef) }, getRowFieldValue)
          if (v !== null && v !== undefined) {
            if (t.IS_CUSTOM) {
              loadParam[t.FIELD_NAME] = v
            } else {
              extendRule(loadParam, t.FIELD_NAME, t.OPERATION, v, t.IS_SYS_PARAM)
            }
          }
        })
      }
    }

    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 (arrShowField && arrShowField.length > 0) {
      arrShowField.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 = uniq(navFields)
      tmp.forEach((n, i) => {
        extendInclude(loadParam, n)
      })
    }
    return loadParam
  }

  getLabelByShowField = opt => { // 根据下拉显示字段 配置
    const { data } = this.props
    const { showField } = data || {}
    const arrShowField = showField ? showField.split(',') : ['NAME']
    const nodearr = arrShowField.map((i, key) => {
      if (key < arrShowField.length && key > 0) {
        const v1 = getDataFieldValue(opt, i)
        return '-' + (v1 == null ? '空' : v1)
      } else {
        const v1 = getDataFieldValue(opt, i)
        return (v1 == null ? '空' : v1)
      }
    })
    return nodearr
  }

  fetchDatas = (selectedOptions = []) => { // 获取级联数据
    const targetOption = selectedOptions.length ? selectedOptions[selectedOptions.length - 1] : {}
    const { options } = this.state
    const { api, data } = this.props
    if (!api) return
    targetOption.loading = true
    const loadParam = this.getPramas(targetOption.ID)
    this.props.dispatch({
      type: 'app/getTableData',
      payload: loadParam,
      url: api,
      onComplete: (ret) => {
        targetOption.loading = false
        if (ret && ret.IsSuccessful && ret.Data) {
          // 一次性加载全部数据
          if (data.showLevel === -1) {
            constructStandardTreeData(ret.Data, true)
            this.setState({ options: ret.Data })
            return
          }
          for (const resp of ret.Data) {
            const isLeaf = resp.IsLeaf || !!(data.showLevel && data.showLevel >= 0 && (selectedOptions.length + 1 >= data.showLevel))
            const option = {
              ...resp.Node,
              value: resp.Node.ID,
              label: this.getLabelByShowField(resp.Node),
              // isLeaf: resp.IsLeaf || (selectedOptions ? selectedOptions.length + 1 === (data.showLevel || 3) : (data.showLevel || 3) === 1)
              isLeaf
            }
            if (!selectedOptions.length) {
              options.push(option)
            } else {
              if (!targetOption.children) targetOption.children = []
              targetOption.children.push(option)
            }
          }
          if (!ret.Data.length && !targetOption.isLeaf) {
            targetOption.isLeaf = true
            this.onChange(selectedOptions.map(so => so.ID), selectedOptions)
          }
          this.setState({
            options
          })
        } else {
          ret && message.error(ret.ErrorMessage)
        }
      }
    })
  }

  onChange = (value, selectedOptions) => {
    const { onChange, onSelect, data } = this.props
    const { navField } = data || {}
    if (typeof onSelect === 'function') {
      const navFields = navField ? navField.split(',') : ['ID']
      const saveValues = []
      for (let j = 0; j < navFields.length; j++) {
        saveValues.push(getDataFieldValue(selectedOptions[selectedOptions.length - 1], navFields[j]))
      }
      onSelect({
        data: saveValues,
        record: selectedOptions[selectedOptions.length - 1],
        colConfig: this.props.colConfig,
        thisRef: this.props.thisRef
      })
    } else if (typeof onChange === 'function') {
      onChange({
        value: (value && value.length > 0 ? value.join(',') : null),
        colConfig: this.props.colConfig,
        thisRef: this.props.thisRef
      })
    }
  }

  loadData = selectedOptions => {
    this.fetchDatas(selectedOptions)
  }

  displayRender = (label, selectedOptions) => {
    const { data, value } = this.props
    const { labelField } = data || {}
    if (selectedOptions.length === 0) {
      return value
    }
    const lastItem = selectedOptions[selectedOptions.length - 1]
    return lastItem[(labelField || 'NAME')]
  }

  render () {
    const { data, disabled, placeholder, style, value, colConfig } = this.props
    const { options } = this.state
    return (
      <Cascader
        changeOnSelect={!data.onlyLeaf}
        style={style}
        disabled={disabled}
        placeholder={placeholder || `请选择${colConfig.label}`}
        options={options}
        loadData={data.showLevel !== -1 ? this.loadData : null}
        onChange={this.onChange}
        displayRender={this.displayRender}
        value={value && value.split(',')}
      />
    )
  }
}

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