<template>
  <div class="waybill">
    <div class="waybill-info">
      <div class="waybill-info-title">运单基本信息</div>
      <div class="waybill-info-content flex">
        <span
          v-for="item in waybillInfoItems"
          :key="item.key"
          class="waybill-info-item"
        >
          <span>{{ item.label }}：</span>
          <el-tooltip
            v-if="item.key === 'typeCode'"
            effect="light"
            :content="computedWaybillInfo(item)"
          >
            <span class="waybill-info-item-value">{{
              computedWaybillInfo(item)
            }}</span>
          </el-tooltip>
          <span v-else>{{ computedWaybillInfo(item) }}</span>
        </span>
      </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 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="filteredColumns"
        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 } from '~/common'

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

const route = useRoute()
const { waybillNO } = route.query

const {
  waybillInfoItems,
  waybillInfo,
  computedWaybillInfo,
} = useWaybillInfo(props.name, [waybillNO as string])

const { tableColumns, tableData: trackData } = useTable(`${props.name}Goods`, [
  waybillNO as string,
])

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

const tableData = computed(() =>
  trackData.value.reduce((data, current) => {
    const sameRow = data.find(row =>
      ['stockCode', 'flightNO', 'flightDate', 'ULDNO', '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
    } else {
      data.push({
        ...current,
        [String(nodeCode)]: nodeValue,
      })
    }
    return data
  }, [] as CommonData[])
)

const formatter = (row, column, cellValue, index) => {
  const value = String(cellValue ?? '').split('\n')
  if (value[2]) {
    value[2] = value[2].split('T')[1]
  }
  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 { filteredColumns, 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;
      &-value {
        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: 30px;
        }
      }
    }
  }
  .goods-list :deep {
    margin-top: 16px;
    height: 0;
    flex: 1;
    .el-table__body .el-table__cell .cell {
      padding: 4px 8px;
    }
  }
}
</style>
