<template>
  <div class="bg-white rounded-md p-4 border h-100">
    <h3 class="text-md font-medium mb-4">基本信息</h3>
    <el-form
      ref="templateFormRef"
      :model="templateForm"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="模板名称" prop="templateName">
        <el-input
          v-model="templateForm.templateName"
          placeholder="请输入模板名称"
          :disabled="isSaved"
        />
      </el-form-item>
      <el-form-item label="模板编码" prop="templateCode">
        <el-input
          v-model="templateForm.templateCode"
          placeholder="请输入模板编码"
          :disabled="isSaved"
        />
      </el-form-item>
      <el-form-item label="模板类型" prop="templateType">
        <el-select
          v-model="templateForm.templateType"
          placeholder="请选择模板类型"
          style="width: 100%"
          :disabled="isSaved"
        >
          <el-option
            v-for="item in templateTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="templateForm.status" :disabled="isSaved">
          <el-radio
            v-for="dict in sys_normal_disable"
            :key="dict.value"
            :label="dict.value"
          >{{ dict.label }}</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="templateForm.remark"
          type="textarea"
          placeholder="请输入内容"
          :disabled="isSaved"
        />
      </el-form-item>

      <!-- 保存基本信息按钮 -->
      <el-form-item v-if="!isSaved">
        <el-button
          type="primary"
          :loading="savingBasicInfo"
          @click="handleSaveBasicInfo"
        >保存基本信息</el-button>
      </el-form-item>
    </el-form>

    <!-- 附件上传区域 - 仅在基本信息保存后显示 -->
    <div v-if="isSaved" class="mt-6 border-t pt-4">
      <h4 class="text-md font-medium mb-4">模板文件</h4>

      <!-- 已有附件信息显示 -->
      <div v-if="templateForm.attId" class="mb-4">
        <div class="flex items-center">
          <el-icon class="mr-2"><Document /></el-icon>
          <span>{{ attachInfo.originalName || attachInfo.fileName || '未知文件名' }}</span>
          <el-tag class="ml-2" type="info" size="small" v-if="attachInfo.fileSize">
            {{ formatFileSize(attachInfo.fileSize) }}
          </el-tag>
        </div>
        <div class="mt-2">
          <el-button type="warning" size="small" @click="handleReplaceFile">更换文件</el-button>
          <el-button type="primary" size="small" @click="handleDownloadAttachment">下载文件</el-button>
        </div>
      </div>

      <!-- 未上传附件时显示上传按钮 -->
      <div v-else>
        <el-upload
          ref="uploadRef"
          :action="''"
          :auto-upload="false"
          :limit="1"
          :on-change="handleFileChange"
          :on-exceed="handleFileExceed"
          :file-list="fileList"
          accept=".docx,.doc"
        >
          <el-button type="primary">选择文件</el-button>
          <template #tip>
            <div class="mt-2 text-gray-400">只能上传Word文档(docx/doc)，且大小不超过10MB</div>
          </template>
        </el-upload>

        <div class="mt-4" v-if="fileList.length > 0">
          <el-button
            type="success"
            :loading="uploadingFile"
            @click="handleUploadFile"
          >上传文件</el-button>
        </div>
      </div>

      <!-- 模板参考链接 -->
      <div class="mt-4 text-gray-600">
        <p>模板参考:</p>
        <div class="flex space-x-2 mt-1">
          <el-link type="primary" @click="handleViewGuide">查看模板标记语法指南</el-link>
          <el-link type="success" @click="handleDownloadSample">下载示例模板</el-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { Document } from '@element-plus/icons-vue';
import { TemplateForm } from '@/api/system/template/types';

const props = defineProps({
  templateForm: {
    type: Object as PropType<TemplateForm>,
    required: true
  },
  isSaved: {
    type: Boolean,
    default: false
  },
  savingBasicInfo: {
    type: Boolean,
    default: false
  },
  uploadingFile: {
    type: Boolean,
    default: false
  },
  fileList: {
    type: Array,
    default: () => []
  },
  attachInfo: {
    type: Object,
    required: true
  },
  isAdd: {
    type: Boolean,
    default: true
  }
});

const emit = defineEmits([
  'save-basic-info',
  'replace-file',
  'download-attachment',
  'file-change',
  'file-exceed',
  'upload-file',
  'view-guide'
]);

const { proxy } = getCurrentInstance() as any;
const { sys_normal_disable } = toRefs<any>(proxy?.useDict('sys_normal_disable'));

// 模板类型选项
const templateTypeOptions = [
  { value: 'WAGE', label: '佣金报表' },
  { value: 'POLICY', label: '保单凭证' },
  { value: 'NOTICE', label: '通知书' },
  { value: 'OTHER', label: '其他' }
];

// 表单引用
const templateFormRef = ref<FormInstance>();

// 表单验证规则
const rules = {
  templateName: [{ required: true, message: '模板名称不能为空', trigger: 'blur' }],
  templateCode: [{ required: true, message: '模板编码不能为空', trigger: 'blur' }],
  templateType: [{ required: true, message: '模板类型不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'change' }]
};

// 格式化文件大小
const formatFileSize = (size: number) => {
  if (!size) return '0 B';

  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(size) / Math.log(k));

  return parseFloat((size / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

// 处理保存基本信息
const handleSaveBasicInfo = async () => {
  if (!templateFormRef.value) return;

  await templateFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      emit('save-basic-info');
    }
  });
};

// 处理更换文件
const handleReplaceFile = () => {
  emit('replace-file');
};

// 处理下载附件
const handleDownloadAttachment = () => {
  emit('download-attachment');
};

// 处理文件选择变更
const handleFileChange = (file: any) => {
  emit('file-change', file);
};

// 处理文件数量超出限制
const handleFileExceed = () => {
  emit('file-exceed');
};

// 处理文件上传
const handleUploadFile = () => {
  emit('upload-file');
};

// 查看模板指南
const handleViewGuide = () => {
  emit('view-guide');
};

// 下载示例模板
const handleDownloadSample = () => {
  // 注: 需要准备示例模板文件并放在正确的静态资源路径
  ElMessage.info('示例模板下载将在后续版本提供');
};
</script>

<style scoped>
.h-100 {
  height: 100%;
}
</style>
