<template>
  <div class="page card h-100 flex-gap-10 overflow-hidden flex">
    <div class="left">
      <ElTree
        ref="treeRef"
        default-expand-all
        :expand-on-click-node="false"
        :default-expanded-keys="[]"
        :highlight-current="true"
        node-key="status"
        :data="treeData"
        :props="{ children: 'children', label: 'name' }"
        @node-click="nodeClick"
      >
        <template #default="{ data }">
          <div class="tree-node">
            <div class="tree-node-label">{{ data.name }}</div>
            <div v-if="data.num || data.num === 0" class="tree-node-count">
              {{ `(${data.num})` }}
            </div>
          </div>
        </template>
      </ElTree>
    </div>
    <div class="right">
      <split-div>
        <template #top>
          <el-card>
            <el-form inline :model="searchForm" ref="searchFormRef">
              <el-form-item label="创建时间">
                <el-date-picker
                  v-model="tradingTime"
                  :shortcuts="pickerOptions.shortcuts"
                  :default-time="[
                    new Date(0, 0, 0, 0, 0, 0),
                    new Date(0, 0, 0, 23, 59, 59),
                  ]"
                  type="datetimerange"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  clearable
                  style="width: 260px"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </el-form-item>
              <el-form-item label="物流跟踪号">
                <el-input
                  v-model="searchForm.trackNumber"
                  style="width: 180px"
                  placeholder="请输入物流跟踪号"
                  clearable
                ></el-input>
              </el-form-item>
              <el-form-item label="店铺单号">
                <el-input
                  v-model="searchForm.shopNumber"
                  style="width: 180px"
                  placeholder="请输入店铺单号"
                  clearable
                ></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="getData" ref="searchBtnRef"
                  >查询</el-button
                >
                <el-button
                  v-if="nodeId === 0 || nodeId === 11"
                  type="success"
                  @click="batchRegister"
                >
                  批量注册跟踪
                </el-button>
                <el-button
                  v-if="nodeId !== -1 && nodeId !== 0 && nodeId !== 11"
                  type="warning"
                  @click="batchPushOrder"
                >
                  批量同步跟踪
                </el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </template>
        <template #bottom>
          <el-card style="height: 100%">
            <div class="manage">
              <div class="table-flex">
                <div class="left-table">
                  <div class="table-container">
                    <TableView
                      ref="tableRef"
                      :columns="tableColumns"
                      :serial-numberable="true"
                      :selectionable="true"
                      :paginated-data="leftData"
                      :is-more="true"
                      highlight-current-row
                      @selection-change="handleSelectionChange"
                    >
                      <template #orderStatus="{ row }">
                        <div>{{ getStatus(row.orderStatus) }}</div>
                      </template>
                      <template #shipmentType="{ row }">
                        {{ ['自有物流', '工厂物流'][row.shipmentType] }}
                      </template>
                      <template #shippingAge="{ row }">
                        {{ getShippingAge(row) }}
                      </template>
                    </TableView>
                  </div>
                  <div class="pagination">
                    <el-pagination
                      v-model:current-page="pagination.currentPage"
                      v-model:page-size="pagination.pageSize"
                      :page-sizes="[50, 100, 150, 200]"
                      layout="total, sizes, prev, pager, next, jumper"
                      :total="pagination.total"
                      @size-change="handleSizeChange"
                      @current-change="handleCurrentChange"
                    />
                  </div>
                </div>
              </div>
            </div>
          </el-card>
        </template>
      </split-div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { nextTick, ref, onMounted, computed } from 'vue'
import { ElMessage, ElTree } from 'element-plus'

import SplitDiv from '@/components/splitDiv/splitDiv.vue'
import TableView from '@/components/TableView.vue'

import {
  ILogisticsCompany,
  ILogisticsCompanyData,
  logisticsTrackingPage,
  logisticStatusList,
  logisticsTrackingBatchRegister,
  logisticsTrackingBatchPushOrder,
} from '@/api/logistics.ts'
import { getOrderTabData } from '@/api/podUsOrder'
import { LogisticsTrackingTree } from '@/views/logistics/types/logistics'
import { Tab } from '@/types/api/podUsOrder'
import { useEnterKeyTrigger } from '@/utils/hooks/useEnterKeyTrigger.ts'

interface SearchForm {
  shopNumber: string
  trackNumber: string | number
}

const searchForm = ref<SearchForm>({
  shopNumber: '',
  trackNumber: '',
})
function getStartTime() {
  const date = new Date()
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  return `${year}-${month}-${day} 00:00:00`
}
const tradingTime = ref<string[]>([])
const pickerOptions = {
  shortcuts: [
    {
      text: '今日',
      value: () => {
        const start = new Date(new Date(getStartTime()).getTime())
        const end = new Date()
        return [start, end]
      },
    },
    {
      text: '昨天',
      value: () => {
        const start = new Date()
        const end = new Date(new Date(getStartTime()).getTime() - 1)
        start.setTime(end.getTime() - 3600 * 1000 * 24 * 1 + 1)
        return [start, end]
      },
    },
    {
      text: '最近7天',
      value: () => {
        const end = new Date()
        const start = new Date(getStartTime())
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 6)
        return [start, end]
      },
    },
    {
      text: '最近14天',
      value: () => {
        const end = new Date()
        const start = new Date(getStartTime())
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 13)
        return [start, end]
      },
    },
    {
      text: '最近30天',
      value: () => {
        const end = new Date()
        const start = new Date(getStartTime())
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 29)
        return [start, end]
      },
    },
    {
      text: '本星期',
      value: () => {
        const end = new Date()
        const start = new Date()
        const nowDay = new Date().getDay() - 1
        start.setTime(
          new Date(getStartTime()).getTime() - 3600 * 1000 * 24 * nowDay,
        )
        return [start, end]
      },
    },
    {
      text: '上星期',
      value: () => {
        const end = new Date()
        const start = new Date()
        const nowDay = new Date().getDay() - 1
        end.setTime(
          new Date(getStartTime()).getTime() - 3600 * 1000 * 24 * nowDay - 1,
        )
        start.setTime(end.getTime() - 3600 * 1000 * 24 * 7 + 1)
        return [start, end]
      },
    },
    {
      text: '这个月',
      value: () => {
        const end = new Date()
        const start = new Date()
        const nowDate = new Date().getDate() - 1
        start.setTime(
          new Date(getStartTime()).getTime() - 3600 * 1000 * 24 * nowDate,
        )
        return [start, end]
      },
    },
    {
      text: '上个月',
      value: () => {
        const date = new Date()
        let year = date.getFullYear()
        let month = date.getMonth()
        const end = new Date(
          new Date(`${year}-${month + 1}-1 00:00:00`).getTime() - 1,
        )
        if (month === 0) {
          month = 12
          year = year - 1
        }
        const start = new Date(
          new Date(`${year}-${month}-1 00:00:00`).getTime(),
        )
        return [start, end]
      },
    },
    {
      text: '历史',
      value: () => {
        return ['', '']
      },
    },
  ],
}
const treeData = ref<LogisticsTrackingTree[]>()
const treeRef = ref<InstanceType<typeof ElTree>>()
const tableRef = ref<{ internalIsMore?: boolean }>()
const nodeId = ref<number>(-1)

const selections = ref<ILogisticsCompany[]>([])

const leftData = ref<ILogisticsCompany[]>([])
const pagination = ref<ILogisticsCompanyData>({
  pageSize: 50,
  currentPage: 1,
  total: 0,
})

// 表格列配置
const tableColumns = computed(() => {
  return [
    {
      label: '物流跟踪号',
      prop: 'trackingNumber',
      width: 200,
      align: 'center',
      showOverflowTooltip: true,
    },
    {
      label: '店铺单号',
      prop: 'shopNumber',
      width: 160,
      align: 'center',
    },
    {
      label: '订单号',
      prop: 'factoryOrderNumber',
      width: 160,
      align: 'center',
    },
    {
      label: '第三方订单号',
      prop: 'thirdOrderNumber',
      width: 240,
      align: 'center',
    },
    {
      label: '创建时间',
      prop: 'createTime',
      width: 200,
      align: 'center',
    },
    {
      label: '发货时效(天)',
      prop: 'shippingAge',
      slot: 'shippingAge',
      width: 120,
      align: 'center',
    },
    {
      label: '订单状态',
      prop: 'orderStatus',
      slot: 'orderStatus',
      width: 160,
      align: 'center',
    },
    {
      label: '物流类型',
      slot: 'shipmentType',
      prop: 'shipmentType',
      width: 120,
      align: 'center',
    },
    {
      label: '总克重(g)',
      prop: 'weight',
      width: 100,
      align: 'center',
    },
    {
      label: '生产端',
      prop: 'productionClient',
      width: 100,
      align: 'center',
    },
    {
      label: '发货仓库',
      prop: 'warehouseName',
      width: 120,
      align: 'center',
    },
    {
      label: '物流方式',
      prop: 'logisticsWayName',
      width: 120,
      align: 'center',
    },
    {
      label: '收货人',
      prop: 'receiverName',
      width: 150,
      align: 'center',
      showOverflowTooltip: true,
    },
    {
      label: '收货人电话',
      prop: 'receiverPhone',
      width: 140,
      align: 'center',
      showOverflowTooltip: true,
    },
    {
      label: '收货人邮编',
      prop: 'receiverPostCode',
      width: 140,
      align: 'center',
    },
    {
      label: '收货地址',
      prop: 'lanshouAddress',
      width: 500,
      align: 'center',
      showOverflowTooltip: true,
    },
  ]
})
// 获取菜单树
const getTree = async () => {
  try {
    const res = await logisticStatusList()
    treeData.value = res.data
    await nextTick(() => {
      treeRef.value!.setCurrentKey(nodeId.value, true)
    })
  } catch (e) {
    console.error(e)
  }
}
/** 计算发货时效（天）
 *  已签收 → 停止计时
 *  <12h = 0天；≥12h & <24h = 1天；≥48h = 2天 ...
 */
function getShippingAge(row: ILogisticsCompany): number {
  // 成功签收就固定: 已签收时间 - 创建时间
  if (row.orderStatus === 'COMPLETE') {
    const signTime = new Date(row.signTime ?? 0).getTime()
    const createTime = new Date(row.createTime ?? 0).getTime()
    return msToDays(signTime - createTime)
  }
  // 未签收：当前时间 - 创建时间
  const now = Date.now()
  const create = new Date(row.createTime ?? 0).getTime()
  return msToDays(now - create)
}

/** 毫秒 → 天数（≥12h 向下取整） */
function msToDays(ms: number): number {
  const hours = ms / (1000 * 60 * 60)
  if (hours < 12) return 0
  return Math.floor(hours / 24)
}
// 列表查询
async function getData() {
  const res = await logisticsTrackingPage({
    trackingStatus: nodeId.value,
    shopNumber: searchForm.value.shopNumber,
    trackNumber: searchForm.value.trackNumber,
    startTime: tradingTime.value && tradingTime.value[0],
    endTime: tradingTime.value && tradingTime.value[1],
    queryDateType: tradingTime.value && 1,
  })
  leftData.value = res.data.records
  pagination.value.total = res.data.total
}

// 批量注册
const batchRegister = async () => {
  if (selections.value.length === 0) {
    ElMessage.warning('请选择要注册的订单')
    return
  }
  try {
    await ElMessageBox.confirm(`确定批量注册？`, '重要提示', {
      confirmButtonText: '确定',
      type: 'warning',
    })
  } catch (error) {
    return
  }
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    await logisticsTrackingBatchRegister({
      idList: tableRef.value?.internalIsMore
        ? []
        : selections.value.map((d) => d.id),
      selectAll: tableRef.value?.internalIsMore || false,
    })
    loading.close()
    selections.value = []
    ElMessage.success('操作成功')
    getData()
  } catch (err) {
    console.log(err)
  } finally {
    loading.close()
  }
}

// 批量同步
const batchPushOrder = async () => {
  if (selections.value.length === 0) {
    ElMessage.warning('请选择要同步的订单')
    return
  }
  try {
    await ElMessageBox.confirm(`确定批量同步？`, '重要提示', {
      confirmButtonText: '确定',
      type: 'warning',
    })
  } catch (error) {
    return
  }
  const loading = ElLoading.service({
    fullscreen: true,
    text: '操作中...',
    background: 'rgba(0, 0, 0, 0.3)',
  })
  try {
    await logisticsTrackingBatchPushOrder({
      idList: selections.value.map((d) => d.id),
      selectAll: false,
    })
    loading.close()
    selections.value = []
    ElMessage.success('操作成功')
    getData()
  } catch (err) {
    console.log(err)
  } finally {
    loading.close()
  }
}

const tabsNav = ref<Tab[]>([])

const loadTabData = async () => {
  try {
    const res = await getOrderTabData()
    tabsNav.value = res.data.filter((el) => el.status !== 'BATCH_DOWNLOAD')
  } catch (error) {
    // showError(error)
  }
}

function getStatus(status: string) {
  const item = tabsNav.value.find((el) => el.status === status)

  if (item) {
    return item.statusName
  }
  return ''
}

const nodeClick = (data: LogisticsTrackingTree) => {
  nodeId.value = data.status ?? 0
  getData()
}

const handleSelectionChange = (data: ILogisticsCompany[]) => {
  selections.value = data
}
const handleSizeChange = (pageSize: number) => {
  pagination.value.pageSize = pageSize
  getData()
}
const handleCurrentChange = (currentPage: number) => {
  pagination.value.currentPage = currentPage
  getData()
}

onMounted(() => {
  getTree()
  getData()
  loadTabData()
})
/**
 * @description: 页面添加回车监听
 */
const searchFormRef = ref()
const searchBtnRef = ref()
useEnterKeyTrigger({
  formRef: searchFormRef,
  btnRef: searchBtnRef,

  callback: (event: KeyboardEvent) => {
    console.log('回车键被按下', event)
    getData()
  },
})
</script>

<style scoped lang="scss">
.el-card {
  ::v-deep(.el-card__body) {
    height: 100%;
  }
}

.manage {
  height: 100%;
  display: flex;
  flex-direction: column;

  .header {
    margin-bottom: 10px;
  }

  .table-flex {
    flex: 1;
    flex-shrink: 0;
    overflow: hidden;
    display: flex;
  }

  .right-table {
    flex: 1;
    margin-left: 10px;
    flex-shrink: 0;
  }

  .left-table {
    height: 100%;
    display: flex;
    width: 100%;
    flex-direction: column;

    .pagination {
      display: flex;
      margin-top: 10px;
      justify-content: center;
    }

    .table-container {
      flex: 1;
      flex-shrink: 0;
      overflow: hidden;
    }
  }
}
.left {
  width: 160px;
  :deep(.el-tree-node__content) {
    height: 30px;
    line-height: 30px;
  }
  :deep(.el-tree-node__label) {
    font-size: 13px;
    cursor: pointer;
    display: inline-block;
    width: 100%;
    color: black !important;

    padding: 3px 7px;
  }

  :deep(.el-tree-node__expand-icon) {
    display: none;
  }

  .tree-node {
    display: flex;
    color: #333;
    font-weight: 500;
  }
  :deep(.is-current) {
    .tree-node-label,
    .tree-node-count {
      background-color: #ecf5ff;
      color: #409eff !important;
    }

    .el-tree-node__children {
      .tree-node-label,
      .tree-node-count {
        background-color: transparent !important;
        color: black !important;
      }
    }
  }
}
.right {
  flex: 1;
  flex-shrink: 0;
  background: white;
  overflow: hidden;
}
</style>
