<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 class="waybill-info-item-label">{{ item.label }}：</div>
          <div class="waybill-info-item-content">
            <OverflowTooltip
              :content="computedWaybillInfo(item)"
              effect="light"
            />
          </div>
        </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" color="#ac014d" @click="exportHandler">
          <i class="icon-export" />
        </el-button>
        <ColumnSet
          class="button-sqaure"
          :table-columns="isDeparture ? pullTableColumns : tableColumns"
          @checked-submit="columnChecked"
        />
      </div>
    </div>
    <div
      v-show="trackAirlines.length"
      :style="{
        maxHeight: `${
          trackAirlines.length > 1 ? 208 * 2 + 8 : trackRowHeight
        }px`,
      }"
      class="waybill-track"
    >
      <el-scrollbar always>
        <div class="waybill-track-warpper">
          <div
            v-for="trackAirline in trackAirlines"
            :key="trackAirline.flightNO"
            class="waybill-track-row"
            :style="{ height: `${trackRowHeight}px` }"
          >
            <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"
                :hasMultiple="hasMultiple"
              />
            </div>
          </div>
        </div>
      </el-scrollbar>
    </div>
    <div class="goods-list">
      <SimpleTable
        v-if="isDeparture"
        ref="tableRef"
        :data="pullTableData"
        :columns="pullTableColumns"
        sequence
        scrollbar-always-on
        :column-props="{ formatter }"
      />
      <SimpleTable
        v-else
        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 OverflowTooltip from '@/components/OverflowTooltip/index.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 hasMultiple = computed(() =>
  trackAirlines.value.some(airline =>
    airline.airports.some(airport =>
      airport.trackSteps.some(step => 'children' in step)
    )
  )
)
const trackRowHeight = computed(() => (unref(hasMultiple) ? 280 : 208))

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

const isDeparture = props.name.includes('Departure')

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
)

const {
  tableColumns: pullTableColumns,
  tableData: pullTableData,
  getTableData: getPullTableData,
} = useTable(`${props.name}Pull`, dataContent)

// 判断是否有另外一个机场的节点信息，没有则隐藏那些列
watch(trackData, data => {
  let anotherAirportNodeFlag = ''
  if (isDeparture) {
    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
      }
    }
  })
})

const loopFuncs = [getWaybillInfo, getTableData]
if (isDeparture) {
  loopFuncs.push(getPullTableData)
}
useLoop(loopFuncs, 'waybill')

// onMounted(getTableData)

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 {
        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' && cargoSN !== '') {
      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) => {
  if (column.property === 'wholePull') {
    return cellValue === 1 ? '是' : '否'
  }
  if (column.property === 'pullTime') {
    return datetimeToTime(cellValue, flightDate as CommonValue)
  }
  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) => {}
const clear = () => {}

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

const { columnChecked } = useTableColumnSet(
  isDeparture ? pullTableColumns : 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 {
      width: 150px;
      display: flex;
      &-content {
        width: 0;
        flex: 1;
      }
    }
  }
  &-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: 19px;
      }
    }
  }
  &-track {
    height: 0;
    flex: 1.5;
    &-row {
      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>
