<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 isUpdateRef = ref<boolean>(false);

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

// 初始化表单
const [Form, formApi] = useVbenForm({
  showDefaultActions: false,
  schema: drawerFormSchema(),
});

// 初始化抽屉
const [Drawer, drawerApi] = useVbenDrawer({
  async onOpenChange(isOpen) {
    if (!isOpen) {
      return;
    }
    await handleDrawerOpen();
  },

  async onConfirm() {
    await handleFormSubmit();
  },

  onClosed() {
    formApi.resetForm();
  },
});

/**
 * 处理抽屉打开逻辑
 */
async function handleDrawerOpen() {
  try {
    drawerApi.drawerLoading(true);
    const { id, isUpdate } = drawerApi.getData();
    isUpdateRef.value = isUpdate;

    // 处理编辑模式的数据回显
    if (isUpdate && id) {
      await loadIdPhotoDetail(id);
    }
  } catch (error) {
    console.error('打开抽屉失败:', error);
  } finally {
    drawerApi.drawerLoading(false);
  }
}

/**
 * 加载证照详情数据
 * @param id 证照ID
 */
async function loadIdPhotoDetail(id: number | string) {
  try {
    const res = await getIdPhotoDetail(id);

    // 确保从正确的响应结构中获取数据
    const detailData = res?.data || res;

    // 构建表单数据
    const formData = buildFormData(detailData);

    // 设置表单值
    await formApi.setValues(formData);
  } catch (error) {
    console.error('获取证照详情失败:', error);
  }
}

/**
 * 构建表单数据
 * @param detailData 详情数据
 * @returns 格式化后的表单数据
 */
function buildFormData(detailData: any) {
  // 处理长期有效的布尔值转换
  const isLongTerm =
    detailData.isLongTerm === '1' ||
    detailData.isLongTerm === 1 ||
    detailData.isLongTerm === true;

  detailData.statusCode = (detailData.statusCode || 0).toString();

  return {
    ...detailData,
    isLongTerm,
    // 保持 certificateScanPath 为字符串格式，逗号隔开
    certificateScanPath: detailData.certificateScanPath || '',
    // 处理 certificateScanPathUrl 字段，确保为数组格式
    certificateScanPathUrl: formatCertificateScanPathUrl(detailData),
  };
}

/**
 * 格式化 certificateScanPathUrl 字段
 * @param detailData 详情数据
 * @returns 格式化后的数组
 */
function formatCertificateScanPathUrl(detailData: any) {
  if (!detailData.certificateScanPathUrl) {
    return [];
  }

  // 处理数组格式
  if (Array.isArray(detailData.certificateScanPathUrl)) {
    return detailData.certificateScanPathUrl.map(
      (url: string, index: number) => ({
        name:
          detailData.certificateScanPath?.split(',')[index] ||
          `文件${index + 1}`,
        url,
        status: 'success',
        uid: Date.now() + index,
      }),
    );
  }

  // 处理字符串格式
  if (typeof detailData.certificateScanPathUrl === 'string') {
    return [
      {
        name: detailData.certificateScanPathUrl.split('/').pop() || '未知文件',
        url: detailData.certificateScanPathUrl,
        status: 'success',
        uid: Date.now(),
      },
    ];
  }

  return [];
}

/**
 * 处理表单提交
 */
async function handleFormSubmit() {
  try {
    // 验证表单
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }

    // 获取表单数据
    const data = await formApi.getValues();
    console.log('表单数据:', data);

    // 处理数据
    const processedData = processFormData(data);

    // 构建提交数据
    const submitData = buildSubmitData(processedData);
    console.log('提交数据:', submitData);

    // 提交请求
    await (isUpdateRef.value
      ? updateIdPhoto(submitData)
      : addIdPhoto(submitData));

    // 触发重载事件并关闭抽屉
    emit('reload');
    drawerApi.close();
  } catch (error) {
    console.error('保存证照信息失败:', error);
  }
}

/**
 * 处理表单数据
 * @param data 表单数据
 * @returns 处理后的数据
 */
function processFormData(data: any) {
  // 处理长期有效的逻辑
  if (data.isLongTerm) {
    data.validDate = null;
  }

  // 转换长期有效字段格式
  data.isLongTerm = data.isLongTerm ? '1' : '0';

  // 设置默认站点ID
  data.stationId = 1;

  // 处理证书扫描件路径
  data.certificateScanPath = processCertificateScanPath(data);

  return data;
}

/**
 * 处理证书扫描件路径
 * @param data 表单数据
 * @returns 处理后的路径字符串
 */
function processCertificateScanPath(data: any) {
  // 直接使用 certificateScanPath 字段，上传时已设置为逗号分隔的 fileName 格式
  let certificateScanPath = data.certificateScanPath || '';

  // 如果有 certificateScanPathUrl，优先使用其中的 name 构建 certificateScanPath
  if (
    Array.isArray(data.certificateScanPathUrl) &&
    data.certificateScanPathUrl.length > 0
  ) {
    // 检查是否有上传响应数据
    if (data.certificateScanPathUrl[0].response) {
      certificateScanPath = data.certificateScanPathUrl
        .map((item: any) => item.response.data.fileName)
        .join(',');
    } else if (data.certificateScanPathUrl[0].name) {
      // 检查是否有 name 属性
      certificateScanPath = data.certificateScanPathUrl
        .map((item: any) => item.name)
        .join(',');
    }
  }

  return certificateScanPath;
}

/**
 * 构建提交数据
 * @param data 处理后的数据
 * @returns 提交数据对象
 */
function buildSubmitData(data: any) {
  return {
    // 基础字段
    id: data.id,
    licenseNameCode: data.licenseNameCode || data.certificateName,
    licenseRuleId: data.licenseRuleId || data.licenseRule,
    licenseName: data.licenseName || data.licenseNameCode,
    orgTypeCode: data.orgTypeCode || data.organizationType,
    issuingAuthority: data.issuingAuthority,
    issueDate: data.issueDate,
    certificateNumber: data.certificateNumber || data.certificateNo,
    storageLocationCode: data.storageLocationCode || data.storageLocation,
    renewalRequirements:
      data.renewalRequirements || data.replacementRequirements,
    statusCode: data.statusCode || data.status,
    validDate: data.validDate,
    isLongTerm: data.isLongTerm,
    stationId: data.stationId,
    // 只传 certificateScanPath，字符串逗号隔开
    certificateScanPath: data.certificateScanPath || '',
  };
}

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

<template>
  <Drawer :title="isUpdateRef ? '编辑证照' : '新增证照'">
    <Form />
  </Drawer>
</template>
