import { CommonData, CommonValue } from '~/common'
import { Query } from '@/api/webApi'
import { ElMessage } from 'element-plus'

const waybillInfoItemsMap = {
  internal: [
    {
      label: '运单',
      key: 'stockCode',
    },
    {
      label: '货代公司',
      key: 'cargoCompany',
    },
    {
      label: '品名',
      key: 'typeCode',
      showOverflowTooltip: true,
    },
    {
      label: '特货信息',
      key: 'speCargoInfo',
    },
    {
      label: '始发机场',
      key: 'departureAirport',
    },
    {
      label: '目的机场',
      key: 'arriveAirport',
    },
    {
      label: '货物数量',
      key: 'luggageCount',
    },
    {
      label: '货物总重',
      key: 'weight',
    },
  ],
  international: [
    {
      label: '运单',
      key: 'stockCode',
    },
    // {
    //   label: '运单类型',
    //   key: 'type',
    // },
    {
      label: '机场代理',
      key: 'proxy',
      getter: info => (info.proxy === 1 ? '是' : '否'),
    },
    {
      label: '货代公司',
      key: 'cargoCompany',
    },
    {
      label: '品名',
      key: 'typeCode',
      showOverflowTooltip: true,
    },
    {
      label: '特货信息',
      key: 'speCargoInfo',
    },
    {
      label: '始发机场',
      key: 'departureAirport',
    },
    {
      label: '目的机场',
      key: 'arriveAirport',
    },
  ],
}

export function useWaybillInfo(name: string, dataContent: CommonValue[]) {
  const waybillInfoItems = ref<
    {
      label: string
      key?: string
      getter?: (info: any) => string
      showOverflowTooltip?: boolean
    }[]
  >([])
  const getWaybillInfoItems = () => {
    waybillInfoItems.value =
      waybillInfoItemsMap[
        name.includes('International') ? 'international' : 'internal'
      ]
  }
  getWaybillInfoItems()

  const waybillInfo: CommonData = reactive({})
  const getWaybillInfo = async () => {
    try {
      const {
        code,
        returnData: { listValues },
        message,
      } = await Query<CommonData>({
        id:
          DATACONTENT_ID[
            `${name.slice(0, 1).toLowerCase()}${name.slice(1)}Info`
          ],
        dataContent,
      })
      if (Number(code) !== 0) {
        throw new Error(message || '失败')
      }
      if (!listValues.length) {
        ElMessage.info('未查询到运单信息')
        return
      }
      Object.assign(waybillInfo, listValues[0])
    } catch (error) {
      console.error(error)
    }
  }

  const computedWaybillInfo = computed(() => item => {
    if (item.getter) {
      return item.getter(waybillInfo)
    } else if (item.key) {
      return String(waybillInfo[item.key] ?? '')
    } else {
      return ''
    }
  })

  return {
    waybillInfoItems,
    waybillInfo,
    computedWaybillInfo,
    getWaybillInfo,
  }
}
