<script lang="ts" setup>
import type { AssetVehiclePrepareApi } from '#/api/asset/vehicle-prepare';

import { computed, ref } from 'vue';

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

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

import {
  Button,
  Card,
  Col,
  Divider,
  Drawer,
  Input,
  InputNumber,
  message,
  Row,
  Select,
  Switch,
  Table,
  Upload,
} from 'ant-design-vue';
import { PlusOutlined } from '@vben/icons';

import { useVbenForm } from '#/adapter/form';
import {
  createVehiclePrepare,
  getVehiclePrepare,
  updateVehiclePrepare,
} from '#/api/asset/vehicle-prepare';
import { $t } from '#/locales';

import {
  CHECK_CATEGORIES,
  HYDROGEN_UNIT_OPTIONS,
  PREP_TYPE_OPTIONS,
} from '../data';

const emit = defineEmits(['success']);
const formData = ref<AssetVehiclePrepareApi.VehiclePrepare>();
const getTitle = computed(() => {
  return formData.value?.id
    ? $t('ui.actionTitle.edit', ['备车记录'])
    : $t('ui.actionTitle.create', ['备车记录']);
});

// ========== 车辆基本信息 ==========
const vehicleInfo = ref({
  vehicleId: undefined as number | undefined,
  plateNo: '',
  vehicleType: '',
  brand: '',
  model: '',
  vin: '',
  parkingLot: '',
});

// ========== 整备信息 ==========
const prepInfo = ref({
  preparationType: '日常整备',
  mileage: undefined as number | undefined,
  hydrogenRemaining: undefined as number | undefined,
  hydrogenUnit: '%',
  batteryRemaining: undefined as number | undefined,
  commercialInsuranceExpiry: '',
  compulsoryInsuranceExpiry: '',
  hasBodyAd: false,
  hasTailLift: false,
  trailerPlateNo: '',
  spareTireDepth: undefined as number | undefined,
  remark: '',
});

// ========== 照片上传 ==========
const bodyAdPhotos = ref<any[]>([]);
const enlargedTextPhotos = ref<any[]>([]);
const spareTirePhotos = ref<any[]>([]);
const defectPhotos = ref<any[]>([]);

// ========== 备车检查单 ==========
const checkDrawerVisible = ref(false);
const checkData = ref<
  Record<string, { checked: boolean; remark: string; depth?: number }>
>({});

function initCheckData() {
  const data: Record<
    string,
    { checked: boolean; remark: string; depth?: number }
  > = {};
  for (const cat of CHECK_CATEGORIES) {
    for (const item of cat.items) {
      const key = `${cat.category}-${item}`;
      data[key] = { checked: true, remark: '', depth: undefined };
    }
  }
  checkData.value = data;
}
initCheckData();

// 生成检查表数据源（带行合并信息）
const checkTableData = computed(() => {
  const rows: any[] = [];
  for (const cat of CHECK_CATEGORIES) {
    for (let i = 0; i < cat.items.length; i++) {
      rows.push({
        key: `${cat.category}-${cat.items[i]}`,
        category: cat.category,
        item: cat.items[i]!,
        isInput: cat.type === 'input',
        rowSpan: i === 0 ? cat.items.length : 0,
      });
    }
  }
  return rows;
});

const checkColumns = [
  {
    title: '类别',
    dataIndex: 'category',
    key: 'category',
    width: 120,
    customCell: (_: any, index: number) => {
      const row = checkTableData.value[index];
      return { rowSpan: row?.rowSpan ?? 1 };
    },
  },
  { title: '检查项目', dataIndex: 'item', key: 'item', width: 160 },
  { title: '检查情况', key: 'check', width: 160 },
  { title: '备注', key: 'remark', width: 200 },
];

// 已完成的检查项统计
const checkSummary = computed(() => {
  const total = Object.keys(checkData.value).length;
  const normal = Object.values(checkData.value).filter(
    (v) => v.checked,
  ).length;
  return { total, normal, abnormal: total - normal };
});

// ========== 重置表单 ==========
function resetForm() {
  vehicleInfo.value = {
    vehicleId: undefined,
    plateNo: '',
    vehicleType: '',
    brand: '',
    model: '',
    vin: '',
    parkingLot: '',
  };
  prepInfo.value = {
    preparationType: '日常整备',
    mileage: undefined,
    hydrogenRemaining: undefined,
    hydrogenUnit: '%',
    batteryRemaining: undefined,
    commercialInsuranceExpiry: '',
    compulsoryInsuranceExpiry: '',
    hasBodyAd: false,
    hasTailLift: false,
    trailerPlateNo: '',
    spareTireDepth: undefined,
    remark: '',
  };
  bodyAdPhotos.value = [];
  enlargedTextPhotos.value = [];
  spareTirePhotos.value = [];
  defectPhotos.value = [];
  initCheckData();
}

// ========== Modal ==========
const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    // 基础校验
    if (!vehicleInfo.value.vehicleId) {
      message.warning('请选择车牌号');
      return;
    }

    modalApi.lock();
    const data = {
      ...vehicleInfo.value,
      ...prepInfo.value,
      checkList: JSON.stringify(checkData.value),
    } as any;

    if (formData.value?.id) {
      data.id = formData.value.id;
    }

    try {
      await (formData.value?.id
        ? updateVehiclePrepare(data)
        : createVehiclePrepare(data));
      await modalApi.close();
      emit('success');
      message.success($t('ui.actionMessage.operationSuccess'));
    } finally {
      modalApi.unlock();
    }
  },
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      formData.value = undefined;
      resetForm();
      return;
    }

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

    modalApi.lock();
    try {
      formData.value = await getVehiclePrepare(data.id);
      // 回填表单数据
      vehicleInfo.value = {
        vehicleId: formData.value.vehicleId,
        plateNo: formData.value.plateNo || '',
        vehicleType: formData.value.vehicleType || '',
        brand: formData.value.brand || '',
        model: formData.value.model || '',
        vin: formData.value.vin || '',
        parkingLot: formData.value.parkingLot || '',
      };
      prepInfo.value = {
        ...prepInfo.value,
        hasBodyAd: formData.value.hasBodyAd || false,
        hasTailLift: formData.value.hasTailLift || false,
        spareTireDepth: formData.value.spareTireDepth,
        trailerPlateNo: formData.value.trailerPlateNo || '',
      };
      if (formData.value.checkList) {
        try {
          checkData.value = JSON.parse(formData.value.checkList);
        } catch {}
      }
    } finally {
      modalApi.unlock();
    }
  },
});

const isView = computed(() => {
  const mode = modalApi.getData<any>()?._mode;
  return !!mode && mode === 'view';
});
</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">
        <Row :gutter="24">
          <Col :span="8">
            <div class="mb-4">
              <label class="mb-1 block font-medium">
                <span class="text-red-500">*</span> 车牌号
              </label>
              <Select
                v-model:value="vehicleInfo.vehicleId"
                placeholder="请选择或输入车牌号"
                show-search
                :filter-option="
                  (input: string, option: any) =>
                    (option?.label ?? '')
                      .toLowerCase()
                      .includes(input.toLowerCase())
                "
                style="width: 100%"
              >
                <!-- 实际应从API获取 -->
              </Select>
            </div>
          </Col>
          <Col :span="8">
            <div class="mb-4">
              <label class="mb-1 block font-medium">车辆类型</label>
              <Input
                v-model:value="vehicleInfo.vehicleType"
                placeholder="选择车牌号后自动填充"
                disabled
              />
            </div>
          </Col>
          <Col :span="8">
            <div class="mb-4">
              <label class="mb-1 block font-medium">品牌</label>
              <Input
                v-model:value="vehicleInfo.brand"
                placeholder="选择车牌号后自动填充"
                disabled
              />
            </div>
          </Col>
          <Col :span="8">
            <div class="mb-4">
              <label class="mb-1 block font-medium">型号</label>
              <Input
                v-model:value="vehicleInfo.model"
                placeholder="选择车牌号后自动填充"
                disabled
              />
            </div>
          </Col>
          <Col :span="8">
            <div class="mb-4">
              <label class="mb-1 block font-medium">车辆识别代码</label>
              <Input
                v-model:value="vehicleInfo.vin"
                placeholder="选择车牌号后自动填充"
                disabled
              />
            </div>
          </Col>
          <Col :span="8">
            <div class="mb-4">
              <label class="mb-1 block font-medium">停车场</label>
              <Select
                v-model:value="vehicleInfo.parkingLot"
                placeholder="请选择停车场"
                style="width: 100%"
                allow-clear
              >
                <!-- 从停车场API获取 -->
              </Select>
            </div>
          </Col>
        </Row>
      </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>
              <Select
                v-model:value="prepInfo.preparationType"
                :options="PREP_TYPE_OPTIONS"
                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="prepInfo.mileage"
                :min="0"
                :precision="0"
                addon-after="km"
                placeholder="请输入里程"
                style="width: 100%"
              />
            </div>
          </Col>
          <Col :span="8">
            <div class="mb-4">
              <label class="mb-1 block font-medium">剩余氢量</label>
              <div class="flex gap-2">
                <InputNumber
                  v-model:value="prepInfo.hydrogenRemaining"
                  :min="0"
                  :precision="1"
                  placeholder="请输入"
                  class="flex-1"
                />
                <Select
                  v-model:value="prepInfo.hydrogenUnit"
                  :options="HYDROGEN_UNIT_OPTIONS"
                  style="width: 80px"
                />
              </div>
            </div>
          </Col>
          <Col :span="8">
            <div class="mb-4">
              <label class="mb-1 block font-medium">剩余电量</label>
              <InputNumber
                v-model:value="prepInfo.batteryRemaining"
                :min="0"
                :max="100"
                :precision="0"
                addon-after="%"
                placeholder="请输入电量百分比"
                style="width: 100%"
              />
            </div>
          </Col>
          <Col :span="8">
            <div class="mb-4">
              <label class="mb-1 block font-medium">商业险到期时间</label>
              <Input
                v-model:value="prepInfo.commercialInsuranceExpiry"
                placeholder="自动获取"
                disabled
              />
            </div>
          </Col>
          <Col :span="8">
            <div class="mb-4">
              <label class="mb-1 block font-medium">交强险到期时间</label>
              <Input
                v-model:value="prepInfo.compulsoryInsuranceExpiry"
                placeholder="自动获取"
                disabled
              />
            </div>
          </Col>
        </Row>

        <Divider />

        <!-- 设备开关 -->
        <Row :gutter="24">
          <Col :span="6">
            <div class="mb-4 flex items-center gap-3">
              <label class="font-medium">车身广告及放大字</label>
              <Switch v-model:checked="prepInfo.hasBodyAd" />
            </div>
          </Col>
          <Col :span="6">
            <div class="mb-4 flex items-center gap-3">
              <label class="font-medium">尾板</label>
              <Switch v-model:checked="prepInfo.hasTailLift" />
            </div>
          </Col>
          <Col :span="6">
            <div class="mb-4">
              <label class="mb-1 block font-medium">备胎胎纹深度</label>
              <InputNumber
                v-model:value="prepInfo.spareTireDepth"
                :min="0"
                :precision="1"
                addon-after="mm"
                placeholder="请输入"
                style="width: 100%"
              />
            </div>
          </Col>
          <Col :span="6">
            <div class="mb-4">
              <label class="mb-1 block font-medium">挂车牌号</label>
              <Input
                v-model:value="prepInfo.trailerPlateNo"
                placeholder="请输入挂车牌号"
              />
            </div>
          </Col>
        </Row>
      </Card>

      <!-- Card 3: 照片信息 -->
      <Card title="照片信息" size="small">
        <Row :gutter="24">
          <Col :span="6" v-if="prepInfo.hasBodyAd">
            <div class="mb-4">
              <label class="mb-2 block font-medium">广告照片（最多1张）</label>
              <Upload
                :file-list="bodyAdPhotos"
                list-type="picture-card"
                :max-count="1"
                :before-upload="() => false"
                @change="({ fileList }: any) => (bodyAdPhotos = fileList)"
              >
                <div v-if="bodyAdPhotos.length < 1">
                  <PlusOutlined />
                  <div class="mt-2 text-xs">上传</div>
                </div>
              </Upload>
            </div>
          </Col>
          <Col :span="6" v-if="prepInfo.hasBodyAd">
            <div class="mb-4">
              <label class="mb-2 block font-medium"
                >放大字照片（最多1张）</label
              >
              <Upload
                :file-list="enlargedTextPhotos"
                list-type="picture-card"
                :max-count="1"
                :before-upload="() => false"
                @change="
                  ({ fileList }: any) => (enlargedTextPhotos = fileList)
                "
              >
                <div v-if="enlargedTextPhotos.length < 1">
                  <PlusOutlined />
                  <div class="mt-2 text-xs">上传</div>
                </div>
              </Upload>
            </div>
          </Col>
          <Col :span="6">
            <div class="mb-4">
              <label class="mb-2 block font-medium"
                >备胎照片（最多1张）</label
              >
              <Upload
                :file-list="spareTirePhotos"
                list-type="picture-card"
                :max-count="1"
                :before-upload="() => false"
                @change="({ fileList }: any) => (spareTirePhotos = fileList)"
              >
                <div v-if="spareTirePhotos.length < 1">
                  <PlusOutlined />
                  <div class="mt-2 text-xs">上传</div>
                </div>
              </Upload>
            </div>
          </Col>
          <Col :span="6">
            <div class="mb-4">
              <label class="mb-2 block font-medium"
                >瑕疵照片（最多4张）</label
              >
              <Upload
                :file-list="defectPhotos"
                list-type="picture-card"
                :max-count="4"
                :before-upload="() => false"
                @change="({ fileList }: any) => (defectPhotos = fileList)"
              >
                <div v-if="defectPhotos.length < 4">
                  <PlusOutlined />
                  <div class="mt-2 text-xs">上传</div>
                </div>
              </Upload>
            </div>
          </Col>
        </Row>
      </Card>

      <!-- Card 4: 车辆检查 -->
      <Card title="车辆检查" size="small">
        <!-- 新版：使用验车记录组件 -->
        <template v-if="formData?.inspectionRecordId">
          <InspectionForm :record-id="formData.inspectionRecordId" :readonly="isView" />
        </template>
        <!-- 旧版：硬编码检查单（兼容旧数据） -->
        <template v-else>
          <div class="flex items-center justify-between">
            <div>
              <Button type="primary" @click="checkDrawerVisible = true">
                打开备车检查单
              </Button>
              <span class="ml-4 text-gray-500">
                共 {{ checkSummary.total }} 项，正常
                <span class="text-green-600">{{ checkSummary.normal }}</span>
                项，异常
                <span class="text-red-500">{{ checkSummary.abnormal }}</span> 项
              </span>
            </div>
          </div>
        </template>
      </Card>

      <!-- Card 5: 备注 -->
      <Card title="备注" size="small">
        <Input.TextArea
          v-model:value="prepInfo.remark"
          placeholder="请输入备注信息"
          :rows="3"
          :maxlength="500"
          show-count
        />
      </Card>
    </div>

    <!-- 检查单抽屉 -->
    <Drawer
      v-model:open="checkDrawerVisible"
      title="备车检查单"
      :width="780"
      placement="right"
    >
      <template #extra>
        <span class="text-gray-500">
          正常 {{ checkSummary.normal }}/{{ checkSummary.total }}
        </span>
      </template>
      <Table
        :columns="checkColumns"
        :data-source="checkTableData"
        :pagination="false"
        size="small"
        bordered
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'check'">
            <template v-if="record.isInput">
              <InputNumber
                v-model:value="checkData[record.key]!.depth"
                placeholder="胎纹深度"
                addon-after="mm"
                :min="0"
                :precision="1"
                size="small"
                style="width: 130px"
              />
            </template>
            <template v-else>
              <Switch
                v-model:checked="checkData[record.key]!.checked"
                checked-children="正常"
                un-checked-children="异常"
              />
            </template>
          </template>
          <template v-else-if="column.key === 'remark'">
            <Input
              v-model:value="checkData[record.key]!.remark"
              placeholder="备注"
              size="small"
            />
          </template>
        </template>
      </Table>
    </Drawer>
  </Modal>
</template>
