<script setup lang="ts">
import { onMounted, ref } from 'vue';

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

import {
  addIdPhoto,
  getIdPhotoDetail,
  updateIdPhoto,
} from '#/api/oilstation/idphoto/idphoto';
import { getDictOptions } from '#/utils/dict';

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

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

// 字典标识常量
const DICT_KEYS = {
  // 驾照字典标识
  ID_PAPERS_NAME: 'id_papers_name',
  // 机构字典标识
  ID_PAPERS_ORGANIZATION: 'id_papers_organization',
  // 存放处字典标识
  ID_PAPERS_STORAGE: 'id_papers_storage',
  // 状态字典标识
  STATUS: 'status',
};

const uploadUrlRef = ref<string>('');
// 获取字典选项函数
const getDictOptionsByKey = (key: string) => getDictOptions(key);

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

// 获取初始字典数据，确保表单加载时有默认选项
onMounted(() => {
  // 字典数据会在表单schema中动态获取，这里只是为了确保组件挂载时有初始数据
  getDictOptionsByKey(DICT_KEYS.ID_PAPERS_NAME);
  getDictOptionsByKey(DICT_KEYS.ID_PAPERS_ORGANIZATION);
  getDictOptionsByKey(DICT_KEYS.ID_PAPERS_STORAGE);
  getDictOptionsByKey(DICT_KEYS.STATUS);
});

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;
      if (isUpdate && id) {
        const res = await getIdPhotoDetail(id);
        console.log('获取证照详情数据:', res);
        // 确保从正确的响应结构中获取数据
        const detailData = res?.data || res;

        uploadUrlRef.value = detailData.certificateScanPath || '';
        // 处理长期有效的布尔值转换并确保字段名映射正确
        const formData = {
          ...detailData,
          isLongTerm:
            detailData.isLongTerm === '1' ||
            detailData.isLongTerm === 1 ||
            detailData.isLongTerm === true,
          // 文件列表格式转换，确保符合Upload组件要求
          certificateScanPath: detailData.certificateScanPath
            ? typeof detailData.certificateScanPath === 'string' &&
              detailData.certificateScanPath.includes(',')
              ? // 如果是逗号分隔的多个URL字符串
                detailData.certificateScanPath
                  .split(',')
                  .map((url: string, index: number) => ({
                    name: url.split('/').pop() || `文件${index + 1}`,
                    url,
                    status: 'success',
                    uid: Date.now() + index,
                  }))
              : // 单个URL字符串
                typeof detailData.certificateScanPath === 'string'
                ? [
                    {
                      name:
                        detailData.certificateScanPath.split('/').pop() ||
                        '未知文件',
                      url: detailData.certificateScanPath,
                      status: 'success',
                      uid: Date.now(),
                    },
                  ]
                : // 已经是数组格式
                  Array.isArray(detailData.certificateScanPath)
                  ? detailData.certificateScanPath.map(
                      (item: any, index: number) => ({
                        name:
                          (item.url || item).split('/').pop() ||
                          `文件${index + 1}`,
                        url: item.url || item,
                        status: 'success',
                        uid: Date.now() + index,
                      }),
                    )
                  : []
            : [],
        };
        // Object.assign(drawerFormRef, formData);
        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();
      // 处理长期有效的逻辑
      if (data.isLongTerm) {
        data.validDate = null;
      }
      data.isLongTerm = data.isLongTerm ? '1' : '0';
      data.stationId = 1;
      // 确保使用正确的字段名提交数据
      console.log(data.certificateScanPath);
      const submitData = {
        ...data,
        licenseNameCode: data.licenseNameCode || data.certificateName,
        orgTypeCode: data.orgTypeCode || data.organizationType,
        certificateNumber: data.certificateNumber || data.certificateNo,
        storageLocationCode: data.storageLocationCode || data.storageLocation,
        renewalRequirements:
          data.renewalRequirements || data.replacementRequirements,
        // url 数组转换为逗号分隔的字符串
        statusCode: data.statusCode || data.status,
      };

      console.log('提交数据:', submitData);
      await (isUpdateRef.value
        ? updateIdPhoto(submitData)
        : addIdPhoto(submitData));
      emit('reload');
      drawerApi.close();
    } catch (error) {
      console.error('保存证照信息失败:', error);
    } finally {
      this.confirmLoading = false;
    }
  },

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

<template>
  <Drawer :title="isUpdateRef ? '编辑证照' : '新增证照'">
    <Form>
      <!-- 自定义Upload组件插槽 -->
      <!-- <template #certificateScanPath="scope">
        <ElUpload
          v-model:file-list="scope.modelValue"
          action="#"
          multiple
          accept=".jpg,.jpeg,.png,.pdf"
          list-type="picture-card"
          show-file-list
          :auto-upload="true"
          :drag="false"
          :http-request="handleUpload"
          :on-remove="handleRemove"
          :on-preview="handlePreview"
        >
          <div>
            <ElIcon class="el-upload__icon">
              <Plus size="30" />
            </ElIcon>
          </div>
        </ElUpload>
      </template> -->
    </Form>
  </Drawer>
</template>
