<template>
  <div class="waybill">
    <div class="waybill-info">
      <div class="waybill-info-title">运单基本信息</div>
      <div class="waybill-info-content flex">
        <div
          v-for="(item, index) in waybillInfoItems"
          :key="index"
          class="waybill-info-item"
        >
          <div>{{ item.label }}：</div>
          <el-tooltip
            :disabled="!computedWaybillInfo(item) || !item.showOverflowTooltip"
            :content="computedWaybillInfo(item)"
            effect="light"
          >
            <div>{{ computedWaybillInfo(item) }}</div>
          </el-tooltip>
        </div>
      </div>
    </div>
    <div class="waybill-header flex">
      <div class="waybill-header-title flex-wrap">
        <div class="manageTitle">运单跟踪信息</div>
        <div class="status">正常</div>
      </div>
      <div class="waybill-header-operate flex-wrap">
        <Search @clear="clear" @search="search" />
        <el-button
          class="button-sqaure"
          :icon="Download"
          color="#ac014d"
          @click="downloadHandler"
        />
        <ColumnSet
          class="button-sqaure"
          :table-columns="tableColumns"
          @checked-submit="columnChecked"
        />
      </div>
    </div>
    <div
      v-show="trackAirlines.length"
      :style="{
        maxHeight: trackAirlines.length > 1 ? `${208 * 2 + 8}px` : '208px',
      }"
      class="waybill-track"
    >
      <el-scrollbar always>
        <div class="waybill-track-warpper">
          <div
            v-for="trackAirline in trackAirlines"
            :key="trackAirline.flightNO"
            class="waybill-track-row"
          >
            <div
              v-for="(trackAirport, index) in trackAirline.airports"
              :key="trackAirport.airport"
              class="waybill-track-box"
              :style="trackBoxStyle(trackAirline.airports, index)"
            >
              <div class="title flex-wrap">
                <span v-if="index === 0" class="title-span"
                  >航班号：{{ trackAirline.flightNO }}</span
                >
                <!-- <span
                  v-if="!name.includes('InternationalDeparture')"
                  class="title-span"
                  >{{ trackAirport.isDeparture ? '出港' : '进港' }}：{{
                    trackAirport.airport
                  }}</span
                > -->
                <span class="title-span"
                  >日期：{{ trackAirline.flightDate }}</span
                >
              </div>
              <Steps :steps="trackAirport.trackSteps" />
            </div>
          </div>
        </div>
      </el-scrollbar>
    </div>
    <div class="goods-list">
      <SimpleTable
        ref="tableRef"
        :data="tableData"
        :columns="tableColumns"
        scrollbar-always-on
        :row-class-name="rowClass"
        :cell-class-name="cellClass"
        @cell-click="cellClickHandler"
        :column-props="{ formatter, minWidth: 75 }"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { Download } from '@element-plus/icons-vue'
import Search from '@/components/search/index.vue'
import Steps from '@/components/steps/index.vue'
import ColumnSet from '@/components/ColumnSet/index.vue'
import SimpleTable from '@/components/SimpleTable/index.vue'
import { useTrackData } from '../../hooks/useTrackData'
import { useTable } from '../../hooks/useTable'
import { useTableColumnSet } from '@/hooks/useTableColumnSet'
import { useTableExport } from '../../hooks/useTableExport'
import { useTableStyle } from '../../hooks/useTableStyle'
import { useTableCellClick } from '../../hooks/useTableCellClick'
import { useWaybillInfo } from './useWaybillInfo'
import { CommonData, CommonTableFormatter, CommonValue } from '~/common'
import { useLoop } from '@/hooks/useLoop'
import { datetimeToTime } from '@/utils/validate'

const props = defineProps({
  name: {
    type: String,
    required: true,
  },
})

const route = useRoute()
const { flightDate, waybillNO } = route.query
const dataContent = [flightDate, waybillNO] as string[]

const {
  waybillInfoItems,
  waybillInfo,
  computedWaybillInfo,
  getWaybillInfo,
} = useWaybillInfo(props.name, dataContent)

const { tableColumns, tableData: trackData, getTableData } = useTable(
  `${props.name}Goods`,
  dataContent
)

// 判断是否有另外一个机场的节点信息，没有则隐藏那些列
watch(trackData, data => {
  let anotherAirportNodeFlag = ''
  if (props.name.includes('Departure')) {
    anotherAirportNodeFlag = 'node-arrival'
  } else {
    anotherAirportNodeFlag = 'node-departure'
  }
  const activeNodes = data.reduce((nodes: string[], row) => {
    if (typeof row.nodeCode === 'string' && !nodes.includes(row.nodeCode)) {
      nodes.push(row.nodeCode)
    }
    return nodes
  }, [])
  tableColumns.value.forEach(column => {
    if (
      column.defaultDisabled ||
      (typeof column.className === 'string' &&
        column.className.includes(anotherAirportNodeFlag))
    ) {
      column.checkDisabled = true
      if (activeNodes.includes(column.columnName)) {
        column.hidden = false
      } else {
        column.hidden = true
      }
    }
  })
})

useLoop([getWaybillInfo, getTableData], 'waybill')

const { trackAirlines, trackBoxStyle } = useTrackData(props.name, trackData)

const tableData = computed(() => {
  const mergedTableData = trackData.value.reduce(
    (data: CommonData[], current) => {
      const sameRow = data.find(row =>
        ['flightNO', 'flightDate', 'cargoSN'].every(
          key => row[key] === current[key]
        )
      )
      const {
        stockCode,
        flightNO,
        flightDate,
        departureAirport, // 装载机场
        arriveAirport, // 卸载机场
        ULDNO,
        cargoSN,
        pullMark,
        returnMark,
        // transMark,
        exceptionCustomsMark,
        execPosition, // 读取位置
        nodeCode, // 节点名称
        ConsignmentItemPackagingQuantityQuantity, // 跟踪节点件数
        execResult,
        execTime,
      } = current
      const nodeValue = `${execPosition ?? ''}\n${
        execResult ? '通过' : '未通过'
      }\n${execTime ?? ''}`
      if (sameRow) {
        sameRow[String(nodeCode)] = nodeValue
        ;[
          'ULDNO',
          // 'cargoSN'
        ].forEach(key => {
          const oldValue = sameRow[key]
          const currentValue = current[key]
          if (typeof currentValue === 'string' && currentValue !== oldValue) {
            if (typeof oldValue === 'string') {
              sameRow[key] = [
                ...new Set([
                  ...oldValue.split(','),
                  ...currentValue.split(','),
                ]),
              ].join(',')
            } else {
              sameRow[key] = currentValue
            }
          }
        })
        ;['pullMark', 'returnMark'].forEach(key => {
          sameRow[key] = sameRow[key] ?? current[key]
        })
      } else {
        data.push({
          ...current,
          [String(nodeCode)]: nodeValue,
        })
      }
      return data
    },
    []
  )
  return mergedTableData.reduce((data: CommonData[], current) => {
    const { cargoSN } = current
    if (typeof cargoSN === 'string') {
      const splitedRows = cargoSN.split(',').map(splitedCargoSN => ({
        ...current,
        cargoSN: splitedCargoSN,
      }))
      data.push(...splitedRows)
    } else {
      data.push(current)
    }
    return data
  }, [])
})

const formatter: CommonTableFormatter = (row, column, cellValue, index) => {
  const value = String(cellValue ?? '').split('\n')
  if (value[2]) {
    value[2] = datetimeToTime(value[2], flightDate as CommonValue)
  }
  return value.join('\n')
}

const search = (text: string) => {
  console.log(text)
}
const clear = () => {}

const tableRef = ref<InstanceType<typeof SimpleTable> | null>(null)
const { exportToExcel } = useTableExport()
const downloadHandler = () => {
  const table = tableRef.value!.table!
  exportToExcel({ table })
}

const { columnChecked } = useTableColumnSet(tableColumns)

const { rowClass, cellClass } = useTableStyle(`${props.name}Goods`)

const { cellClickHandler } = useTableCellClick(`${props.name}Goods`)
</script>

<style lang="scss" scoped>
.waybill {
  height: 100%;
  display: flex;
  flex-direction: column;
  &-info {
    height: 144px;
    background: #410425;
    padding: 24px 30px;
    color: #ffffff;
    &-title {
      font-size: 18px;
      font-family: Microsoft YaHei;
      font-weight: bold;
      margin-bottom: 40px;
    }
    &-item {
      display: flex;
      .el-tooltip__trigger {
        max-width: 300px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }
  }
  &-header :deep {
    margin: 24px 0;
    line-height: 32px;
    .status {
      font-size: 16px;
      font-family: Microsoft YaHei;
      font-weight: bold;
      color: #519f6b;
    }
    .el-button {
      background-color: #d5327b;
      border: none;
    }
    .button-sqaure {
      width: 30px;
      height: 30px;
      border-radius: 4px;
      font-size: 16px;
      margin-left: 24px;
      &:first-of-type {
        margin-left: 35px;
      }
    }
  }
  &-track {
    height: 0;
    flex: 1.5;
    &-row {
      height: 208px;
      display: flex;
      &:not(:last-child) {
        margin-bottom: 8px;
      }
    }
    &-box {
      background: #ffffff;
      padding: 24px 24px 12px 24px;
      &:not(:last-child) {
        margin-right: 8px;
      }
      .title {
        font-size: 16px;
        font-family: Microsoft YaHei;
        font-weight: bold;
        color: #101116;
        margin-bottom: 10px;
        &-span:not(:last-of-type) {
          margin-right: 8px;
        }
      }
    }
  }
  .goods-list :deep {
    margin-top: 16px;
    height: 0;
    flex: 1;
    .el-table__body .el-table__cell .cell {
      padding: 4px 8px;
    }
  }
}
</style>
