<script lang="ts" setup>
import type { AssetDeliveryOrderApi } from '#/api/asset/delivery-order';

import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import InspectionForm from '../../components/InspectionForm.vue';

import {
  Button,
  Card,
  Col,
  Input,
  InputNumber,
  message,
  Row,
  Space,
  Switch,
  Table,
} from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import {
  createDeliveryOrder,
  getDeliveryOrder,
  updateDeliveryOrder,
} from '#/api/asset/delivery-order';
import { $t } from '#/locales';

import { useFormSchema } from '../data';

const emit = defineEmits(['success']);
const formData = ref<AssetDeliveryOrderApi.DeliveryOrder>();
const vehicles = ref<AssetDeliveryOrderApi.DeliveryOrderVehicle[]>([]);

// 司机信息
const driverInfo = ref({
  driverName: '',
  driverIdCard: '',
  driverPhone: '',
});

// 费用信息
const costList = ref<{ costName: string; amount: number; remark: string }[]>(
  [],
);

// 交检清单数据
const inspectionData = ref<
  Record<string, { checked: boolean; remark: string }>
>({});

const INSPECTION_ITEMS = [
  {
    category: '车辆附件',
    items: [
      '行驶证',
      '营运证',
      '通行证',
      '加氢证',
      '登记证',
      '保险卡',
      '车钥匙',
    ],
  },
  {
    category: '外观检查',
    items: ['车身完好', '挡风玻璃', '后视镜', '车灯完好', '轮胎正常'],
  },
  {
    category: '车内检查',
    items: [
      '仪表盘正常',
      '空调功能',
      '安全带',
      '喇叭功能',
      '雨刮器',
      '车窗升降',
    ],
  },
  {
    category: '动力系统',
    items: ['发动机正常', '燃料电池状态', '制动功能', '转向正常'],
  },
];

function initInspectionData() {
  const data: Record<string, { checked: boolean; remark: string }> = {};
  for (const cat of INSPECTION_ITEMS) {
    for (const item of cat.items) {
      data[`${cat.category}-${item}`] = { checked: true, remark: '' };
    }
  }
  inspectionData.value = data;
}
initInspectionData();

const inspectionTableData = computed(() => {
  const rows: any[] = [];
  for (const cat of INSPECTION_ITEMS) {
    for (let i = 0; i < cat.items.length; i++) {
      rows.push({
        key: `${cat.category}-${cat.items[i]}`,
        category: cat.category,
        item: cat.items[i]!,
        rowSpan: i === 0 ? cat.items.length : 0,
      });
    }
  }
  return rows;
});

const inspectionColumns = [
  {
    title: '类别',
    dataIndex: 'category',
    key: 'category',
    width: 120,
    customCell: (_: any, index: number) => {
      const row = inspectionTableData.value[index];
      return { rowSpan: row?.rowSpan ?? 1 };
    },
  },
  { title: '检查项目', dataIndex: 'item', key: 'item', width: 160 },
  { title: '交车方', key: 'deliver', width: 120 },
  { title: '接车方', key: 'receive', width: 120 },
  { title: '备注', key: 'remark', width: 180 },
];

const getTitle = computed(() => {
  return formData.value?.id
    ? $t('ui.actionTitle.edit', ['交车单'])
    : $t('ui.actionTitle.create', ['交车单']);
});

const [BasicForm, basicFormApi] = useVbenForm({
  commonConfig: {
    componentProps: { class: 'w-full' },
    formItemClass: 'col-span-2',
    labelWidth: 150,
  },
  layout: 'horizontal',
  schema: useFormSchema(),
  showDefaultActions: false,
  wrapperClass: 'grid-cols-6',
});

// 车辆明细列定义
const vehicleColumns = [
  { title: '序号', key: 'index', width: 60 },
  { title: '品牌', dataIndex: 'brand', key: 'brand', width: 100 },
  { title: '型号', dataIndex: 'model', key: 'model', width: 100 },
  { title: '车牌号', dataIndex: 'plateNo', key: 'plateNo', width: 120 },
  { title: 'VIN码', dataIndex: 'vin', key: 'vin', width: 180 },
  { title: '停车场', dataIndex: 'parkingLot', key: 'parkingLot', width: 120 },
  { title: '交车里程(km)', key: 'mileage', width: 130 },
  { title: '交车氢量(%)', key: 'hydrogenLevel', width: 120 },
  { title: '交车电量(%)', key: 'batteryLevel', width: 120 },
];

// 费用列定义
const costColumns = [
  { title: '序号', key: 'index', width: 60 },
  { title: '费用名称', key: 'costName', width: 200 },
  { title: '金额(元)', key: 'amount', width: 150 },
  { title: '备注', key: 'costRemark', width: 200 },
  { title: '操作', key: 'costAction', width: 80 },
];

function handleAddCost() {
  costList.value.push({ costName: '', amount: 0, remark: '' });
}
function handleDeleteCost(index: number) {
  costList.value.splice(index, 1);
}

const costTotal = computed(() => {
  return costList.value.reduce((sum, c) => sum + (c.amount || 0), 0);
});

const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    const { valid } = await basicFormApi.validate();
    if (!valid) return;

    modalApi.lock();
    const data =
      (await basicFormApi.getValues()) as AssetDeliveryOrderApi.DeliveryOrder;
    data.vehicles = vehicles.value;

    try {
      await (formData.value?.id
        ? updateDeliveryOrder(data)
        : createDeliveryOrder(data));
      await modalApi.close();
      emit('success');
      message.success($t('ui.actionMessage.operationSuccess'));
    } finally {
      modalApi.unlock();
    }
  },
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      formData.value = undefined;
      vehicles.value = [];
      costList.value = [];
      driverInfo.value = { driverName: '', driverIdCard: '', driverPhone: '' };
      initInspectionData();
      return;
    }

    const data = modalApi.getData<AssetDeliveryOrderApi.DeliveryOrder>();
    if (!data || !data.id) return;

    modalApi.lock();
    try {
      formData.value = await getDeliveryOrder(data.id);
      await basicFormApi.setValues(formData.value);
      vehicles.value = formData.value.vehicles || [];
    } finally {
      modalApi.unlock();
    }
  },
});
</script>

<template>
  <Modal :title="getTitle" class="w-4/5" style="max-width: 1400px">
    <div class="space-y-4" style="max-height: 75vh; overflow-y: auto">
      <!-- Card 1: 交车基本信息 -->
      <Card title="交车基本信息" size="small">
        <BasicForm />
      </Card>

      <!-- Card 2: 司机信息 -->
      <Card title="司机信息" size="small">
        <Row :gutter="24">
          <Col :span="8">
            <div class="mb-4">
              <label class="mb-1 block font-medium">司机姓名</label>
              <Input
                v-model:value="driverInfo.driverName"
                placeholder="请输入司机姓名"
              />
            </div>
          </Col>
          <Col :span="8">
            <div class="mb-4">
              <label class="mb-1 block font-medium">司机身份证</label>
              <Input
                v-model:value="driverInfo.driverIdCard"
                placeholder="请输入司机身份证号"
              />
            </div>
          </Col>
          <Col :span="8">
            <div class="mb-4">
              <label class="mb-1 block font-medium">司机手机号</label>
              <Input
                v-model:value="driverInfo.driverPhone"
                placeholder="请输入司机手机号"
              />
            </div>
          </Col>
        </Row>
      </Card>

      <!-- Card 3: 交车车辆明细 -->
      <Card title="交车车辆明细" size="small">
        <Table
          :columns="vehicleColumns"
          :data-source="vehicles"
          :pagination="false"
          :scroll="{ x: 1200 }"
          size="small"
          bordered
        >
          <template #bodyCell="{ column, record, index }">
            <template v-if="column.key === 'index'">
              {{ index + 1 }}
            </template>
            <template v-else-if="column.key === 'mileage'">
              <InputNumber
                v-model:value="record.mileage"
                :min="0"
                :precision="0"
                placeholder="里程"
                size="small"
                style="width: 100%"
              />
            </template>
            <template v-else-if="column.key === 'hydrogenLevel'">
              <InputNumber
                v-model:value="record.hydrogenLevel"
                :min="0"
                :max="100"
                :precision="0"
                placeholder="氢量%"
                size="small"
                style="width: 100%"
              />
            </template>
            <template v-else-if="column.key === 'batteryLevel'">
              <InputNumber
                v-model:value="record.batteryLevel"
                :min="0"
                :max="100"
                :precision="0"
                placeholder="电量%"
                size="small"
                style="width: 100%"
              />
            </template>
          </template>
        </Table>
      </Card>

      <!-- Card 4: 交检清单 -->
      <Card title="交检清单" size="small">
        <!-- 新版：使用验车记录组件 -->
        <template v-if="formData?.inspectionRecordId">
          <InspectionForm :record-id="formData.inspectionRecordId" :readonly="false" />
        </template>
        <!-- 旧版：硬编码检查单（兼容旧数据） -->
        <template v-else>
          <Table
            :columns="inspectionColumns"
            :data-source="inspectionTableData"
            :pagination="false"
            size="small"
            bordered
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'deliver'">
                <Switch
                  v-model:checked="inspectionData[record.key]!.checked"
                  checked-children="✓"
                  un-checked-children="×"
                  size="small"
                />
              </template>
              <template v-else-if="column.key === 'receive'">
                <Switch
                  checked-children="✓"
                  un-checked-children="×"
                  size="small"
                  disabled
                />
              </template>
              <template v-else-if="column.key === 'remark'">
                <Input
                  v-model:value="inspectionData[record.key]!.remark"
                  placeholder="备注"
                  size="small"
                />
              </template>
            </template>
          </Table>
        </template>
      </Card>

      <!-- Card 5: 费用信息 -->
      <Card title="费用信息" size="small">
        <Space direction="vertical" style="width: 100%" :size="12">
          <div
            v-if="costList.length > 0"
            class="rounded bg-blue-50 px-3 py-2 text-sm"
          >
            费用合计：<span class="font-semibold text-red-500"
              >¥{{ costTotal.toFixed(2) }}</span
            >
          </div>
          <Table
            :columns="costColumns"
            :data-source="costList"
            :pagination="false"
            size="small"
            bordered
          >
            <template #bodyCell="{ column, record, index }">
              <template v-if="column.key === 'index'">
                {{ index + 1 }}
              </template>
              <template v-else-if="column.key === 'costName'">
                <Input
                  v-model:value="record.costName"
                  placeholder="请输入费用名称"
                  size="small"
                />
              </template>
              <template v-else-if="column.key === 'amount'">
                <InputNumber
                  v-model:value="record.amount"
                  :min="0"
                  :precision="2"
                  placeholder="金额"
                  size="small"
                  style="width: 100%"
                />
              </template>
              <template v-else-if="column.key === 'costRemark'">
                <Input
                  v-model:value="record.remark"
                  placeholder="备注"
                  size="small"
                />
              </template>
              <template v-else-if="column.key === 'costAction'">
                <Button
                  type="link"
                  danger
                  size="small"
                  @click="handleDeleteCost(index)"
                >
                  删除
                </Button>
              </template>
            </template>
          </Table>
          <Button type="dashed" block @click="handleAddCost">
            + 添加费用项
          </Button>
        </Space>
      </Card>
    </div>
  </Modal>
</template>
