import { axios } from '@/utils/request'
import store from '@/store'
import BigJs from "big.js";

import { UPCLOUD_RDC_TMS_MAINDATA_SERVICE } from '@/config/serviceSettings.js'
const serviceName = UPCLOUD_RDC_TMS_MAINDATA_SERVICE

function getDictionaryOptions(params) {
  return axios({
    url: serviceName + '/refdata/dtl/dd-list',
    method: 'post',
    data: params
  })
}

function getPart(params) {
  return axios({
    url: serviceName + '/refdata/get/v1.0',
    method: 'post',
    data: params
  })
}

// 批量获取字典 isNumber:是否格式化value成数字
export const initDictionary = (params, isNumber) => {
  return new Promise((resolve, reject) => {
    getDictionaryOptions(params)
      .then(res => {
        if (res.success && res.data) {
          const { data } = res
          const keys = Object.keys(data)
          for (let index = 0; index < keys.length; index++) {
            const key = keys[index]
            data[key] = data[key].map(item => ({ label: item.text, value: (isNumber && !isNaN(+item.value)) ? +item.value : item.value }))
          }
          resolve(data)
        }
      })
      .catch(err => reject(err))
  })
}

// 通过value获取label
export const getLabelFromValue = (value, options) => {
  if (!options || (value === undefined || value === null) || typeof options !== 'object') {
    return ''
  }
  const index = options.findIndex(item => item.value == value)
  if (index === -1) {
    return ''
  }
  return options[index].label
}

// 获取字典所有数据
export const initDictionaryAll = params => {
  return new Promise((resolve, reject) => {
    getPart(params)
      .then(res => {
        if (res.success && res.data) {
          const list = res.data.map(item => {
            return {
              label: item.name,
              value: item.code,
              ...item
            }
          })
          resolve(list)
        }
      })
      .catch(err => reject(err))
  })
}

export const dealNullQueryCondition = obj => {
  for (var p in obj) {
    if (obj[p] === '' || (obj[p] !== 0 && obj[p] !== false && !obj[p] && (typeof obj[p] !== 'boolean' || typeof obj[p] !== 'number'))) {
      delete obj[p]
    }
  }
  return obj
}

export const extendedFieldList = params => {
  return new Promise((resolve, reject) => {
    axios({
      url: serviceName + '/extendedField/list',
      method: 'post',
      data: params
    })
      .then(res => {
        if (res.success && res.data) {
          resolve(res.data)
        }
      })
      .catch(err => reject(err))
  })
}

export const resultExtendedField = params => {
  return extendedFieldList(params).then(data => {
    if (data) {
      //displayName: "扩展字段-1"
      // extendedObjectCode: "11"
      // extendedObjectName: "司机管理"
      // fieldChoiceValue: null
      // fieldName: "extStr1"
      // fieldSort: null
      // fieldType: "1"
      // fieldTypeName: "文本输入框"
      // lineid: "d4624d8d45ff4691afac34ab9df0b7db"

      let table = []
      let form = []
      let formType = function (item) {
        let arr = [
          {
            type: 'input'
          },
          {
            type: 'number'
          },
          {
            type: 'date',
            format: 'YYYY-MM-DD HH:mm:ss'
          },
          {
            type: 'select',
            options:
              item.fieldChoiceValue &&
              item.fieldChoiceValue.split(',').map(txt => {
                return {
                  value: txt,
                  label: txt
                }
              })
          }
        ]

        return arr[+item.fieldType - 1]
      }

      data.map(item => {
        const { displayName, fieldName } = item
        table.push({
          dataIndex: fieldName,
          title: displayName,
          width: 120,
        }),
          form.push({ name: fieldName, label: displayName, ...formType(item), value: '' })
      })

      return { table, form, list: data }
    }
    return null
  })
}

//函数节流
export const throttle = function (fn, wait) {
  let last = 0
  let dur = wait || 1000
  return function () {
    let self = this
    const current_time = +new Date()
    if (current_time - last > dur) {
      fn.apply(self, arguments)
      last = +new Date()
    }
  }
}

//函数防抖;
export const debounce = function (fn, wait) {
  let timer
  let dur = wait || 400
  return function () {
    clearTimeout(timer)
    let self = this
    let args = arguments
    timer = setTimeout(() => {
      fn.apply(self, args)
    }, dur)
  }
}

/*
 * @method 日期格式化
 * @param time {Date}- 要格式化的日期
 * @param format {string} - 返回格式；年%YY；月%MM；日%DD，时%hh，分%mm，秒%ss，毫秒%ff
 * @author jiw
 * @deprecated 返回指定格式日期，默认返回yyyy-mm-dd；例：fromatDate(new Date("2019-01-01"), "%YY-%MM-%DD")，执行后返回 2019-01-01
 */
export const formatDate = function (time, format) {
  if (time == '' || time == null) return ''
  let dt = new Date(time)
  let y = dt.getFullYear()
  let m = dt.getMonth() + 1 < 10 ? '0' + (dt.getMonth() + 1) : dt.getMonth() + 1
  let d = dt.getDate() < 10 ? '0' + dt.getDate() : dt.getDate()
  let hh = dt.getHours() < 10 ? '0' + dt.getHours() : dt.getHours()
  let mm = dt.getMinutes() < 10 ? '0' + dt.getMinutes() : dt.getMinutes()
  let ss = dt.getSeconds() < 10 ? '0' + dt.getSeconds() : dt.getSeconds()
  let ff = dt.getMilliseconds()

  if (format == null || format == '' || format == undefined) {
    return y + '-' + m + '-' + d
  }

  let arr = format.split('%')
  if (arr.length > 0) {
    let res = ''
    for (let i = 0; i < arr.length; i++) {
      let t = arr[i]
      if (t.substring(0, 2) == 'YY') {
        res += y
      } else if (t.substring(0, 2) == 'MM') {
        res += m
      } else if (t.substring(0, 2) == 'DD') {
        res += d
      } else if (t.substring(0, 2) == 'hh') {
        res += hh
      } else if (t.substring(0, 2) == 'mm') {
        res += mm
      } else if (t.substring(0, 2) == 'ss') {
        res += ss
      } else if (t.substring(0, 2) == 'ff') {
        res += ff
      }
      if (i < arr.length - 1) res += t.substring(2)
    }
    return res
  }
}

/**
 * 获取指定日期：
 * @param {number} days 指定日期的前后N天
 * @param {string} date 指定日期
 * @param {string} format 指定格式
 * @returns {string} 返回时间
 */
export const getSpecDate = function (days, date, format) {
  days = days || 0
  let currDate = date ? new Date(date) : new Date()
  let specTime = currDate.setDate(currDate.getDate() + days)
  const formatDate = (date, format) => {
    const padStart = (value, length, char) => {
      value = value + ''
      return value.padStart(length, char)
    }
    if (!date) return '--'
    let _date = date
    format = format || 'YYYY-MM-DD'
    let splitArr = format.split(/(YYYY|MM|DD|hh|mm|ss)+/)

    if (typeof date !== 'object') {
      _date = new Date(date)
    }

    return splitArr
      .map((item) => {
        if (item === 'YYYY') {
          return _date.getFullYear()
        }

        if (item === 'MM') {
          return padStart(_date.getMonth() + 1, 2, 0)
        }

        if (item === 'DD') {
          return padStart(_date.getDate(), 2, 0)
        }

        if (item === 'hh') {
          return padStart(_date.getHours(), 2, 0)
        }
        if (item === 'mm') {
          return padStart(_date.getMinutes(), 2, 0)
        }
        if (item === 'ss') {
          return padStart(_date.getSeconds(), 2, 0)
        }
        return item
      })
      .join('')
  }
  return formatDate(specTime, format)
}

export const createID = function (length) {
  return Number(
    Math.random()
      .toString()
      .substr(3, length) + Date.now()
  ).toString(36);
};

/**
 * 解析、计算系统参数中的精度与取整
 * @param {number} number 需要解析的数字
 * @param {string} type 哪个字段需要解析
 * @returns {number} 返回解析后的数字
 *
 * weight 重量
 * volume 体积
 * packWeight 包裹重量
 * packVolume 包裹体积
 * cost 费用
 */
export const getComputedParameter = function (number, type) {
  const { sysParameter_BMS, options } = store.state.sysParameter
  let property = sysParameter_BMS[type + 'Integer']
  let propertyLabel
  if (!sysParameter_BMS[type + 'Precision'] || !property) {
    return number || 0
  }

  // 精度
  let precisionLabel = Number(getLabelFromValue(sysParameter_BMS[type + 'Precision'], options.WEIGHT_PRECISION))
  // property 取整方式 字典:WEIGHT_INTEGER
  // 1-四舍五入 bigjs中使用 roundHalfEven 参数2
  // 2-向上取整 bigjs中使用 roundUp 参数3
  // 3-向下取整 bigjs中使用 roundDown 参数0
  switch (property) {
    case 1:
      propertyLabel = 2
      break;
    case 2:
      propertyLabel = 3
      break;
    case 3:
      propertyLabel = 0
      break;
  }
  let result = parseFloat(BigJs(number).round(precisionLabel, propertyLabel))
  return result
}