import CacheManager from './CacheManager'

/**
 * 扫码获取结果
 * @param {boolean} options.isBikeCode - 是否为单车码
 * @param {Function} options.success - 成功回调函数
 * @param {Function} options.fail - 失败回调函数
 */
export function scanCode({ isSN = false, success, fail }) {
  uni.scanCode({
    success: (res) => {
      const codeStr = res.result
      console.log('扫码结果:', codeStr)

      // 解析车牌编号
      if (isSN) {
        const codeObj = {
          IMEI: '',
          SN: '',
        }
        if (codeStr) {
          const codeArr = codeStr.split(' ')
          codeObj.IMEI = codeArr[0].replace('IMEI:', '')
          codeObj.SN = codeArr[1].replace('SN:', '')
          return success && success(codeObj)
        }
      }

      return success && success({ code: codeStr })
    },
    fail: (err) => {
      fail && fail(err)
    },
  })
}

/**
 * 翻译数组类型数据
 * @param list
 * @param code
 */
export function translateErrorCode(list: any[], code: string) {
  const dicList = CacheManager.get('dictData')
  let str = ''
  if (Array.isArray(dicList) && dicList.length > 0) {
    const codeList = dicList.find(item => item.dicCode === code)
    console.log(codeList)

    if (Array.isArray(list) && list.length > 0) {
      list.forEach((item) => {
        const codeItem = codeList.values.find(codeItem => codeItem.dicValue === item.orderPart.toString())?.dicValueName
        if (codeItem) {
          console.log(codeItem)
          str += `${codeItem} | `
        }
      })
      return str.substring(0, str.length - 2)
    }
  }

  return str
}
