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

import { computed, ref } from 'vue';

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

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

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

import { useVbenForm } from '#/adapter/form';
import {
  createReturnOrder,
  getReturnOrder,
  startVehicleInspection,
  updateReturnOrder,
} from '#/api/asset/return-order';
import { $t } from '#/locales';

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

const emit = defineEmits(['success']);
const formData = ref<AssetReturnOrderApi.ReturnOrder>();
const vehicles = ref<AssetReturnOrderApi.ReturnOrderVehicle[]>([]);

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: 'plateNo', key: 'plateNo', width: 120 },
  { title: '品牌', dataIndex: 'brand', key: 'brand', width: 100 },
  { title: '型号', dataIndex: 'model', key: 'model', width: 100 },
  { title: 'VIN码', dataIndex: 'vin', key: 'vin', width: 180 },
  { title: '还车里程(km)', key: 'returnMileage', width: 130 },
  { title: '还车氢量(%)', key: 'returnHydrogenLevel', width: 120 },
  {
    title: '交车氢量(%)',
    dataIndex: 'deliveryHydrogenLevel',
    key: 'deliveryHydrogenLevel',
    width: 120,
  },
  { title: '氢量差值', key: 'hydrogenDiff', width: 100 },
  { title: '氢费退还(元)', key: 'hydrogenRefundAmount', width: 120 },
  { title: '验车', key: 'inspection', width: 120 },
  { title: '操作', key: 'action', width: 80, fixed: 'right' as const },
];

function handleAddVehicle() {
  vehicles.value.push({
    plateNo: '',
    brand: '',
    model: '',
    vin: '',
    returnMileage: 0,
    returnHydrogenLevel: 0,
    deliveryHydrogenLevel: 0,
    hydrogenDiff: 0,
    hydrogenUnitPrice: 0,
    hydrogenRefundAmount: 0,
  });
}

function handleDeleteVehicle(index: number) {
  vehicles.value.splice(index, 1);
}

// ========== 车辆验车 ==========
async function handleStartInspection(vehicle: AssetReturnOrderApi.ReturnOrderVehicle) {
  if (!vehicle.id) return;
  await startVehicleInspection(vehicle.id);
  message.success('验车记录已创建');
  // Reload the return order to get updated inspectionRecordId
  if (formData.value?.id) {
    formData.value = await getReturnOrder(formData.value.id);
    vehicles.value = formData.value.vehicles || [];
  }
}

// ========== 费用核算 ==========
const costBreakdown = ref({
  vehicleDamageFee: 0,
  toolDamageFee: 0,
  unpaidMaintenanceFee: 0,
  unpaidRepairFee: 0,
  violationFee: 0,
  otherFee: 0,
});

// 各项费用合计
const totalDeductions = computed(() => {
  const c = costBreakdown.value;
  return (
    (c.vehicleDamageFee || 0) +
    (c.toolDamageFee || 0) +
    (c.unpaidMaintenanceFee || 0) +
    (c.unpaidRepairFee || 0) +
    (c.violationFee || 0) +
    (c.otherFee || 0)
  );
});

// 氢费退还合计
const totalHydrogenRefund = computed(() => {
  return vehicles.value.reduce(
    (sum, v) => sum + (v.hydrogenRefundAmount || 0),
    0,
  );
});

// 汇总
const summary = computed(() => {
  const depositRefund = formData.value?.depositRefund || 0;
  const totalRefund = depositRefund + totalHydrogenRefund.value;
  const totalDeduct = totalDeductions.value;
  const netAmount = totalRefund - totalDeduct;
  return {
    depositRefund,
    hydrogenRefund: totalHydrogenRefund.value,
    totalRefund,
    totalDeductions: totalDeduct,
    netAmount,
  };
});

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

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

function initInspectionData() {
  const data: Record<
    string,
    { deliver: boolean; receive: boolean; remark: string }
  > = {};
  for (const cat of INSPECTION_ITEMS) {
    for (const item of cat.items) {
      data[`${cat.category}-${item}`] = {
        deliver: true,
        receive: 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: 'inspRemark', width: 180 },
];

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

    if (vehicles.value.length === 0) {
      message.warning('请至少添加一辆还车车辆');
      return;
    }

    modalApi.lock();
    const data =
      (await basicFormApi.getValues()) as AssetReturnOrderApi.ReturnOrder;
    data.vehicles = vehicles.value;

    try {
      await (formData.value?.id
        ? updateReturnOrder(data)
        : createReturnOrder(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 = [];
      costBreakdown.value = {
        vehicleDamageFee: 0,
        toolDamageFee: 0,
        unpaidMaintenanceFee: 0,
        unpaidRepairFee: 0,
        violationFee: 0,
        otherFee: 0,
      };
      initInspectionData();
      return;
    }

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

    modalApi.lock();
    try {
      formData.value = await getReturnOrder(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">
        <Space direction="vertical" style="width: 100%" :size="12">
          <Table
            :columns="vehicleColumns"
            :data-source="vehicles"
            :pagination="false"
            :scroll="{ x: 1400 }"
            size="small"
            bordered
          >
            <template #bodyCell="{ column, record, index }">
              <template v-if="column.key === 'index'">
                {{ index + 1 }}
              </template>
              <template v-else-if="column.key === 'returnMileage'">
                <InputNumber
                  v-model:value="record.returnMileage"
                  :min="0"
                  :precision="0"
                  placeholder="里程"
                  size="small"
                  style="width: 100%"
                />
              </template>
              <template v-else-if="column.key === 'returnHydrogenLevel'">
                <InputNumber
                  v-model:value="record.returnHydrogenLevel"
                  :min="0"
                  :max="100"
                  :precision="0"
                  placeholder="氢量%"
                  size="small"
                  style="width: 100%"
                />
              </template>
              <template v-else-if="column.key === 'hydrogenDiff'">
                <span
                  :class="
                    (record.returnHydrogenLevel || 0) -
                      (record.deliveryHydrogenLevel || 0) <
                    0
                      ? 'text-red-500'
                      : 'text-green-600'
                  "
                >
                  {{
                    (
                      (record.returnHydrogenLevel || 0) -
                      (record.deliveryHydrogenLevel || 0)
                    ).toFixed(0)
                  }}%
                </span>
              </template>
              <template v-else-if="column.key === 'hydrogenRefundAmount'">
                <InputNumber
                  v-model:value="record.hydrogenRefundAmount"
                  :min="0"
                  :precision="2"
                  placeholder="退还金额"
                  size="small"
                  style="width: 100%"
                />
              </template>
              <template v-else-if="column.key === 'inspection'">
                <Button
                  v-if="!record.inspectionRecordId"
                  type="link"
                  size="small"
                  @click="handleStartInspection(record)"
                >
                  开始验车
                </Button>
                <span v-else class="text-green-600">已有验车记录</span>
              </template>
              <template v-else-if="column.key === 'action'">
                <Button
                  type="link"
                  danger
                  size="small"
                  @click="handleDeleteVehicle(index)"
                >
                  删除
                </Button>
              </template>
            </template>
          </Table>
          <Button type="dashed" block @click="handleAddVehicle">
            + 添加车辆
          </Button>
        </Space>
      </Card>

      <!-- Card 3: 交检清单（旧版兼容） -->
      <Card title="交检清单" size="small">
        <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]!.deliver"
                checked-children="✓"
                un-checked-children="×"
                size="small"
                disabled
              />
            </template>
            <template v-else-if="column.key === 'receive'">
              <Switch
                v-model:checked="inspectionData[record.key]!.receive"
                checked-children="✓"
                un-checked-children="×"
                size="small"
              />
            </template>
            <template v-else-if="column.key === 'inspRemark'">
              <Input
                v-model:value="inspectionData[record.key]!.remark"
                placeholder="备注"
                size="small"
              />
            </template>
          </template>
        </Table>
      </Card>

      <!-- 车辆验车详情 -->
      <template v-for="vehicle in vehicles" :key="vehicle.id">
        <Card
          v-if="vehicle.inspectionRecordId"
          :title="`${vehicle.plateNo || '车辆'} - 验车记录`"
          size="small"
          class="mt-2"
        >
          <InspectionForm :record-id="vehicle.inspectionRecordId" :readonly="false" />
        </Card>
      </template>

      <!-- Card 4: 费用核算 -->
      <Card title="费用核算" size="small">
        <Row :gutter="24">
          <Col :span="8">
            <div class="mb-4">
              <label class="mb-1 block font-medium">车辆损坏费用</label>
              <InputNumber
                v-model:value="costBreakdown.vehicleDamageFee"
                :min="0"
                :precision="2"
                addon-after="元"
                placeholder="请输入"
                style="width: 100%"
              />
            </div>
          </Col>
          <Col :span="8">
            <div class="mb-4">
              <label class="mb-1 block font-medium">工具损坏费用</label>
              <InputNumber
                v-model:value="costBreakdown.toolDamageFee"
                :min="0"
                :precision="2"
                addon-after="元"
                placeholder="请输入"
                style="width: 100%"
              />
            </div>
          </Col>
          <Col :span="8">
            <div class="mb-4">
              <label class="mb-1 block font-medium">未结保养费</label>
              <InputNumber
                v-model:value="costBreakdown.unpaidMaintenanceFee"
                :min="0"
                :precision="2"
                addon-after="元"
                placeholder="请输入"
                style="width: 100%"
              />
            </div>
          </Col>
          <Col :span="8">
            <div class="mb-4">
              <label class="mb-1 block font-medium">未结维修费</label>
              <InputNumber
                v-model:value="costBreakdown.unpaidRepairFee"
                :min="0"
                :precision="2"
                addon-after="元"
                placeholder="请输入"
                style="width: 100%"
              />
            </div>
          </Col>
          <Col :span="8">
            <div class="mb-4">
              <label class="mb-1 block font-medium">违章罚款</label>
              <InputNumber
                v-model:value="costBreakdown.violationFee"
                :min="0"
                :precision="2"
                addon-after="元"
                placeholder="请输入"
                style="width: 100%"
              />
            </div>
          </Col>
          <Col :span="8">
            <div class="mb-4">
              <label class="mb-1 block font-medium">其他费用</label>
              <InputNumber
                v-model:value="costBreakdown.otherFee"
                :min="0"
                :precision="2"
                addon-after="元"
                placeholder="请输入"
                style="width: 100%"
              />
            </div>
          </Col>
        </Row>

        <Divider />

        <!-- 费用汇总 -->
        <div class="grid grid-cols-5 gap-4 rounded bg-gray-50 p-4">
          <div class="text-center">
            <div class="text-xs text-gray-500">退还保证金</div>
            <div class="mt-1 text-lg font-semibold">
              ¥{{ summary.depositRefund.toFixed(2) }}
            </div>
          </div>
          <div class="text-center">
            <div class="text-xs text-gray-500">氢费退还</div>
            <div class="mt-1 text-lg font-semibold">
              ¥{{ summary.hydrogenRefund.toFixed(2) }}
            </div>
          </div>
          <div class="text-center">
            <div class="text-xs text-gray-500">应退总额</div>
            <div class="mt-1 text-lg font-semibold text-green-600">
              ¥{{ summary.totalRefund.toFixed(2) }}
            </div>
          </div>
          <div class="text-center">
            <div class="text-xs text-gray-500">扣款总额</div>
            <div class="mt-1 text-lg font-semibold text-red-500">
              ¥{{ summary.totalDeductions.toFixed(2) }}
            </div>
          </div>
          <div class="text-center">
            <div class="text-xs text-gray-500">
              {{ summary.netAmount >= 0 ? '应退款' : '应缴纳' }}
            </div>
            <div
              class="mt-1 text-xl font-bold"
              :class="
                summary.netAmount >= 0 ? 'text-green-600' : 'text-red-500'
              "
            >
              ¥{{ Math.abs(summary.netAmount).toFixed(2) }}
            </div>
          </div>
        </div>
      </Card>
    </div>
  </Modal>
</template>
