<template>
  <!-- 添加或修改模板抽屉 -->
  <el-drawer
    v-model="visibleProxy"
    :title="title"
    size="90%"
    append-to-body
    :close-on-click-modal="false"
    @closed="resetAll"
  >
    <el-card shadow="always" class="box-card">
      <!-- 两栏布局：基本信息和参数/预览管理 -->
      <el-row :gutter="20">
        <!-- 左栏：基本信息 -->
        <el-col :lg="8" :md="24" :sm="24" :xs="24" class="mb-4">
          <!-- 基本信息组件 -->
          <template-basic-info
            :template-form="templateForm"
            :is-saved="isSaved"
            :saving-basic-info="savingBasicInfo"
            :uploading-file="uploadingFile"
            :file-list="fileList"
            :attach-info="attachInfo"
            :is-add="isAdd"
            @save-basic-info="saveBasicInfo"
            @replace-file="handleReplaceFile"
            @download-attachment="handleDownloadAttachment"
            @file-change="handleFileChange"
            @file-exceed="handleExceed"
            @upload-file="uploadTemplateFile"
            @view-guide="guideVisible = true"
          />
        </el-col>

        <!-- 右栏：参数管理和预览测试（使用标签页） -->
        <el-col :lg="16" :md="24" :sm="24" :xs="24" class="mb-4">
          <div class="bg-white rounded-md p-4 border h-100">
            <el-tabs v-model="activeTab" type="border-card" class="h-full">
              <!-- 参数管理标签页 -->
              <el-tab-pane label="参数管理" name="params">
                <!-- 参数管理组件 -->
                <template-parameters
                  :params-list="paramsList"
                  :template-id="templateForm.templateId"
                  :att-id="templateForm.attId"
                  :parsing-params="parsingParams"
                  @update-param="updateParamDetail"
                  @reparse-params="reparseParams"
                  @view-guide="guideVisible = true"
                />
              </el-tab-pane>

              <!-- 预览测试标签页 -->
              <el-tab-pane label="预览测试" name="preview">
                <!-- 预览测试组件 -->
                <template-preview
                  :params-list="paramsList"
                  :template-id="templateForm.templateId"
                  :template-name="templateForm.templateName"
                  :test-data="testData"
                  :preview-url="previewUrl"
                  :preview-loading="previewLoading"
                  :download-loading="downloadLoading"
                  @auto-generate="autoGenerateTestData"
                  @generate-preview="generatePreview"
                  @download-document="handleDownloadDocument"
                  @update-test-data="handleUpdateTestData"
                />
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-col>
      </el-row>
    </el-card>
    <template #footer>
      <div class="dialog-footer">
        <el-button v-if="hasChanges" :loading="submitLoading" type="primary" @click="saveChanges">保存修改</el-button>
        <el-button @click="cancel">关闭</el-button>
      </div>
    </template>

    <!-- 模板指南对话框 -->
    <el-dialog
      v-model="guideVisible"
      title="模板标记语法指南"
      width="80%"
      top="5vh"
      append-to-body
    >
      <template-guide />
    </el-dialog>
  </el-drawer>
</template>

<script setup lang="ts">
import { ComponentInternalInstance, computed, getCurrentInstance, PropType, reactive, ref, watch, nextTick } from 'vue';
import {
  addTemplate,
  getTemplate,
  listTemplateParams,
  parseTemplateParams,
  previewTemplate,
  saveTemplateParams,
  updateTemplate
} from '@/api/system/template';
import { TemplateForm, TemplateParamVO, TemplateVO } from '@/api/system/template/types';
import { delAttachments, sysUploadFile } from '@/api/common/syscommon';
import TemplateBasicInfo from './components/TemplateBasicInfo.vue';
import TemplateParameters from './components/TemplateParameters.vue';
import TemplatePreview from './components/TemplatePreview.vue';
import TemplateGuide from './components/TemplateGuide.vue';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  editType: {
    type: String,
    default: 'add'
  },
  rowData: {
    type: Object as PropType<TemplateVO | null>,
    default: null
  }
});

const emit = defineEmits(['update:visible', 'save']);

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

// 可见性的双向绑定
const visibleProxy = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
});

// 根据编辑类型决定标题
const title = computed(() => (props.editType === 'add' ? '添加模板' : '修改模板'));
const isAdd = computed(() => props.editType === 'add');

// 状态变量
const activeTab = ref('params');
const savingBasicInfo = ref(false);
const uploadingFile = ref(false);
const submitLoading = ref(false);
const parsingParams = ref(false);
const previewLoading = ref(false);
const downloadLoading = ref(false);
const fileList = ref<any[]>([]);
const paramsList = ref<TemplateParamVO[]>([]);
const previewUrl = ref<string>('');
const testData = reactive<Record<string, any>>({});
const isSaved = ref(false); // 标记基本信息是否已保存
const hasChanges = ref(false); // 标记是否有未保存的修改
const guideVisible = ref(false); // 模板指南对话框可见性

// 附件信息
const attachInfo = reactive({
  fileName: '',
  originalName: '',
  fileSuffix: '',
  fileSize: 0,
  url: '',
  service: ''
});

// 表单数据
const initTemplateForm: TemplateForm = {
  templateId: undefined,
  templateCode: '',
  templateName: '',
  templateType: 'WAGE',
  attId: undefined,
  status: '0',
  remark: ''
};

const templateForm = reactive<TemplateForm>({ ...initTemplateForm });

// 自动生成测试数据 - 修复后的方法
const autoGenerateTestData = (generatedData: Record<string, any>) => {
  if (!paramsList.value.length) {
    proxy?.$modal.msgWarning('请先解析模板参数');
    return;
  }


  // 清空现有测试数据
  Object.keys(testData).forEach(key => {
    delete testData[key];
  });

  // 批量更新测试数据
  Object.keys(generatedData).forEach(key => {
    testData[key] = generatedData[key];
  });

  // 确保界面更新
  nextTick(() => {
  });

  hasChanges.value = true;
};

// 处理测试数据更新
const handleUpdateTestData = (paramName: string, value: any) => {
  testData[paramName] = value;
  hasChanges.value = true;

  // 添加调试信息
};

// 监听抽屉可见性、编辑类型和行数据变化
watch(
  [() => props.visible, () => props.editType, () => props.rowData],
  async ([visible, type, data]) => {
    if (visible) {
      resetForm();
      hasChanges.value = false;

      if (type === 'edit' && data) {
        // 修改操作
        try {
          const res = await getTemplate(data.templateId);
          Object.assign(templateForm, res.data);
          // 设置附件信息
          if (res.data.attId) {
            // 更新附件信息显示
            attachInfo.fileName = res.data.fileName || res.data.originalName || '未命名文件';
            attachInfo.originalName = res.data.originalName || '';
            attachInfo.fileSuffix = res.data.fileSuffix || '';
            attachInfo.fileSize = res.data.fileSize || 0;
            attachInfo.url = res.data.url || '';
            attachInfo.service = res.data.service || '';

            // 确保模板表单中的attId被正确设置
            templateForm.attId = res.data.attId;

            // 添加此段代码 - 设置fileList用于显示已上传文件
            fileList.value = [{
              name: attachInfo.originalName || attachInfo.fileName,
              url: attachInfo.url,
              status: 'success',
              uid: templateForm.attId.toString()
            }];
          }

          // 标记为已保存
          isSaved.value = true;

          // 加载参数
          await loadTemplateParams();
        } catch (error) {
          proxy?.$modal.msgError('获取模板详情失败');
        }
      }
    }
  },
  { immediate: true }
);

// 保存基本信息
const saveBasicInfo = async () => {
  savingBasicInfo.value = true;
  try {
    let result;
    if (isAdd.value) {
      result = await addTemplate(templateForm);
      if (result.code === 200) {
        templateForm.templateId = result.data;
        isSaved.value = true;
        proxy?.$modal.msgSuccess('基本信息保存成功，请上传模板文件');
      }
    } else {
      result = await updateTemplate(templateForm);
      if (result.code === 200) {
        isSaved.value = true;
        proxy?.$modal.msgSuccess('基本信息保存成功');
      }
    }
  } catch (error) {
    proxy?.$modal.msgError('保存基本信息失败');
  } finally {
    savingBasicInfo.value = false;
  }
};

// 下载附件
const handleDownloadAttachment = () => {
  if (!templateForm.attId) {
    proxy?.$modal.msgWarning('没有可下载的附件');
    return;
  }

  try {
    // 使用统一的下载方法
    // proxy?.$download.attach('/resource/buscommon/download', templateForm.attId, AttachBusCodeConstant.SYS_TEMPLATE_UPLOAD.code);
  } catch (error) {
    // proxy?.$modal.msgError('下载失败');
  }
};

// 下载预览文件
const handleDownloadDocument = async () => {
  if (!previewUrl.value) {
    proxy?.$modal.msgWarning('请先生成预览');
    return;
  }

  try {
    downloadLoading.value = true;

    // 创建一个链接并模拟点击下载
    const link = document.createElement('a');
    link.href = previewUrl.value;
    link.download = `${templateForm.templateName || 'preview'}_${new Date().getTime()}.pdf`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    proxy?.$modal.msgSuccess('预览文件已下载');
  } catch (error) {
    proxy?.$modal.msgError('下载失败');
  } finally {
    downloadLoading.value = false;
  }
};

// 更换文件
const handleReplaceFile = async () => {
  // 如果存在旧附件，先删除它
  if (templateForm.attId) {
    try {
      // await delAttachments(templateForm.attId, AttachBusCodeConstant.SYS_TEMPLATE_UPLOAD.code);
    } catch (error) {
      // proxy?.$modal.msgWarning('删除旧附件失败，但您仍可以上传新附件');
    }
  }
  // 清空原有附件信息
  Object.assign(attachInfo, {
    fileName: '',
    originalName: '',
    fileSuffix: '',
    fileSize: 0,
    url: '',
    service: ''
  });
  // 清空参数列表
  paramsList.value = [];
  // 清空预览URL
  if (previewUrl.value) {
    URL.revokeObjectURL(previewUrl.value);
    previewUrl.value = '';
  }
  // 清空测试数据
  Object.keys(testData).forEach(key => {
    delete testData[key];
  });
  // 清空文件列表
  fileList.value = [];
  // 清空附件ID
  templateForm.attId = undefined;
  // 标记为有修改
  hasChanges.value = true;
};

// 加载模板参数
const loadTemplateParams = async () => {
  if (!templateForm.templateId) return;

  try {
    parsingParams.value = true;
    const res = await listTemplateParams(templateForm.templateId);
    paramsList.value = res.data || [];

    // 初始化测试数据
    initTestData();
  } catch (error) {
    proxy?.$modal.msgError('获取模板参数失败');
  } finally {
    parsingParams.value = false;
  }
};

// 初始化测试数据 - 增强版本
const initTestData = () => {
  // 清空现有测试数据
  Object.keys(testData).forEach(key => {
    delete testData[key];
  });

  // 分别处理不同类型的参数
  const rootParams = paramsList.value.filter(p => !p.parentId);
  const containerParams = rootParams.filter(p => isContainerType(p.paramType));
  const normalParams = rootParams.filter(p => !isContainerType(p.paramType));

  // 初始化普通参数
  normalParams.forEach(param => {
    testData[param.paramName] = param.defaultValue || '';
  });

  // 初始化容器参数
  containerParams.forEach(param => {
    testData[param.paramName] = [];
  });

};

// 上传模板文件
const uploadTemplateFile = async () => {
  if (fileList.value.length === 0) {
    proxy?.$modal.msgError('请选择模板文件');
    return;
  }

  uploadingFile.value = true;
  try {
    // 再次检查，确保没有旧附件（以防出现附件ID与前端状态不一致的情况）
    if (templateForm.attId) {
      try {
        // await delAttachments(templateForm.attId, AttachBusCodeConstant.SYS_TEMPLATE_UPLOAD.code);
      } catch (error) {
      }
    }
    // 使用通用附件上传API
    const file = fileList.value[0].raw;
    const formData = new FormData();
    formData.append('files', file);
    formData.append('busDataType', 'TEMPLATE_FILE');
    formData.append('uid', `template_${Date.now()}`);
    formData.append('markedUpdate', 'false');
    formData.append('markedAdd', 'true');
    // formData.append('busCode', AttachBusCodeConstant.SYS_TEMPLATE_UPLOAD.code);
    formData.append('dataId', templateForm.templateId?.toString() || '0');
    const res = await sysUploadFile(formData);
    if (res.code === 200 && res.data && res.data.length > 0) {
      // 设置模板attId
      const fileInfo = res.data[0];
      templateForm.attId = fileInfo.attId;
      // 更新附件信息展示
      attachInfo.fileName = fileInfo.fileName || '';
      attachInfo.originalName = fileInfo.originalName || '';
      attachInfo.fileSize = fileInfo.fileSize || 0;
      // 立即更新数据库中的附件ID
      if (templateForm.templateId) {
        try {
          // 使用当前完整的templateForm对象更新数据库
          const updateRes = await updateTemplate(templateForm);
          if (updateRes.code === 200) {
            proxy?.$modal.msgSuccess('文件上传成功并关联到模板');
          } else {
            proxy?.$modal.msgWarning('文件上传成功，但关联到模板失败，请保存修改');
          }
        } catch (updateError) {
          proxy?.$modal.msgWarning('文件上传成功，但关联到模板失败，请保存修改');
        }
      }
      // 标记为有修改
      hasChanges.value = true;
      proxy?.$modal.msgSuccess('文件上传成功，请点击"解析参数"');
      // 自动解析参数
      await reparseParams();
    } else {
      proxy?.$modal.msgError('上传文件失败');
    }
  } catch (error) {
    proxy?.$modal.msgError('上传文件失败');
  } finally {
    uploadingFile.value = false;
  }
};

// 解析参数
const reparseParams = async () => {
  if (!templateForm.templateId) {
    proxy?.$modal.msgWarning('请先保存模板');
    return;
  }

  if (!templateForm.attId) {
    proxy?.$modal.msgWarning('请先上传模板文件');
    return;
  }

  try {
    parsingParams.value = true;
    const res = await parseTemplateParams(templateForm.templateId);
    paramsList.value = res.data || [];

    // 初始化测试数据
    initTestData();

    proxy?.$modal.msgSuccess('解析参数成功');

    // 标记为有修改
    hasChanges.value = true;
  } catch (error) {
    proxy?.$modal.msgError('解析参数失败');
  } finally {
    parsingParams.value = false;
  }
};

// 生成预览 - 增强版本
const generatePreview = async () => {
  if (!templateForm.templateId) {
    proxy?.$modal.msgWarning('请先保存模板');
    return;
  }

  if (!paramsList.value.length) {
    proxy?.$modal.msgWarning('请先解析模板参数');
    return;
  }

  // 验证必填参数
  const requiredParams = paramsList.value.filter(p => p.isRequired === '1');
  for (const param of requiredParams) {
    const value = testData[param.paramName];

    // 对于容器参数，检查是否有数据
    if (isContainerType(param.paramType)) {
      if (!Array.isArray(value) || value.length === 0) {
        proxy?.$modal.msgWarning(`参数 ${param.paramDesc || param.paramName} 为必填项，请添加数据`);
        return;
      }
    } else {
      // 对于普通参数，检查是否为空
      if (!value) {
        proxy?.$modal.msgWarning(`参数 ${param.paramDesc || param.paramName} 为必填项`);
        return;
      }
    }
  }

  try {
    previewLoading.value = true;

    // 处理测试数据，确保结构正确
    const processedData = processTestDataForPreview(testData);


    // 调用预览API
    const res = await previewTemplate(templateForm.templateId, processedData);

    // 创建Blob URL
    const blob = new Blob([res], { type: 'application/pdf' });

    // 如果已存在预览URL，先释放它
    if (previewUrl.value) {
      URL.revokeObjectURL(previewUrl.value);
    }

    previewUrl.value = URL.createObjectURL(blob);
    proxy?.$modal.msgSuccess('预览生成成功');

    // 自动切换到预览标签页
    activeTab.value = 'preview';
  } catch (error) {
    proxy?.$modal.msgError('生成预览失败');
  } finally {
    previewLoading.value = false;
  }
};

// 处理测试数据以适配后端要求
const processTestDataForPreview = (rawData: Record<string, any>): Record<string, any> => {
  const processedData = { ...rawData };

  // 处理每个参数
  paramsList.value.forEach(param => {
    const paramName = param.paramName;
    const paramType = param.paramType;
    const value = processedData[paramName];

    if (paramType === 'conditionalList' || paramType === 'list') {
      // 确保列表类型的数据是数组
      if (typeof value === 'string') {
        try {
          processedData[paramName] = JSON.parse(value);
        } catch (e) {
          processedData[paramName] = [];
        }
      } else if (!Array.isArray(value)) {
        processedData[paramName] = [];
      }
    }
  });

  return processedData;
};

// 判断是否为容器类型
const isContainerType = (paramType: string): boolean => {
  const containerTypes = ['list', 'conditionalList', 'nestedList', 'table'];
  return containerTypes.includes(paramType);
};

// 更新参数详情
const updateParamDetail = (field: string, param: TemplateParamVO) => {
  if (!param) return;

  // 如果更新的是默认值，同时更新测试数据
  if (field === 'defaultValue' && param.defaultValue) {
    testData[param.paramName] = param.defaultValue;
  }

  // 标记为有修改
  hasChanges.value = true;
};

// 文件上传相关方法
const handleFileChange = (file: any) => {
  fileList.value = [file];
};

const handleExceed = () => {
  proxy?.$modal.msgWarning('只能上传一个文件');
};

// 保存所有修改
const saveChanges = async () => {
  if (!hasChanges.value) return;

  submitLoading.value = true;
  try {
    // 1. 保存模板基本信息
    await updateTemplate(templateForm);

    // 2. 保存模板参数
    if (paramsList.value.length > 0) {
      await saveTemplateParams(paramsList.value);
    }

    proxy?.$modal.msgSuccess('保存成功');
    hasChanges.value = false;
    emit('save');
  } catch (error) {
    proxy?.$modal.msgError('保存失败');
  } finally {
    submitLoading.value = false;
  }
};

// 表单重置
const resetForm = () => {
  Object.assign(templateForm, initTemplateForm);
  fileList.value = [];
  isSaved.value = false;

  // 重置附件信息
  Object.assign(attachInfo, {
    fileName: '',
    originalName: '',
    fileSuffix: '',
    fileSize: 0,
    url: '',
    service: ''
  });
};

// 清理所有状态
const resetAll = () => {
  resetForm();
  paramsList.value = [];

  // 清除预览URL
  if (previewUrl.value) {
    URL.revokeObjectURL(previewUrl.value);
    previewUrl.value = '';
  }

  // 清除测试数据
  Object.keys(testData).forEach(key => {
    delete testData[key];
  });

  hasChanges.value = false;
  activeTab.value = 'params'; // 重置为默认标签页
};

// 取消按钮
const cancel = () => {
  if (hasChanges.value) {
    proxy?.$modal.confirm('有未保存的修改，确定要关闭吗？').then(() => {
      visibleProxy.value = false;
      emit('submit');
    }).catch(() => {
    });
  } else {
    visibleProxy.value = false;
    emit('submit');
  }
};
</script>

<style scoped>
/* 设置元素高度 */
.h-100 {
  height: 100%;
}

/* 标签页样式 */
:deep(.el-tabs) {
  height: 100%;
  display: flex;
}

:deep(.el-tabs__content) {
  flex: 1;
  overflow: auto;
  padding: 16px;
}

:deep(.el-tabs__header) {
  margin-bottom: 0;
}

:deep(.el-tab-pane) {
  height: 100%;
}

/* 抽屉内容最小高度 */
:deep(.el-drawer__body) {
  min-height: 600px;
  display: flex;
  flex-direction: column;
}

/* 卡片占满除了底部以外的空间 */
:deep(.el-card.box-card) {
  flex: 1;
  margin-bottom: 10px;
  overflow: auto;
}

/* 让标签页内容区域占满可用空间 */
.h-full {
  height: 100%;
}
</style>
