<template>
  <ATablePage
    ref="tablePage"
    v-bind="tablePageProps">
    <template #highFormItem="formData">
      <ElFormItem label="订单编号">
        <ElInput v-model="formData.sn" placeholder="订单编号"/>
      </ElFormItem>
      <!-- <ElFormItem label="订单状态">
        <ElSelect v-model="formData.orderStatus" placeholder="订单状态">
          <ElOption v-for="item in orderStatus" :key="item.val" :label="item.txt" :value="item.val"/>
        </ElSelect>
      </ElFormItem> -->
      <ElFormItem label="收纳站点">
        <ElInput v-model="formData.stationId" placeholder="收纳站点"/>
      </ElFormItem>
      <ElFormItem label="客户姓名">
        <ElInput v-model="formData.contacts" placeholder="客户姓名"/>
      </ElFormItem>
      <ElFormItem label="客户电话">
        <ElInput v-model="formData.phone" placeholder="客户电话"/>
      </ElFormItem>
      <ElFormItem label="运输企业">
        <ElInput v-model="formData.transOrgName" placeholder="运输企业"/>
      </ElFormItem>
      <ElFormItem label="项目名称">
        <ElInput v-model="formData.projectName" placeholder="项目名称"/>
      </ElFormItem>
      <ElFormItem label="下单时间">
        <ADtPicker v-model="formData.orderTimes" :change-handler="research"/>
      </ElFormItem>
    </template>
    <template #simpleFormItem="formData">
      <ElFormItem>
        <ElInput v-model="formData.keywords" placeholder="单号/车牌号"/>
      </ElFormItem>
    </template>
    <template #columns>
      <ElTableColumn fixed="left" label="订单编号" prop="sn" width="155"/>
      <!-- <ElTableColumn label="下单时间" prop="orderTime"/> -->
      <!-- <ElTableColumn label="客户姓名" prop="contacts"/> -->
      <!-- <ElTableColumn label="联系方式" prop="phone"/> -->
      <ElTableColumn label="货品名称" prop="goodsName" width="120"/>

      <!-- <ElTableColumn label="项目名称" show-overflow-tooltip width="100">
        <template #default="{row}">
          {{ row.projectName ?? '-' }}
        </template>
      </ElTableColumn> -->
      <!-- <ElTableColumn label="站点名称" prop="stationName" width="120"/> -->
      <!-- <ElTableColumn label="运输单位" prop="transOrgName" show-overflow-tooltip width="140"/> -->
      <!-- <ElTableColumn label="运距（米）" prop="transDistance"/> -->
      <ElTableColumn label="运距" prop="transDistance" width="100">
        <template #default="{row}">
          {{ `${row.transDistance == null ? '' : (row.transDistance / 1000) + ' 公里'}` }}
        </template>
      </ElTableColumn>
      <ElTableColumn label="车次" prop="trainNum" width="70"/>
      <ElTableColumn label="司机姓名" prop="driverName" width="120">
        <template #default="{row}">
          <span> {{ row.driverName ?? '-' }}</span>
        </template>
      </ElTableColumn>
      <ElTableColumn label="司机电话" prop="driverPhone" width="120">
        <template #default="{row}">
          <span> {{ row.driverName ?? '-' }}</span>
        </template>
      </ElTableColumn>
      <ElTableColumn label="车牌号" prop="truckLicensePlate" width="120">
        <template #default="{row}">
          <span> {{ row.truckLicensePlate ?? '-' }}</span>
        </template>
      </ElTableColumn>
      <!-- <ElTableColumn label="司机姓名" prop="driverName"/> -->
      <!-- <ElTableColumn label="司机电话" prop="driverPhone"/> -->

      <ElTableColumn label="毛重" prop="roughWeight" width="80">
        <template #default="{row}">
          {{ `${row.roughWeight == null ? '' : (row.roughWeight / 1000) + ' 吨'}` }}
        </template>
      </ElTableColumn>
      <ElTableColumn label="皮重" prop="tareWeight" width="80">
        <template #default="{row}">
          {{ `${row.tareWeight == null ? '' : (row.tareWeight / 1000) + ' 吨'}` }}
        </template>
      </ElTableColumn>
      <ElTableColumn label="净重" prop="settleWeight" width="80">
        <template #default="{row}">
          {{ `${row.settleWeight == null ? '' : (row.settleWeight / 1000) + ' 吨'}` }}
        </template>
      </ElTableColumn>
      <ElTableColumn label="进场时间" prop="inTime" width="175"/>
      <!-- <ElTableColumn label="开始运输时间" prop="transTime"/> -->
      <ElTableColumn label="出场时间" prop="outTime" width="175"/>
      <!-- <ElTableColumn label="完结时间" prop="finishTime"/> -->
      <ElTableColumn fixed="right" label="支付状态" prop="paymentStatusTxt" width="120">
        <template #default="{row}">
          <ElTag :data-cs="paymentStatusColor.cs(row.paymentStatus,'info')"> {{ row.paymentStatusTxt ?? '暂无支付信息' }}</ElTag>
        </template>
      </ElTableColumn>
      <ElTableColumn fixed="right" label="总金额" prop="settleMoney" width="80">
        <template #default="{row}">
          {{ `${row.settleMoney == null ? '' : row.settleMoney + ' 元'}` }}
        </template>
      </ElTableColumn>
      <ElTableColumn fixed="right" label="勘料状态" prop="checkStatusTxt" width="90">
        <template #default="{row}">
          <ElTag :data-cs="checkStatusColor.cs(row.checkStatus)"> {{ row.checkStatusTxt }}</ElTag>
        </template>
      </ElTableColumn>
      <ElTableColumn fixed="right" label="运输状态" prop="transStatusTxt" width="100">
        <template #default="{row}">
          <ElTag :data-cs="transStatusColor.cs(row.transStatus)"> {{ row.transStatusTxt }}</ElTag>
        </template>
      </ElTableColumn>

      <!-- <ElTableColumn label="客户备注" prop="customerMemo"/> -->
    </template>
    <RealtimeDetail ref="realtimeDetail"/>
    <InOutPanel ref="inOutPanel" @succ="research"/>
    <CheckPanel ref="checkPanel" @succ="research"/>
  </ATablePage>
</template>

<script lang="ts" setup>
import ADtPicker from '@/components/a-dt-picker/ADtPicker.vue'
import ATablePage, {
  type ATablePageInstance,
  buildTablePageProps,
} from '@/components/a-page/a-table-page/ATablePage.tsx'
import {
  checkStatus,
  checkStatusColor,
  paymentStatusColor,
  summaryMethod,
  transStatus,
  transStatusColor,
} from '@/pages/order/constants.ts'
import InOutPanel from '@/pages/order/realtime/InOutPanel.vue'
import { useTemplateRef } from 'vue'
import type { R } from '@/common/utils/http-util.ts'
import RealtimeDetail from '@/pages/order/realtime/RealtimeDetail.vue'
import CheckPanel from '@/pages/order/realtime/CheckPanel.vue'
import OrderApi from '@/pages/order/order-api.ts'

const props = defineProps<{
  bizType: 'XiaoShou' | 'HuiShou' | 'DuanBo'
}>()
const tablePageIns = useTemplateRef<ATablePageInstance>('tablePage')
const realtimeDetailIns = useTemplateRef<InstanceType<typeof RealtimeDetail>>('realtimeDetail')
const inOutPanelIns = useTemplateRef<InstanceType<typeof InOutPanel>>('inOutPanel')
const checkPanelIns = useTemplateRef<InstanceType<typeof CheckPanel>>('checkPanel')

function research() {
  tablePageIns.value?.doSearch()
}

const spanColumn = [ 'sn', 'orderTime', 'contacts', 'phone', 'goodsName', 'projectName', 'stationName', 'transOrgName', 'transDistance' ]

const tablePageProps = buildTablePageProps<OrderTypes.SearchOrderParam, OrderTypes.TableData>({
  pageLayout: {
    searchFormHeight: '180px',
    dataListHeight: 1,
  },
  searchForm: {
    defaultData: {
      bizType: props.bizType,
      orderType: 'ShiShi',
    },
    highForm: {
      contentWidth: 342,
    },
    paging(param: OrderTypes.SearchOrderParam) {
      return OrderApi.paging(param)
        .then(res => {
          const records = res.data.records
          const dataList: OrderTypes.TableData[] = []
          res.data.records = dataList
          for (const record of records) {
            const transRecodes = (record.transRecodes ?? []) as TransRecode[]
            record.transRecodes = undefined
            for (let i = 0; i < transRecodes.length; i++) {
              const it = transRecodes[i] as TransRecode
              const settleMoney = it.paymentRecords?.map(it1 => +(it1.settleMoney ?? 0)).reduce((a: number, b: number) => a + b, 0) ?? 0
              dataList.push({
                ...record,
                ...it,
                settleMoney,
                orderId: record.id,
                rowCount: i === 0 ? transRecodes.length : 0,
              } as OrderTypes.TableData)
            }
          }
          return res as R<G.PageResult<OrderTypes.TableData>>
        })
    },
  },
  table: {
    spanMethod({row, column}) {
      if (!spanColumn.includes(column.property)) {
        return {
          rowspan: 1,
          colspan: 1,
        }
      }
      return {
        rowspan: row.rowCount,
        colspan: 1,
      }
    },
    summaryMethod,
    actionColumn: {
      width: 185,
      foldLimit: 5,
      tableActions: [
        {
          tooltip: '详情',
          icon: 'Postcard',
          type: 'primary',
          action({row}) {
            realtimeDetailIns.value?.open(row)
          },
        },
        {
          tooltip: '进场',
          type: 'success',
          icon: 'approach',
          show({row}) {
            return row.transStatus === transStatus.YunShuZhong
          },
          action({row}) {
            inOutPanelIns.value?.open(row.id!, row.truckLicensePlate!, '进场')
          },
        },
        {
          tooltip: '出场',
          type: 'danger',
          icon: 'carexit',
          show({row}) {
            return row.transStatus === transStatus.YiJinChang && (row.checkStatus === checkStatus.Wu || row.checkStatus === checkStatus.YiKanLiao)
          },
          action({row}) {
            inOutPanelIns.value?.open(row.id!, row.truckLicensePlate!, '出场')
          },
        },
        { // 二级框  退单
          tooltip: '勘料',
          type: 'warning',
          icon: 'chakanliaodan',
          show({row}) {
            return row.transStatus === transStatus.YiJinChang && row.checkStatus === checkStatus.WeiKanLiao
          },
          action({row}) {
            checkPanelIns.value?.open(row.id!, row.truckLicensePlate!)
          },
        },
        {
          tooltip: '三联单',
          type: 'info',
          icon: 'liandan',
          action() {
          },
        },
        {
          tooltip: '实时轨迹',
          type: 'success',
          icon: 'yundanguiji',
          action() {
          },
        },
      ],
    },
  },
})
</script>
