<script setup lang="ts">
import type { UploadUserFile } from 'element-plus';

import { ref } from 'vue';

import { useVbenDrawer, useVbenForm } from '@vben/common-ui';

import { Plus } from '@element-plus/icons-vue';
import { ElIcon, ElUpload } from 'element-plus';

import { uploadApi } from '#/api/core/upload';
import { addCar, getCarDetail, updateCar } from '#/api/oilstation/car/car';

import { drawerFormSchema } from './car-data';

const emit = defineEmits<{
  reload: [];
}>();

// 图片上传引用
const driverLicenseUrl = ref<string>('');
const vehicleLicenseUrl = ref<string>('');
const trafficRouteBookUrl = ref<string>('');
const vehicleFullViewUrl = ref<string>('');

// 自定义上传方法
const handleUpload = async (options: any, fieldName: string) => {
  try {
    const res = await uploadApi(options.file);
    const responseData = { url: res.url };
    // 根据字段名设置对应的URL
    switch (fieldName) {
      case 'driverLicensePath': {
        driverLicenseUrl.value = res.url;
        break;
      }
      case 'trafficRouteBookPath': {
        trafficRouteBookUrl.value = res.url;
        break;
      }
      case 'vehicleFullViewPath': {
        vehicleFullViewUrl.value = res.url;
        break;
      }
      case 'vehicleLicensePath': {
        vehicleLicenseUrl.value = res.url;
        break;
      }
    }
    options.onSuccess(responseData);
  } catch (error) {
    console.error('上传失败:', error);
    options.onError(error);
  }
};

// 删除文件处理
const handleRemove = (
  uploadFile: UploadUserFile,
  uploadFiles: UploadUserFile[],
) => {
  return true;
};

// 预览文件处理
const handlePreview = (uploadFile: UploadUserFile) => {
  console.log('预览文件:', uploadFile);
};

const [Form, formApi] = useVbenForm({
  showDefaultActions: false,
  schema: drawerFormSchema(),
});

const isUpdateRef = ref<boolean>(false);

const [Drawer, drawerApi] = useVbenDrawer({
  async onOpenChange(isOpen) {
    if (!isOpen) {
      return;
    }
    try {
      drawerApi.drawerLoading(true);
      const { id, isUpdate } = drawerApi.getData();
      isUpdateRef.value = isUpdate;

      // 重置上传URL
      driverLicenseUrl.value = '';
      vehicleLicenseUrl.value = '';
      trafficRouteBookUrl.value = '';
      vehicleFullViewUrl.value = '';

      if (isUpdate && id) {
        const res = await getCarDetail(id);
        const detailData = res?.data || res;

        // 设置上传文件URL
        driverLicenseUrl.value = detailData.driverLicensePath || '';
        vehicleLicenseUrl.value = detailData.vehicleLicensePath || '';
        trafficRouteBookUrl.value = detailData.trafficRouteBookPath || '';
        vehicleFullViewUrl.value = detailData.vehicleFullViewPath || '';

        // 处理表单数据，转换文件列表
        const formData = {
          ...detailData,
          driverLicensePath: detailData.driverLicensePath
            ? [
                {
                  name:
                    detailData.driverLicensePath.split('/').pop() ||
                    '驾驶证图片',
                  url: detailData.driverLicensePath,
                  status: 'success',
                  uid: Date.now(),
                },
              ]
            : [],
          vehicleLicensePath: detailData.vehicleLicensePath
            ? [
                {
                  name:
                    detailData.vehicleLicensePath.split('/').pop() ||
                    '行驶证图片',
                  url: detailData.vehicleLicensePath,
                  status: 'success',
                  uid: Date.now() + 1,
                },
              ]
            : [],
          trafficRouteBookPath: detailData.trafficRouteBookPath
            ? [
                {
                  name:
                    detailData.trafficRouteBookPath.split('/').pop() ||
                    '交通路书图片',
                  url: detailData.trafficRouteBookPath,
                  status: 'success',
                  uid: Date.now() + 2,
                },
              ]
            : [],
          vehicleFullViewPath: detailData.vehicleFullViewPath
            ? [
                {
                  name:
                    detailData.vehicleFullViewPath.split('/').pop() ||
                    '车辆全貌图片',
                  url: detailData.vehicleFullViewPath,
                  status: 'success',
                  uid: Date.now() + 3,
                },
              ]
            : [],
        };

        await formApi.setValues(formData);
      }
    } catch (error) {
      console.error('获取车辆详情失败:', error);
    } finally {
      drawerApi.drawerLoading(false);
    }
  },

  async onConfirm() {
    try {
      this.confirmLoading = true;
      const { valid } = await formApi.validate();
      if (!valid) {
        return;
      }

      const data = await formApi.getValues();
      data.stationId = 1; // 假设默认油站ID

      // 准备提交数据
      const submitData = {
        ...data,
        driverLicensePath: driverLicenseUrl.value,
        vehicleLicensePath: vehicleLicenseUrl.value,
        trafficRouteBookPath: trafficRouteBookUrl.value,
        vehicleFullViewPath: vehicleFullViewUrl.value,
      };

      await (isUpdateRef.value ? updateCar(submitData) : addCar(submitData));
      emit('reload');
      drawerApi.close();
    } catch (error) {
      console.error('保存车辆信息失败:', error);
    } finally {
      this.confirmLoading = false;
    }
  },

  onClosed() {
    formApi.resetForm();
  },
});
</script>

<template>
  <Drawer :title="isUpdateRef ? '编辑车辆信息' : '新增车辆信息'">
    <Form>
      <!-- 驾驶证图片上传 -->
      <template #driverLicensePath="scope">
        <ElUpload
          v-model:file-list="scope.modelValue"
          action="#"
          accept=".jpg,.jpeg,.png"
          list-type="picture-card"
          :auto-upload="true"
          :http-request="
            (options) => handleUpload(options, 'driverLicensePath')
          "
          :on-remove="handleRemove"
          :on-preview="handlePreview"
        >
          <div>
            <ElIcon class="el-upload__icon">
              <Plus size="30" />
            </ElIcon>
          </div>
        </ElUpload>
      </template>
      <!-- 行驶证图片上传 -->
      <template #vehicleLicensePath="scope">
        <ElUpload
          v-model:file-list="scope.modelValue"
          action="#"
          accept=".jpg,.jpeg,.png"
          list-type="picture-card"
          :auto-upload="true"
          :http-request="
            (options) => handleUpload(options, 'vehicleLicensePath')
          "
          :on-remove="handleRemove"
          :on-preview="handlePreview"
        >
          <div>
            <ElIcon class="el-upload__icon">
              <Plus size="30" />
            </ElIcon>
          </div>
        </ElUpload>
      </template>
      <!-- 交通路书图片上传 -->
      <template #trafficRouteBookPath="scope">
        <ElUpload
          v-model:file-list="scope.modelValue"
          action="#"
          accept=".jpg,.jpeg,.png"
          list-type="picture-card"
          :auto-upload="true"
          :http-request="
            (options) => handleUpload(options, 'trafficRouteBookPath')
          "
          :on-remove="handleRemove"
          :on-preview="handlePreview"
        >
          <div>
            <ElIcon class="el-upload__icon">
              <Plus size="30" />
            </ElIcon>
          </div>
        </ElUpload>
      </template>
      <!-- 车辆全貌图片上传 -->
      <template #vehicleFullViewPath="scope">
        <ElUpload
          v-model:file-list="scope.modelValue"
          action="#"
          accept=".jpg,.jpeg,.png"
          list-type="picture-card"
          :auto-upload="true"
          :http-request="
            (options) => handleUpload(options, 'vehicleFullViewPath')
          "
          :on-remove="handleRemove"
          :on-preview="handlePreview"
        >
          <div>
            <ElIcon class="el-upload__icon">
              <Plus size="30" />
            </ElIcon>
          </div>
        </ElUpload>
      </template>
      <!-- 描述信息 -->
      <template #desc>
        <span class="text-sm text-gray-400">
          摩托车必须上传以上4张照片，电动车必须上传交通路书和车辆全貌
        </span>
      </template>
    </Form>
  </Drawer>
</template>
