// 导出相关
import ExportJsonExcel from 'js-export-excel'
import { B1_APIgetlist } from '@/store/action/B1ledger'
import { MessageFu } from './message'
import dayjs from 'dayjs'
import { dictSelect, goodsSelect, statusSelect, storageSelect } from './select'
import { B2_APIgetlist } from '@/store/action/B2register'
import { B3_APIgetlist } from '@/store/action/B3edit'
import { B4_APIgetlist } from '@/store/action/B4delete'
import { C1_APIgetlist } from '@/store/action/C1storageSet'
import { C2_APIgetlist } from '@/store/action/C2storageIn'
import { C3_APIgetlist } from '@/store/action/C3storageMove'
import { C4_APIgetlist } from '@/store/action/C4storageOut'

// 入口
const devDownFu = (
  sheetData: any[],
  nameTemp: string,
  sheetFilter: string[],
  sheetHeader: string[]
) => {
  const name = nameTemp + dayjs(new Date()).format('YYYY-MM-DD HH:mm')

  const option = {
    fileName: name,
    datas: [
      {
        sheetData,
        sheetName: name,
        sheetFilter,
        sheetHeader,
        columnWidths: sheetFilter.map(v => 10)
      }
    ]
  }

  const toExcel = new ExportJsonExcel(option) //new
  toExcel.saveExcel() //保存
}

// 日期处理
export const timeChange = (val?: string) => {
  return val && val !== '（空）' ? dayjs(val).format('YYYY-MM-DD') : '（空）'
}

// 下拉框处理
export const selectChange = (data: any[], val?: number) => {
  let txt = '（空）'
  if (val || val === 0) {
    const obj = data.find(v => v.value === val)
    if (obj) txt = obj.label
  }
  return txt
}

// 数量/重量处理
export const pcsPingFu = (data: any[], val1?: number, val2?: number | string) => {
  let txt = '（空）'
  if (val1) {
    txt = val1 + ''
    if (val2) {
      if (typeof val2 === 'number') {
        const txt2 = selectChange(data, val2)
        if (txt2 !== '（空）') txt += txt2
      } else txt += val2
    }
  }
  return txt
}

// 尺寸处理
export const sizeChange = (val1?: number, val2?: number, val3?: number, val4?: string) => {
  let danWei = val4 || ''
  let txt1 = val1 ? `通长${val1}` : ''
  let txt2 = val2 ? `通宽${val2}` : ''
  let txt3 = val3 ? `通高${val3}` : ''
  txt1 = txt1 ? txt1 + danWei : ''
  txt2 = txt2 ? txt2 + danWei : ''
  txt3 = txt3 ? txt3 + danWei : ''

  let arr = [txt1, txt2, txt3]
  arr = arr.filter(v => v)

  if (!txt1 && !txt2 && !txt3) return '（空）'
  else return arr.join(' - ')
}

// 库房位置处理
export const siteLocChange = (val: string) => {
  if (val) {
    let arr = val.split('-')
    arr = arr.map(v => (v ? v : '（空）'))
    const txt = arr.join('-')
    if (txt === '（空）-（空）-（空）') return '（空）'
    else return arr.join('-')
  } else return '（空）'
}

const dataChange = (key: string, val: any, val2?: any) => {
  if (
    ['inHouseTime', 'registerTime', 'createTime', 'siteDateIn', 'siteDateOut', 'date'].includes(key)
  )
    return timeChange(val)
  else if (['typeDictId'].includes(key)) return selectChange(dictSelect('藏品类型'), val)
  else if (['textureDictId'].includes(key)) return selectChange(dictSelect('藏品材质'), val)
  else if (['pcs'].includes(key)) return pcsPingFu(dictSelect('数量单位'), val, val2)
  else if (['status'].includes(key)) return selectChange(statusSelect, val)
  else if (['siteStatus'].includes(key)) return selectChange(storageSelect, val)
  else if (['siteLoc'].includes(key)) return siteLocChange(val)
  else return val
}

// ------------------藏品总账
export const B1devFu = async (formData: any) => {
  const res = await B1_APIgetlist({ ...formData, pageNum: 1, pageSize: 99999 }, true)
  if (res.code === 0) {
    let data: any[] = res.data.records || []

    if (data.length <= 0) return MessageFu.warning('当前搜索条件没有数据')

    const arr1 = [
      'num',
      'name',
      'inHouseTime',
      'registerTime',
      'siteDateIn',
      'siteDateOut',
      'typeDictId',
      'textureDictId',
      'siteLoc',
      'pcs',
      'isNote',
      'status'
    ]

    const arr2 = [
      '藏品编号',
      '藏品标题',
      '入馆时间',
      '登记时间',
      '入库时间',
      '出库时间',
      '类型',
      '材质',
      '当前位置',
      '数量',
      '有无说明牌',
      '状态'
    ]

    data.forEach(v => {
      let val2: any = undefined

      arr1.forEach(c => {
        if (v[c]) {
          if (c === 'pcs') val2 = v.pcsUnitDictId
          else val2 = undefined

          if (c === 'status') v[c] = selectChange(goodsSelect, v[c])
          else v[c] = dataChange(c, v[c], val2)
        } else v[c] = '（空）'
      })
    })

    devDownFu(data, '藏品总账', arr1, arr2)
  }
}

// ------------------藏品登记' | '藏品修改' | '藏品删除
export const B2devFu = async (formData: any, txtKey: '藏品登记' | '藏品修改' | '藏品删除') => {
  const obj = { ...formData, pageNum: 1, pageSize: 99999 }

  const res =
    txtKey === '藏品登记'
      ? await B2_APIgetlist(obj, true)
      : txtKey === '藏品修改'
      ? await B3_APIgetlist(obj, true)
      : await B4_APIgetlist(obj, true)

  if (res.code === 0) {
    let data: any[] = res.data.records || []

    if (data.length <= 0) return MessageFu.warning('当前搜索条件没有数据')

    const arr1 = ['num', 'snapNum', 'snapName', 'creatorName', 'createTime', 'status']

    const arr2 = ['申请编号', '藏品编号', '藏品名称', '发起人', '发起日期', '申请状态']

    data.forEach(v => {
      arr1.forEach(c => {
        if (v[c]) {
          v[c] = dataChange(c, v[c])
        } else v[c] = '（空）'
      })
    })

    devDownFu(data, txtKey, arr1, arr2)
  }
}

// ------------------库房管理
export const B3devFu = async (formData: any) => {
  const res = await C1_APIgetlist({ ...formData, pageNum: 1, pageSize: 99999 }, true)
  if (res.code === 0) {
    let data: any[] = res.data.records || []

    if (data.length <= 0) return MessageFu.warning('当前搜索条件没有数据')

    const arr1 = [
      'siteLoc',
      'num',
      'name',
      'siteStatus',
      'siteDateIn',
      'siteDateOut',
      'typeDictId',
      'textureDictId',
      'pcs'
    ]

    const arr2 = [
      '库房位置',
      '藏品编号',
      '藏品名称',
      '库存状态',
      '入库时间',
      '出库时间',
      '类型',
      '材质',
      '数量'
    ]

    data.forEach(v => {
      let val2: any = undefined

      arr1.forEach(c => {
        if (v[c] || v[c] === 0) {
          if (c === 'pcs') val2 = v.pcsUnitDictId
          else val2 = undefined
          v[c] = dataChange(c, v[c], val2)
        } else v[c] = '（空）'
      })
    })

    devDownFu(data, '库房管理', arr1, arr2)
  }
}

// ------------------入库 移库 出库
export const C2devFu = async (formData: any, txt: '入库' | '移库' | '出库') => {
  const obj = { ...formData, pageNum: 1, pageSize: 99999 }

  const res =
    txt === '入库'
      ? await C2_APIgetlist(obj, true)
      : txt === '移库'
      ? await C3_APIgetlist(obj, true)
      : await C4_APIgetlist(obj, true)

  if (res.code === 0) {
    let data: any[] = res.data.records || []

    if (data.length <= 0) return MessageFu.warning('当前搜索条件没有数据')

    const arr1 = ['date', 'num', 'creatorName', 'createTime', 'status']

    const arr2 = [`${txt}日期`, `${txt}单编号`, '发起人', '发起日期', '申请状态']

    data.forEach(v => {
      let val2: any = undefined

      arr1.forEach(c => {
        if (v[c] || v[c] === 0) {
          if (c === 'pcs') val2 = v.pcsUnitDictId
          else val2 = undefined
          v[c] = dataChange(c, v[c], val2)
        } else v[c] = '（空）'
      })
    })

    devDownFu(data, `藏品${txt}`, arr1, arr2)
  }
}
