<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>
      <!-- <ElFormItem label="完结时间">
        <ADtPicker v-model="formData.finishTimes" :change-handler="research"/>
      </ElFormItem> -->
    </template>
    <template #simpleFormItem="formData">
      <!-- <ElFormItem>
        <ElSelect v-model="formData.orderStatus" placeholder="订单状态">
          <ElOption v-for="item in orderStatus" :key="item.val" :label="item.txt" :value="item.val"/>
        </ElSelect>
      </ElFormItem> -->
      <ElFormItem>
        <ElInput v-model="formData.sn" placeholder="订单编号"/>
      </ElFormItem>
    </template>
    <template #columns>
      <ElTableColumn fixed="left" label="订单编号" prop="sn" width="155"/>
      <ElTableColumn label="客户姓名" prop="contacts" width="120"/>
      <ElTableColumn label="客户电话" prop="phone" width="120"/>
      <ElTableColumn label="货品名称" prop="goodsName" width="120"/>
      <!-- <ElTableColumn label="项目名称" prop="projectName" 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="100"/>
      <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="truckLicensePlate" width="120">
        <template #default="{row}">
          {{ Strings.isBlank(row.truckLicensePlate) ? '-' : row.truckLicensePlate }}
        </template>
      </ElTableColumn>
      <ElTableColumn label="司机姓名" prop="driverName" width="120">
        <template #default="{row}">
          {{ row.driverName ?? '-' }}
        </template>
      </ElTableColumn>
      <ElTableColumn label="司机电话" prop="driverPhone" width="120">
        <template #default="{row}">
          {{ row.driverPhone ?? '-' }}
        </template>
      </ElTableColumn>
      <ElTableColumn fixed="right" label="总金额" prop="settleMoney" width="80">
        <template #default="{row}">
          {{ `${row.settleMoney == null ? '' : row.settleMoney + ' 元'}` }}
        </template>
      </ElTableColumn>
      <ElTableColumn label="下单时间" prop="orderTime" width="175"/>
      <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="transStatus" width="90">
        <template #default="{row}">
          <ElTag :data-cs="transStatusColor.cs(row.transStatus)"> {{ row.transStatusTxt }}</ElTag>
        </template>
      </ElTableColumn>
    </template>
    <BookForm ref="bookForm" :research="research"/>
    <BookDetail ref="bookDetail"/>
    <DispatchForm ref="dispatchForm" @succ="research"/>
  </ATablePage>
</template>

<script lang="ts" setup>
import BookForm from '@/pages/order/book/BookForm.vue'
import ADtPicker from '@/components/a-dt-picker/ADtPicker.vue'
import ATablePage, {
  type ATablePageInstance,
  buildTablePageProps,
} from '@/components/a-page/a-table-page/ATablePage.tsx'
import {
  orderCategory,
  paymentStatusColor,
  transStatus,
  transStatusColor,
} from '@/pages/order/constants.ts'
import BookDetail from '@/pages/order/book/BookDetail.vue'
import type { R } from '@/common/utils/http-util.ts'
import DispatchForm from '@/pages/order/book/DispatchForm.vue'
import OrderApi from '@/pages/order/order-api.ts'
import Strings from '@/common/utils/strings.ts'

const props = defineProps<{
  bizType: 'XiaoShou' | 'HuiShou' | 'DuanBo'
}>()

const tablePageIns = useTemplateRef<ATablePageInstance>('tablePage')
const bookFormIns = useTemplateRef<InstanceType<typeof BookForm>>('bookForm')
const bookDetailIns = useTemplateRef<InstanceType<typeof BookDetail>>('bookDetail')
const dispatchFormIns = useTemplateRef<InstanceType<typeof DispatchForm>>('dispatchForm')

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

const spanColumn = [ 'sn', 'orderTime', 'contacts', 'phone', 'goodsName', 'projectName', 'stationName', 'transOrgName', 'transDistance', 'tableAction' ]
const tablePageProps = buildTablePageProps<OrderTypes.SearchOrderParam, OrderTypes.TableData>({
  pageLayout: {
    searchFormHeight: '180px',
    dataListHeight: 1,
  },
  searchForm: {
    defaultData: {
      bizType: props.bizType,
      orderType: 'YuYue',
    },
    highForm: {
      contentWidth: 342,
      cgap: 20,
      rgap: 20,
    },
    simpleForm: {
      colCount: 1,
    },
    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 ?? []
            record.transRecodes = undefined
            for (let i = 0; i < transRecodes.length; i++) {
              const it = transRecodes[i]
              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>>
        })
    },
  },
  toolBar: {
    leftTools: [
      {
        icon: 'Plus',
        label: '新建',
        action() {
          bookFormIns.value?.open(orderCategory.HuiShouYuYue)
        },
      },
    ],
  },
  table: {
    spanMethod({row, column}) {
      if (!spanColumn.includes(column.property)) {
        return {
          rowspan: 1,
          colspan: 1,
        }
      }
      return {
        rowspan: row.rowCount,
        colspan: 1,
      }
    },
    actionColumn: {
      tableActions: [
        {
          tooltip: '详情',
          icon: 'Postcard',
          type: 'primary',
          action({row}) {
            bookDetailIns.value?.open(row)
          },
        },
        {
          tooltip: '批量派单',
          type: 'success',
          show({row}) {
            return row.transStatus === transStatus.DaiPaiDan
          },
          icon: 'Position',
          action({row}) {
            dispatchFormIns.value?.open({
              orderId: row.orderId,
              sn: row.sn,
              transOrgId: row.transOrgId,
            })
          },
        },
      ],
    },
  },
})
</script>
