/**
 * 业务公共处理类
 * @author luolin
 */
import {validateNull} from "/@/utils/validate";
import {deepClone} from "/@/utils/other";

// 校验是否为对象或数组
export function validateObjArr(objArr) {
  return objArr instanceof Array || objArr instanceof Object;
}

// 处理克隆
export function handleClone(_this, form: any, ...keys?: string[]) {
  if (_this.operType !== 'add' && _this.operType !== 'copy') return
  if (!form) form = _this.form
  setPropsNull(form, 'code', 'status', 'finishTime', 'createUser', 'createTime', 'updateUser', 'updateTime')
  // 自定义清空字段
  setPropsNull(form, ...keys)
  return form
}

// 处理克隆提交前
export function handleCloneSubmit(_this, row?: any, callback?: Function) {
  if (_this.operType !== 'add' && _this.operType !== 'copy') return
  if (!row) row = _this.form
  row = handleClone(_this, row)
  setPropsNull(row, 'id', 'flowInstId')
  if (callback) callback(row)
}

// 设置属性值null
// @ts-ignore
export function setPropsNull(form: any, ...keys?: string[]) {
  if (arguments.length < 2) return
  let args = Array.prototype.slice.call(arguments)
  for (let i = 1; i < args.length; i++) {
    form[args[i]] = null
  }
}

// 统一设置属性值
// @ts-ignore
export function setPropsValue(form: any, value: any, ...keys?: string[]) {
  if (arguments.length < 3) return
  let args = Array.prototype.slice.call(arguments)
  for (let i = 2; i < args.length; i++) {
    form[args[i]] = value
  }
}

// 重置表单数据
// @ts-ignore
export function setPropsNullValue(form: any, data: any, ...keys?: string[]) {
  if (arguments.length < 3) {
    keys = Object.keys(form)
  }
  setPropsNull(form, ...keys)
  if (validateNull(data)) return
  setPropsDataValue(form, data, keys)
}

// 设置属性为data值
// @ts-ignore
export function setPropsDataValue(form, data, keys?: string[]) {
  if (arguments.length < 3) {
    let keys = Object.keys(data);
    for (let i = 2; i < keys.length; i++) {
      if (!validateNull(data[keys[i]])) form[keys[i]] = data[keys[i]]
    }
    return
  }
  let args = Array.prototype.slice.call(arguments)
  // 第三个参数是否为数组
  if (args[2] instanceof Array) {
    args[2].forEach(key => {
      if (!validateNull(data[key])) {
        // 防止相同引用
        if (validateObjArr(data[key])) form[key] = deepClone(data[key])
        else form[key] = data[key]
      }
    })
  } else {
    for (let i = 2; i < args.length; i++) {
      if (!validateNull(data[args[i]])) form[args[i]] = data[args[i]]
    }
  }
}

// 设置Crud queryForm
export function setCrudQueryForm(_this, ...params?) {
  if (arguments.length < 2) return
  let args = Array.prototype.slice.call(arguments)
  // 单个修改
  for (let i = 1; i < args.length; i++) {
    _this.queryForm[args[i].prop] = args[i].value
  }
}
