<template>
  <Dialog
    :flag="flag"
    width="1440px"
    :msg-title="msgTitle"
    :with-footer="false"
    @reset-form="dialogHide"
  >
    <div class="dialog-content">
      <SimpleTable
        :data="tableData"
        :columns="tableColumns"
        height="300px"
        :column-props="{ formatter }"
      />
    </div>
  </Dialog>
</template>

<script setup lang="ts">
import Dialog from '@/components/dialog/index.vue'
import SimpleTable from '@/components/SimpleTable/index.vue'
import { Query } from '@/api/webApi'
import { PropType } from 'vue'
import {
  CommonData,
  CommonTableColumn,
  CommonTableFormatter,
  CommonValue,
} from '~/common'
import { ellipsisCell } from '@/components/SimpleTable/customRender'
import { datetimeToTime } from '@/utils/validate'

const props = defineProps({
  flag: {
    type: Boolean,
    required: true,
  },
  name: {
    type: String,
    required: true,
  },
  dataContent: {
    type: Array as PropType<CommonValue[]>,
    required: true,
  },
})

const emit = defineEmits(['update:flag'])

const dialogHide = () => {
  emit('update:flag', false)
}

const tableColumnsMap = {
  departure: [
    { columnLabel: '运单号', columnName: 'stockCode', width: 120 },
    // { columnLabel: '集装器数量', columnName: 'stowageNum', needCount: 1 },
    {
      columnLabel: '品名',
      columnName: 'typeCode',
      width: 300,
      showOverflowTooltip: true,
    },
    {
      columnLabel: '特货信息',
      columnName: 'speCargoInfo',
      customRender: ellipsisCell,
    },
    { columnLabel: '货物件数', columnName: 'luggageCount', needCount: 1 },
    { columnLabel: '拉下件数', columnName: 'pullNum', needCount: 1 },
    { columnLabel: '退运件数', columnName: 'returnNum', needCount: 1 },
    { columnLabel: '最新节点', columnName: 'nodeCode' },
    { columnLabel: '最新位置', columnName: 'execPosition' },
    { columnLabel: '处理结果', columnName: 'execResult' },
    { columnLabel: '处理时间', columnName: 'execTime', width: 130 },
  ],
  arrival: [
    { columnLabel: '运单号', columnName: 'stockCode', width: 120 },
    {
      columnLabel: '品名',
      columnName: 'typeCode',
      width: 300,
      showOverflowTooltip: true,
    },
    {
      columnLabel: '特货信息',
      columnName: 'speCargoInfo',
      needCount: 1,
      customRender: ellipsisCell,
    },
    {
      columnLabel: '运单件数',
      columnName: 'messageCargos_in',
      needCount: 1,
    },
    {
      columnLabel: '理货件数',
      columnName: 'acCargos_in',
      needCount: 1,
    },
    { columnLabel: '最新节点', columnName: 'nodeCode' },
    { columnLabel: '最新位置', columnName: 'execPosition' },
    { columnLabel: '处理结果', columnName: 'execResult' },
    { columnLabel: '处理时间', columnName: 'execTime', width: 130 },
  ],
}

const msgTitle = computed(() => props.dataContent.join('-'))

const tableColumns = ref<CommonTableColumn[]>([])
const getTableColumns = () => {
  tableColumns.value = tableColumnsMap[
    props.name.includes('Departure') ? 'departure' : 'arrival'
  ].map(column => ({
    columnDescribe: '',
    dataType: '',
    listqueryTemplateID: null,
    needCount: null,
    needFilters: null,
    needGroup: null,
    needSearch: null,
    needShow: 1,
    needSort: null,
    orderNumber: null,
    queryTemplateColumnSetID: null,
    queryTemplateID: null,
    ...column,
  }))
}
const tableData = ref<CommonData[]>([])
const getTableData = async () => {
  try {
    const {
      code,
      returnData: { listValues },
      message,
    } = await Query<CommonData>({
      id:
        DATACONTENT_ID[
          `${props.name.slice(0, 1).toLowerCase()}${props.name.slice(
            1
          )}ContainerWaybill`
        ],
      dataContent: props.dataContent,
    })
    if (Number(code) !== 0) {
      throw new Error(message || '失败')
    }
    tableData.value = listValues.filter(
      row =>
        !Object.values(row).some(
          cellValue =>
            typeof cellValue === 'string' && cellValue.includes('undefined')
        )
    )
  } catch (error) {
    console.error(error)
  }
}
const resetTable = () => {
  tableColumns.value = []
  tableData.value = []
}

watch(
  () => props.flag,
  val => {
    resetTable()
    if (val) {
      getTableColumns()
      getTableData()
    }
  }
)

const flightDate = computed(() => props.dataContent[0])

const formatter: CommonTableFormatter = (row, column, cellValue, index) => {
  const value = String(cellValue ?? '').trim()
  if (column.property.includes('Time')) {
    return datetimeToTime(value, flightDate.value)
  }
  if (column.property === 'nodeCode') {
    if (props.name.includes('InternationalDeparture') && value === 'LS_CARGO') {
      return '实配'
    }
    return NODE_CODE[value] ?? value
  }
  return value
}
</script>

<style scoped lang="scss">
.dialog-content {
  padding: 0 22px;
  height: 322px;
}
</style>
