<script setup lang="ts">
import DownloadDialog from './components/DownloadDialog.vue'
import { autoWidth } from '@/utils/table'
import { useRowClickStyle } from '@/hooks/rowClickStyle'
import dayjs from 'dayjs'
import { useRouter } from 'vue-router'
import { ref, onMounted } from 'vue'
import { transportationMode } from '@/components/TransportationMode'
import { useLoadingState } from '@/stores/modules/loadingState'

const router = useRouter()
const props = defineProps({
  height: {
    type: Number,
    default: 440
  },
  tagsData: {
    type: Array,
    default: () => []
  }
})
const tableLoadingTable = ref()
const getLoadingData = (data: any) => {
  tableLoadingTable.value = data
}
// 表格展示列的原始字段
const tableOriginColumnsField = ref()
const handleColumns = (columns: any, status?: string) => {
  const newColumns = columns?.map((item: any) => {
    let curColumn: any = {
      title: item.title,
      field: item.field,
      sortable: true
    }
    // 设置插槽
    if (item.type === 'status' && status !== 'all') {
      curColumn = {
        ...curColumn,
        slots: { default: 'status' }
      }
    } else if (item.type === 'link' && status !== 'all') {
      curColumn = {
        ...curColumn,
        slots: { default: 'trackingNo' }
      }
    } else if (item.type === 'mode' && status !== 'all') {
      curColumn = {
        ...curColumn,
        slots: { default: 'mode' }
      }
    }
    // 格式化
    if (item.formatter === 'date') {
      curColumn = {
        ...curColumn,
        formatter: ({ cellValue }: any) =>
          cellValue ? dayjs(cellValue).format('MMM-DD-YYYY ') : '--'
      }
    } else if (item.formatter === 'dateTime') {
      curColumn = {
        ...curColumn,
        formatter: ({ cellValue }: any) =>
          cellValue ? dayjs(cellValue).format('MMM-DD-YYYY HH:mm:ss') : '--'
      }
    }
    return curColumn
  })
  return newColumns
}

// 获取表格列
const getTableColumns = async () => {
  tableLoadingColumn.value = true
  await $api.getTrackingTableColumns().then((res: any) => {
    if (res.code === 200) {
      const index = trackingTable.value.columns.findIndex((item: any) => item.title === 'Action')
      trackingTable.value.columns = [
        { type: 'checkbox', width: 50, fixed: 'left' },
        ...handleColumns(res.data.TrackingTableColumns)
      ]
      if (index !== -1) {
        trackingTable.value.columns.push({
          title: 'Action',
          fixed: 'right',
          width: 80,
          slots: { default: 'action' }
        })
      }
      tableOriginColumnsField.value = res.data.TrackingTableColumns
    }
  })
  nextTick(() => {
    tableLoadingColumn.value = false
    selectedNumber.value = 0
    selectedTableData.value = []
  })
}

const pageInfo = ref({ pageNo: 1, pageSize: 50, total: 0 })
// 从sessionStorage中获取页长以及当前页码
const assignPageInfo = () => {
  const oldPageInfo = sessionStorage.getItem('trackingTablePageInfo')
  if (oldPageInfo) {
    const data = JSON.parse(oldPageInfo)
    pageInfo.value.pageNo = data.pageNo
    pageInfo.value.pageSize = data.pageSize
  }
}
assignPageInfo()
const TagsList = ref()
const tempSearch = ref('')

const curTableData = ref([])

// 获得表格数据后赋值
const assignTableData = (data: any) => {
  trackingTable.value.data = data.searchData || []
  curTableData.value = data.searchData || []
  pageInfo.value.total = Number(data.rc)
  TagsList.value = data.tagsList
  tempSearch.value = data.tmp_search

  if (data.canEdiVgm && trackingTable.value.columns.length > 0) {
    const index = trackingTable.value.columns.findIndex((item: any) => item.title === 'Action')
    if (index === -1) {
      trackingTable.value.columns.push({
        title: 'Action',
        fixed: 'right',
        width: 80,
        slots: { default: 'action' }
      })
    }
  }
  // 拥有所有字段的表格
  setTimeout(() => {
    allTable.value.columns = handleColumns(data.allColums, 'all')
    allTable.value.data = data.searchData
    nextTick(() => {
      allTableRef.value && autoWidth(allTable.value, allTableRef.value)
    })
  }, 1000)
}

const filterdataobj = ref()
const getSharedTableData = () => {
  const trackingData = JSON.parse(localStorage.getItem('searchData'))?.trackingData
  if (trackingData) {
    pageInfo.value.pageSize = Number(trackingData.ps)
    sessionStorage.setItem('trackingTablePageInfo', JSON.stringify(pageInfo.value))
    assignTableData(trackingData)
    selectedNumber.value = 0
    selectedTableData.value = []
    nextTick(() => {
      tableRef.value && autoWidth(trackingTable.value, tableRef.value)
    })
    return true
  }
  return false
}

// 切换分页时重新获取表格数据
const getTableData = async (isPageChange?: boolean) => {
  // 保存页长以及当前页码
  sessionStorage.setItem('trackingTablePageInfo', JSON.stringify(pageInfo.value))
  tableLoadingTable.value = true
  const rc = isPageChange ? pageInfo.value.total : -1
  await $api
    .getTrackingTableData({
      cp: pageInfo.value.pageNo,
      ps: pageInfo.value.pageSize,
      rc,
      other_filed: '',
      ...filterdataobj.value
    })
    .then((res: any) => {
      if (res.code === 200) {
        assignTableData(res.data)
      }
    })
    .finally(() => {
      nextTick(() => {
        tableRef.value && autoWidth(trackingTable.value, tableRef.value)
        tableLoadingTable.value = false
      })
      selectedNumber.value = 0
      selectedTableData.value = []
    })
  // if (
  //   sessionStorage.getItem('clickParams') != null &&
  //   sessionStorage.getItem('clickParams') != '{}'
  // ) {
  //   const data = JSON.parse(sessionStorage.getItem('clickParams') as string) || {}
  //   assignTableData(data)
  //   nextTick(() => {
  //     tableRef.value && autoWidth(trackingTable.value, tableRef.value)
  //     tableLoadingTable.value = false
  //     selectedNumber.value = 0
  //     selectedTableData.value = []
  //   })
  // } else {
  //   await $api
  //     .getTrackingTableData({
  //       cp: pageInfo.value.pageNo,
  //       ps: pageInfo.value.pageSize,
  //       rc,
  //       other_filed: '',
  //       ...filterdataobj.value
  //     })
  //     .then((res: any) => {
  //       if (res.code === 200) {
  //         assignTableData(res.data)
  //       }
  //     })
  //     .finally(() => {
  //       nextTick(() => {
  //         tableRef.value && autoWidth(trackingTable.value, tableRef.value)
  //         tableLoadingTable.value = false
  //       })
  //       selectedNumber.value = 0
  //       selectedTableData.value = []
  //     })
  // }
}

// 查询列表数据
const searchTableData = (data: any) => {
  filterdataobj.value = data
  if (sessionStorage.getItem('TrackingData') != null) {
    const data = JSON.parse(sessionStorage.getItem('TrackingData') as string) || {}
    assignTableData(data)
    setTimeout(() => {
      selectedNumber.value = 0
      selectedTableData.value = []
      nextTick(() => {
        tableRef.value && autoWidth(trackingTable.value, tableRef.value)
        tableLoadingTable.value = false
        sessionStorage.removeItem('TrackingData')
      })
    }, 100)
  }
}

onMounted(() => {
  tableLoadingColumn.value = true
  Promise.all([getTableColumns()]).finally(() => {
    tableLoadingColumn.value = false
    nextTick(() => {
      tableRef.value && autoWidth(trackingTable.value, tableRef.value)
    })
  })
})

const tableRef = ref<any>()
const trackingTable = ref<any>({
  border: true,
  round: true,
  columns: [],
  data: [],
  scrollY: { enabled: true, oSize: 20, gt: 20, scrollToTopOnChange: true },
  scrollX: { enabled: true, gt: 2, scrollToLeftOnChange: true },
  stripe: true,
  emptyText: ' ',
  showHeaderOverflow: true,
  showOverflow: true,
  headerRowStyle: {
    backgroundColor: 'var(--color-table-header-bg)'
  },
  sortConfig: {
    sortMethod: (params) => {
      const { data, sortList } = params
      // 如果没有排序条件，直接返回原数据
      if (sortList.length === 0) return data
      // 对数据进行多重排序
      const sortedData = [...data].sort((a, b) => {
        for (const { field, order } of sortList) {
          const curColumn = tableOriginColumnsField.value.find((item: any) => item.field === field)
          if (!curColumn) continue

          const typeName = curColumn.type
          const aValue = a[field]
          const bValue = b[field]

          const compareResult = (aValue: any, bValue: any) => {
            // 如果 aValue 或 bValue 是 null 或 undefined，优先处理这些值
            if (aValue == null && bValue == null) {
              return 0 // 如果两个值都为 null 或 undefined，视为相等
            } else if (aValue == null) {
              return -1 // 如果 aValue 是 null，bValue 不是，则将 aValue 视为较小值
            } else if (bValue == null) {
              return 1 // 如果 bValue 是 null，aValue 不是，则将 bValue 视为较小值
            }

            if (typeName === 'datetime' || typeName === 'date' || typeName === 'time') {
              return dayjs(aValue).unix() - dayjs(bValue).unix()
            } else if (isNaN(Number(aValue)) || isNaN(Number(bValue))) {
              return aValue.localeCompare(bValue)
            } else {
              return Number(aValue) - Number(bValue)
            }
          }

          const result = compareResult(aValue, bValue)
          if (result !== 0) {
            return order === 'asc' ? result : -result
          }
        }

        return 0 // 如果所有字段都相等
      })

      return sortedData
    }
  },
  columnConfig: { resizable: true, useKey: true },
  rowConfig: { isHover: true },
  exportConfig: {
    types: ['csv', 'html', 'txt', 'xlsx'],
    modes: ['current', 'selected', 'all']
  }
})

const allTableRef = ref<any>()
const allTable = ref<any>({
  columns: [],
  data: [],
  showHeaderOverflow: true,
  showOverflow: true,
  scrollY: { enabled: true, oSize: 5, gt: 2 },
  scrollX: { enabled: true, gt: 2 },
  exportConfig: {
    types: ['csv', 'html', 'txt', 'xlsx'],
    modes: ['current', 'selected', 'all']
  }
})
// 实现行点击样式
useRowClickStyle(tableRef)
onMounted(() => {
  // 表格列自适应宽度
  tableRef.value && autoWidth(trackingTable.value, tableRef.value)
})

const downloadDialogRef = ref()
const handleDownload = () => {
  const curSelectedColumns: string[] = []
  tableRef.value?.columns?.forEach((item: any) => {
    if (item.field) {
      curSelectedColumns.push(item.title)
    }
  })
  downloadDialogRef.value.openDialog(
    props.tagsData,
    curSelectedColumns,
    selectedNumber.value || pageInfo.value.total
  )
}

const exportLoading = ref(false)
// 获取导出表格数据
const getExportTableData = (status: number) => {
  // 如果有选中表格行数据，那么只到处选中的数据
  if (selectedNumber.value > 0) {
    exportTable(status)
    return
  }
  exportLoading.value = true
  const buildColumnString = (columns: any[]): string => {
    return columns
      .filter((item) => item.field)
      .map((item) => item.title)
      .join(',')
  }

  let column = ''
  if (status === 1) {
    column = buildColumnString(trackingTable.value.columns)
  } else {
    column = buildColumnString(allTable.value.columns)
  }

  $api
    .getAllTrackingTableData({
      selected_fields: column,
      excel_filter_condition: props.tagsData.join(','),
      tmp_search: tempSearch.value
    })
    .then((res: any) => {
      if (res.code === 200) {
        allTable.value.data = res.data.Data || []
        nextTick(() => {
          exportLoading.value = false
          // 导出数据
          exportTable(status)
        })
      }
    })
    .finally(() => {
      exportLoading.value = false
    })
}
// 导出表格 status: 1 导出当前表格 2 导出所有字段表格
const exportTable = (status: number) => {
  let type = 'xlsx'
  if (allTable.value.data.length > 20000) {
    type = 'csv'
  }
  const exportConfig: any = {
    type: type,
    message: false,
    filename: `Tracking List_${dayjs().format('YYYYMMDDHH[h]mm[m]ss[s]')}`
  }
  if (status === 1) {
    exportConfig.columnFilterMethod = ({ column }: any) => {
      const index = trackingTable.value.columns.findIndex(
        (item: any) => item.field === column.field
      )
      // 排除复选框列
      return column.field && index !== -1
    }
    exportConfig.columns = trackingTable.value.columns
  }
  if (selectedNumber.value > 0) {
    exportConfig.dataFilterMethod = ({ row }: any) => {
      const index = selectedTableData.value.findIndex(
        (item: any) => item._X_ROW_KEY === row._X_ROW_KEY
      )
      return index !== -1
    }
  }
  allTableRef.value?.exportData(exportConfig)
  // 将所有表格的值赋值为当前表格的值
  allTable.value.data = curTableData.value
}

const tableLoadingColumn = ref(false)

const CustomizeColumnsRef = ref()
// 打开定制表格弹窗
const handleCustomizeColumns = () => {
  const params = {
    getData: {
      action: 'ocean_order',
      operate: 'setting_ocean_order_display'
    },
    saveData: {
      action: 'ajax',
      operate: 'save_setting_display',
      model_name: 'Ocean_Search'
    }
  }
  CustomizeColumnsRef.value.openDialog(params, -153)
}

// 定制表格
const customizeColumns = async () => {
  await getTableColumns()
  nextTick(() => {
    tableRef.value && autoWidth(trackingTable.value, tableRef.value)
  })
}

// 双击表格跳转详情页
const handleCellDblclick = ({ row }: any) => {
  router.push({
    path: '/tracking/detail',
    query: { a: row.__serial_no, _schemas: row._schemas }
  })
}
// 点击link字段时
const handleLinkClick = (row: any, column: any) => {
  if (column.title === 'Booking No.') {
    router.push({
      path: '/booking/detail',
      query: { a: row.__serial_no, _schemas: row._schemas, status: row.Status }
    })
  } else if (column.title === 'HBL No.') {
    router.push({
      path: '/tracking/detail',
      query: { a: row.__serial_no, _schemas: row._schemas }
    })
  }
}

const selectedNumber = ref(0)
const selectedTableData = ref([])
// 复选框选中事件
const handleCheckboxChange = ({ records }: any) => {
  selectedNumber.value = records.length
  selectedTableData.value = records
}
const handleCheckAllChange = ({ records }: any) => {
  selectedNumber.value = records.length
  selectedTableData.value = records
}

// VGM
const handleVGM = (row) => {
  router.push({
    path: '/tracking/add-vgm',
    query: { a: row.__serial_no, _schemas: row._schemas }
  })
}

const loadingState = useLoadingState()

defineExpose({
  searchTableData,
  getSharedTableData,
  getLoadingData,
  pageInfo
})
</script>

<template>
  <div
    style="padding: 0px 24px"
    class="tracking-table"
    v-loading.fullscreen.lock="exportLoading"
    element-loading-background="rgb(43, 47, 54, 0.7)"
  >
    <div class="table-tools">
      <div class="left-total-records">{{ selectedNumber }} Selected</div>
      <div class="right-tools-btn">
        <el-button class="el-button--main" @click="handleDownload">
          <span style="margin-right: 8px" class="font_family icon-icon_download_b"></span>
          Download
        </el-button>
        <el-button type="default" @click="handleCustomizeColumns">
          <span style="margin-right: 8px" class="font_family icon-icon_column_b"></span>
          Customize Columns
        </el-button>
      </div>
    </div>

    <vxe-grid
      ref="tableRef"
      v-vloading="tableLoadingColumn || tableLoadingTable || loadingState.trackingTableLoading"
      :height="props.height"
      :style="{ border: 'none' }"
      v-bind="trackingTable"
      @cell-dblclick="handleCellDblclick"
      @checkbox-change="handleCheckboxChange"
      @checkbox-all="handleCheckAllChange"
    >
      <!-- 空数据时的插槽 -->
      <template #empty v-if="!tableLoadingTable && trackingTable.data.length === 0">
        <VEmpty>
          <template #suggestion>
            <p>We support the following references number to find tracking:</p>
            <p>
              · Tracking No./HAWB No./MAWB No./PO No./Carrier Tracking No./Contract No./File
              No./Quote No.
            </p>
          </template>
        </VEmpty>
      </template>
      <!-- action操作的插槽 -->
      <template #action="{ row }">
        <el-button @click="handleVGM(row)" class="el-button--blue" style="height: 24px">
          <span class="font_family icon-icon_vgm_b"></span> <span style="font-size: 12px">VGM</span>
        </el-button>
      </template>
      <!-- Transportation Mode字段的插槽 -->
      <template #mode="{ row, column }">
        <div>
          <span
            class="font_family"
            :class="[`icon-${transportationMode?.[row[column.field]]}`]"
            style="font-size: 24px"
          ></span>
        </div>
      </template>
      <!-- Status字段的插槽 -->
      <template #status="{ row, column }">
        <VTag :type="row[column.field]">{{ row[column.field] }}</VTag>
      </template>
      <!-- Tracking No字段的插槽 -->
      <template #trackingNo="{ row, column }">
        <span
          style="color: var(--color-theme); cursor: pointer"
          @click="handleLinkClick(row, column)"
        >
          {{ row[column.field] }}
        </span>
      </template>
    </vxe-grid>
    <vxe-grid :height="10" ref="allTableRef" class="all-table" v-bind="allTable"> </vxe-grid>
    <div class="bottom-pagination">
      <div class="left-total-records">Total {{ pageInfo.total }}</div>
      <div class="right-pagination">
        <el-pagination
          v-model:current-page="pageInfo.pageNo"
          v-model:page-size="pageInfo.pageSize"
          :page-sizes="[50, 100, 200, 300, 400]"
          :pagerCount="3"
          background
          layout="sizes, prev, pager, next"
          :total="pageInfo.total"
          @size-change="getTableData(true)"
          @current-change="getTableData(true)"
        />
      </div>
    </div>
    <DownloadDialog @export="getExportTableData" ref="downloadDialogRef" />
    <CustomizeColumns @customize="customizeColumns" ref="CustomizeColumnsRef" />
  </div>
</template>

<style lang="scss" scoped>
.table-tools {
  position: relative;
  display: flex;
  justify-content: space-between;
  height: 48px;
  padding: 8px 0;

  .left-total-records {
    font-size: 16px;
    font-weight: 700;
    line-height: 32px;
  }
}

.bottom-pagination {
  display: flex;
  justify-content: space-between;
  height: 40px;
  margin-top: -1px;
  padding: 4px 8px;
  border: 1px solid var(--color-border);
  border-radius: 0 0 12px 12px;

  .left-total-records {
    line-height: 32px;
  }

  .right-pagination {
    display: flex;
    align-items: center;
  }
}

.tracking-table {
  position: relative;
  overflow: hidden;

  .all-table {
    position: absolute;
    top: -100000px;
    width: 20px;
  }
}
</style>
