/* eslint-disable object-property-newline */
import { message } from 'antd'
import { getParseValueByDate, getDataFieldValue, getParseValue, guid } from './common'
import moment from 'moment'

// dateType 对应 controlType
const dataMapControl = { 2: 7, 3: 3, 4: 4, 5: 10, 6: 12, 8: 17, 9: 18, 10: 19, 11: 9, 12: 20, 13: 21, 14: 11, 15: 22, 16: 23, 17: 2, 108: 108 }

export function getFieldConfigs({ field, onLoadData, onPressEnter, onSelect, onChange, onSearchRef }) {
  const controlType = dataMapControl[field.DATA_TYPE] || 1
  const configId = field.ID || guid()
  const {
    QUERY_NAME,
    LABEL: label,
    DATA_TYPE: dataType,
    DATA_VALUE: dataValue,
    OP_DEFAULT: operator,
    IS_CUSTOM: isCustom,
    IS_SYS_PARAM: isSysParam,
    IS_TITLE: isExportTitle,
    ENUM_NAME: enumName,
    NUM: num,
    CODE: code,
    FEILD_TYPE: fieldType,
    IS_DEFAULT_QUERY: isDefaultQuery,
    USER_C_C_QUERY_GROUP_ID: searchGroupId,
    IS_SYS_QUERY_FIELD: isSysQueryField,
    USER_C_C_QUERY_ID: userCCQueryId,
    CASE: caseType,
    IS_REQUIRE: isRequire,
    INPUT_DATA_API: api,
    INPUT_DATA_LEVEL: showLevel,
    IS_ONLY_CHECK_LEAF: onlyLeaf,
    MULTIPLE_CHOICE: multipleChoice,
    CHECK_STRICTLY: checkStrictly,
    SELECT_CONDITION: selectCondition,
    INPUT_ID_FIELD: idField,
    INPUT_SAVE_FIELD: saveField,
    INPUT_NAV_FIELD: navField,
    INPUT_FILTER_FIELD: filterField,
    INPUT_LABEL_FIELD: labelField,
    INPUT_SHOW_FIELD: showField,
    INPUT_SORT_FIELD: sortField,
    INPUT_SORT_ORDER: sortOrder,
    INPUT_FILTER_ORG_TYPE: filterOrgType,
    INPUT_KEEP_VALUE_BY_NO_SRC: isKeepValueByClear,
    DATETIME_FORMATE:datetimeformate
  } = field
  const config = {
    id: configId, field: QUERY_NAME, label, controlType, dataType, dataValue, operator, isCustom, isSysParam, isExportTitle,
    enumName, num, code, fieldType, isDefaultQuery, searchGroupId, isSysQueryField, userCCQueryId, caseType, isRequire,
    style: { width: controlType === 4 ? 'auto' : '100%' },
    data: {
      id: configId, dataValue, enumName, api, showLevel, onlyLeaf, multipleChoice, checkStrictly, selectCondition, isExportTitle, idField,
      saveField, navField, filterField, labelField, showField, sortField, sortOrder, filterOrgType, isKeepValueByClear,datetimeformate,
      // 提供给 getControl.js 的组件调用
      onLoadData,
      onPressEnter,
      // 分页下拉
      onSelect: dataType === 11 ? onSelect : undefined,
      onSearchRef
    },
    // 提供给 getControl.js 的组件调用
    onChange
  }
  if (dataValue) {
    const dates = getParseValueByDate(dataValue) || [moment(), moment()]
    switch (controlType) {
      case 3: // 单选下拉，都是从 ENUM 枚举选择的，ENUM 值都是数字
      case 7: // 数字输入：InputNumber
        config.defaultValue = +dataValue // 将字符串转成数字
        break
      case 4: // 开关控件：Switch
        config.defaultValue = !!(dataValue === '1' || dataValue === 'true' || dataValue === 'True')
        break
      case 2: // 时间控件：日期选择 ==> date: 日
        config.defaultValue = moment(dates[0]).format('YYYY-MM-DD')
        break
      case 10: // 时间控件：区间选择精确到日：2020-09-22
        config.defaultValue = dates.map(d => d.format('YYYY-MM-DD')).join(',')
        break
      case 18: // 月份选择，格式化为每月一号：2020-09-01
        config.defaultValue = moment(dates[0].format('YYYY-MM')).format('YYYY-MM-DD')
        break
      case 19: // 月份区间，格式化为每月一号：2020-09-01
        config.defaultValue = dates.map(d => moment(d.format('YYYY-MM')).format('YYYY-MM-DD')).join(',')
        break
      case 20: // 年份选择，格式化为每年一月一号：2020-01-01
        config.defaultValue = moment(dates[0].format('YYYY')).format('YYYY-MM-DD')
        break
      case 21: // 年份区间，格式化为每年一月一号：2020-01-01
        config.defaultValue = dates.map(d => moment(d.format('YYYY')).format('YYYY-MM-DD')).join(',')
        break
      case 22: // 年月日时分秒区间
        config.defaultValue = dates.map(d => moment(d).format('YYYY-MM-DD HH:mm:ss')).join(',')
        break
      case 23: // 年月日时分区间
        config.defaultValue = dates.map(d => moment(d).format('YYYY-MM-DD HH:mm')).join(',')
        break
      default:
        config.defaultValue = dataValue
        break
    }
  }
  return config
}

// controlType 对应 operate 操作符，例如：1: '9' 意思是：文本输入框: 包含
const optFormat = { 1: '9', 2: '1', 7: '1', 3: '1', 4: '1', 9: '1', 10: '1', 11: '1', 12: '1', 17: '1', 18: '1', 19: '1', 20: '1', 21: '1', 22: '1', 23: '1' }

export function getRuleByFieldConfigs(data, configs, list, groupList,user) {
  let errorLabel = false
  configs.forEach(item => {
    let val = getDataFieldValue(data, item.id)
    item.controlType === 7 && val === '' && (val = null)
    if (val === null || val === undefined || !item.field) {
      item.isRequire && (errorLabel = item.label)
      return
    }

    // 10: 时分秒区间组件 18：月份 19：月份区间 20：年份 21：年份区间
    if (
      item.controlType === 10 ||
      item.controlType === 18 ||
      item.controlType === 19 ||
      item.controlType === 20 ||
      item.controlType === 21
    ) {
      const temps = val.split(',')
      if (!item.isCustom) {
        const group = {
          isAnd: true,
          rules: []
        }
        temps.forEach((tmp, index) => {
          const tmpVal = index === 0 ? moment(tmp).format('YYYY-MM-DD') : moment(moment(tmp).format('YYYY-MM-DD')).add(1, 'd').subtract(1, 's').format('YYYY-MM-DD HH:mm:ss')
          const monthVal = moment(moment(tmp).format('YYYY-MM')).format('YYYY-MM-DD')
          const yearVal = moment(moment(tmp).format('YYYY')).format('YYYY-MM-DD')
          group.rules.push({
            field: item.field,
            operator: index === 0 ? '6' : '4',
            value: item.dataType === 5 ? tmpVal : (item.dataType === 9 || item.dataType === 10 ? monthVal : yearVal),
            isCustom: item.isCustom
          })
        })
        groupList.push(group)
      } else {
        const vas = temps.map((time, timeIndex) => {
          return timeIndex === 0 ? moment(time).format('YYYY-MM-DD') : moment(moment(time).format('YYYY-MM-DD')).add(1, 'd').subtract(1, 's').format('YYYY-MM-DD HH:mm:ss')
        })
        // 将 2020-07-18 格式化成 2020-07-01 月份开始的时间
        const monthFormat = moment(moment(vas[0]).format('YYYY-MM')).format('YYYY-MM-DD')
        const monthEndFormat = moment(moment(vas[1]).format('YYYY-MM')).format('YYYY-MM-DD')
        // 将 2020-07-18 格式化成 2020-01-01 月份开始的时间
        const yearFormat = moment(moment(vas[0]).format('YYYY')).format('YYYY-MM-DD')
        const yearEndFormat = moment(moment(vas[1]).format('YYYY')).format('YYYY-MM-DD')
        let dateVal = vas.join(',')
        switch (item.controlType) {
          case 18:
            dateVal = monthFormat
            break
          case 19:
            dateVal = [monthFormat, monthEndFormat].join(',')
            break
          case 20:
            dateVal = yearFormat
            break
          case 21:
            dateVal = [yearFormat, yearEndFormat].join(',')
            break
          default:
            break
        }
        list.push({
          field: item.field,
          operator: 0,
          value: dateVal,
          isCustom: item.isCustom,
          isSysParam: item.isSysParam
        })
      }
    }
    // 下拉多选
    else if (item.dataType === 6) {
      let temps = []
      const strVal = val.toString()
      const splitStr = strVal.indexOf(',') !== -1 ? ',' : strVal.indexOf('_') !== -1 ? '_' : ''
      splitStr && (temps = strVal.split(splitStr).filter(validStr => validStr))
      if (!item.isCustom) {
        const group = {
          isAnd: false,
          rules: []
        }
        temps.forEach(tmp => {
          group.rules.push({
            field: item.field,
            operator: '1',
            value: tmp,
            isCustom: item.isCustom,
            isSysParam: item.isSysParam
          })
        })
        groupList.push(group)
      } else {
        list.push({
          field: item.field,
          operator: 0,
          value: val,
          isCustom: item.isCustom,
          isSysParam: item.isSysParam
        })
      }
    }
    // 级联选择
    else if (item.dataType === 8) {
      const temps = val.split(',')
      list.push({
        field: item.field,
        operator: item.operator ? item.operator : optFormat[item.controlType],
        value: temps[temps.length - 1],
        isCustom: item.isCustom,
        isSysParam: item.isSysParam
      })
    }
    // 分页下拉
    else if (item.dataType === 11) {
      const { navField, saveField } = item.data
      const navFields = navField ? navField.split(',') : ['ID']
      const saveFields = saveField ? saveField.split(',') : []
      const record = getDataFieldValue(data, `selectedRecord.${item.id}`)

      let tempList = list
      if (!item.isCustom) {
        const group = {
          isAnd: false,
          rules: []
        }
        groupList.push(group)
        tempList = group.rules
      }
      saveFields.forEach((sf, sfIndex) => {
        tempList.push({
          field: sf,
          operator: '1',
          value: getDataFieldValue(record, navFields[sfIndex]),
          isCustom: item.isCustom,
          isSysParam: item.isSysParam
        })
      })
    }
    // 树选择
    else if (item.dataType === 14) {
      const { multipleChoice } = item.data || {}
      if (multipleChoice && !item.isCustom) {
        const temps = val.split(',')
        temps.forEach(tmp => {
          list.push({
            field: item.field,
            operator: item.operator ? item.operator : optFormat[item.controlType],
            value: tmp,
            isCustom: item.isCustom,
            isSysParam: item.isSysParam
          })
        })
      } else {
        list.push({
          field: item.field,
          operator: item.operator ? item.operator : optFormat[item.controlType],
          value: val,
          isCustom: item.isCustom,
          isSysParam: item.isSysParam
        })
      }
    }
    else {
      val = getParseValue(val, user, null, null);
      val && typeof val === 'string' && (val = val.toString().replace(/(^\s*)|(\s*$)/g, ''))
      list.push({
        field: item.field,
        operator: item.operator ? item.operator : optFormat[item.controlType],
        value: val,
        isCustom: item.isCustom,
        isSysParam: item.isSysParam
      })
    }
  })
  errorLabel && message.error('查询字段' + errorLabel + '必须设置条件')
  return errorLabel
}

export function getGroupByGroupConfigs(data, configs, parent, list) {
  for (let i = 0, j = configs.length; i < j; i++) {
    const group = {
      rules: [],
      childGroups: [],
      isAnd: configs[i].relationType !== 1
    }
    if (configs[i].fieldConfigs && configs[i].fieldConfigs.length) {
      const errorLabel = getRuleByFieldConfigs(data, configs[i].fieldConfigs, group.rules, group.childGroups)
      if (errorLabel) return errorLabel
    }
    if (parent) {
      parent.childGroups.push(group)
    } else {
      list.push(group)
    }
    if (configs[i].childGroups && configs[i].childGroups.length) {
      const result = getGroupByGroupConfigs(data, configs[i].childGroups, group, list)
      if (result) return result
    }
  }
}
