import webapi from './webapi'
import * as validator from '@/utils/validator'

// 定义需要校验的字段和校验规则, 支持同一个字段多条规则和异步校验，详情可参考
// https://github.com/yiminghe/async-validator
const descriptor = {
  code: [{ type: 'string', required: true, message: '请输入编码' }, {
    asyncValidator: async (rule, value, callback) => {
      const res = await webapi.validateFunctionCode(value)
      if (res.errorCode !== '0') {
        callback(res.errorMsg)
      } else {
        callback()
      }
    }
  }],
  name: { type: 'string', required: true, message: '请输入名称' },
  sortNo: [{ type: 'string', required: true, message: '请输入顺序' }, { pattern: /^\d{1,12}$/, message: '顺序必须是数字' }],
  busTypeId: { type: 'string', required: true, message: '请选择业务类型' },
  url: { type: 'string', required: true, message: '请输入路径' }
}

// 获取业务类型
export function getGusType(reduce, gf, data) {
  return async (dispatch, getState) => {
    const res = await webapi.getBusTypeArr({ "dicCode": "DICT_BUSINESS_TYPE_BACK" })
    if (res === undefined) return
    reduce('busType', { type: 'init', data: res.dic_DICT_BUSINESS_TYPE_BACK })
  }
}

// 提交表单
export function save(reduce, gf, data) {
  return async (dispatch, getState) => {
    // 获取表单数据
    const formObj = gf(['formObj'])
    const isEdit = gf(['tempState', 'isEdit'])
    formObj.sortNo = String(formObj.sortNo)
    // 字段校验。返回一个长度为2的数组，第一个是boolean值，代表是否校验成功，第二个是错误消息状态
    const [result, resultObj] = await validator.fieldValidator(formObj, descriptor)
    // 更新文本域验证状态
    reduce('validateState', { type: 'update', data: resultObj })
    let submitResult = false
    let saveResult

    if (result) {
      // 提交表单
      saveResult = await webapi.update(formObj)
      if (saveResult === undefined) {
        submitResult = false
      } else {
        // 新增或修改时记录时需要更新树
        if (!isEdit) {
          dispatch(getTreeChildrenData(reduce, gf, { functioinId: formObj.parentId, subNodeFlag: '1' }))
          // reduce('treeData', { type: 'addChildren', data: { ...formObj } })
        } else {
          reduce('treeData', { type: 'updateChildren', data: { ...formObj } })
        }
        submitResult = true
      }
    }
    return [result, resultObj, submitResult]
  }
}

export function updateFormObj(reduce, gf, fields) {
  return async (dispatch, getState) => {
    // 字段校验。返回一个长度为2的数组，第一个是boolean值，代表是否校验成功，第二个是错误消息状态
    const [result, resultObj] = await validator.fieldValidator(fields, descriptor)
    // 更新文本域验证状态
    reduce('validateState', { type: 'update', data: resultObj })
    // 更新表单数据
    reduce('formObj', { type: 'update', data: fields })
    return resultObj
  }
}

export function deleteItem(reduce, gf, fields) {
  return async (dispatch, getState) => {
    const formObj = gf(['formObj'])
    const result = await webapi.delDic(formObj)
    if (result.errorCode === '0') {
      dispatch(getTreeChildrenData(reduce, gf, { functioinId: formObj.parentId }))
      reduce('selectKey', { type: 'init', data: 0 })
      reduce('formObj', { type: 'reset', data: {} })
      return result
    }
  }
}

//////////////////three 组件//////////////////////////////////////////////

export function getTreeData(reduce, gf, data) {
  return async (dispatch, getState) => {
    const treeData = gf(['treeData'])
    if (treeData.length > 0) return
    const root = await webapi.getTreeData({})
    if (root === undefined) return
    reduce('treeData', { type: 'update', data: root })
  }
}

export function getTreeChildrenData(reduce, gf, { functioinId, ...orther }) {
  return async (dispatch, getState) => {
    const res = await webapi.getTreeData({
      pid: functioinId,
      level: 0
    })
    if (res === undefined) return null
    reduce('treeData', { type: 'updateChildren', data: { children: res, functioinId, ...orther } })
    return res
  }
}

export function getTreeNodeDetail(reduce, gf, functioinId) {
  return async (dispatch, getState) => {
    let res = await webapi.findById({ functioinId })
    if (res === undefined) return
    reduce('formObj', {
      type: 'update', data: {
        parentName: res.parentName,
        ...res.secFunctioinDTOReturn
      }
    })
    reduce('tempState', { type: 'setEdit', data: true })
  }
}