<template>
  <main class="safety-platform-container__main">
    <BasicForm ref="basicFormRef" :formData="ruleFormData" :formRules="formRules" :formConfig="formConfig">
      <template #attachment>
        <!-- <UploadFiles
          label="上传附件"
          :file-list="attachmentFileList"
          :readonly="!isCreateOrEditMode"
          :disabled="!isCreateOrEditMode"
          @uploadSuccess="handleAttachmentUploadSuccess"
          @preview="handlePreview"
        /> -->
        <UploadFiles
          v-if="!isViewMode"
          label="上传文件"
          :maxCount="1"
          :file-list="attachmentFileList" 
          :disabled="isViewMode"
          :allow-all-file-types="true"
          :accept="'.jpg,.jpeg,.png'"
          :desc="'支持.jpg,.jpeg,.png'"
          @uploadSuccess="(list: FileItem[]) => handleAttachmentUploadSuccess(list)"
        />
        <div class="file-list" v-else>
          <div class="file-item" v-for="file in attachmentFileList" :key="file.fileId">
            <span class="file-item--name">{{ file.fileName }}</span>
            <div class="file-item--footer">
              <el-button link type="primary" @click="previewOnline(file.fileUrl, file.fileType)"
                >预览</el-button
              >
              <el-button link type="primary" @click.stop="downloadFile(file.fileUrl, file.fileName)"
                >下载</el-button
              >
            </div>
          </div>
        </div>
      </template>
    </BasicForm>
    <!-- 审核弹窗 -->
    <el-dialog v-model="approveDialogVisible" title="审核" width="500px" @close="handleApproveDialogClose">
      <el-form :model="approveForm" label-width="100px">
        <el-form-item label="审批节点：">
          <el-select v-model="approveForm.node" placeholder="请选择审批节点">
            <el-option label="需求部门" :value="1" />
            <el-option label="安全部门" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="审批状态：">
          <el-radio-group v-model="approveForm.approvalStatus">
            <el-radio :value="2">通过</el-radio>
            <el-radio :value="3">驳回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审批意见：">
          <el-input v-model="approveForm.approvalContent" type="textarea" :rows="4" placeholder="请输入审批意见" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="approveDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleApproveSubmit">确定</el-button>
      </template>
    </el-dialog>
    <PreviewOnline ref="previewOnlineRef" />
  </main>
  <footer class="safety-platform-container__footer">
    <el-button @click="router.back()">返回</el-button>
    <el-button v-if="isCreateOrEditMode" type="primary" @click="handleSubmit">
      {{
        operate === 'employee-report-hidden-trouble-create' || operate === 'hidden-trouble-review-create'
          ? '提交'
          : '保存'
      }}
    </el-button>
    <el-button v-if="isApproveMode" type="primary" @click="handleApproveClick">审核</el-button>
  </footer>
</template>

<script setup lang="ts">
  import { computed, onMounted, ref } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { ElMessage } from 'element-plus';
  import BasicForm from '@/components/BasicForm.vue';
  import UploadFiles from '@/components/UploadFiles/UploadFiles.vue';
  import type { FileItem } from '@/components/UploadFiles/types';
  import { formatAttachmentList } from '@/components/UploadFiles/utils';
  import { useFormConfigHook } from '@/hooks/useFormConfigHook';
  import { ACADEMY_FILE_FORM_CONFIG, ACADEMY_FILE_FORM_DATA, ACADEMY_FILE_FORM_RULES } from '../configs/form';
  import {
    queryHiddenDangerById,
    approveEmployeeHazardReport,
    saveEmployeeHazardReport,
    updateEmployeeHazardReport,
    type ApproveEmployeeHazardReportReq,
  } from '@/api/production-safety';
  import PreviewOnline from '@/views/disaster/components/PreviewOnline.vue';
  import { downloadFile } from '@/views/disaster/utils';

  const router = useRouter();
  const route = useRoute();

  const operate = computed(() => (route.query.operate as string) || 'employee-report-hidden-trouble-view');
  const currentId = computed(() => Number(route.query.id));

  // 支持员工上报与管理员审核两套 operate
  const isViewMode = computed(
    () => operate.value === 'employee-report-hidden-trouble-view' || operate.value === 'hidden-trouble-review-view',
  );
  const isApproveMode = computed(
    () =>
      operate.value === 'employee-report-hidden-trouble-approve' || operate.value === 'hidden-trouble-review-approve',
  );
  // 新增/编辑时表单可编辑，查看/审核时禁用
  const isCreateOrEditMode = computed(
    () =>
      operate.value === 'employee-report-hidden-trouble-create' ||
      operate.value === 'employee-report-hidden-trouble-edit' ||
      operate.value === 'hidden-trouble-review-create' ||
      operate.value === 'hidden-trouble-review-edit',
  );

  const { ruleFormData, formRules, ruleFormConfig, cloneRuleFormData } = useFormConfigHook(
    ACADEMY_FILE_FORM_CONFIG,
    ACADEMY_FILE_FORM_DATA,
    ACADEMY_FILE_FORM_RULES,
  );

  const formConfig = computed(() =>
    isCreateOrEditMode.value
      ? ruleFormConfig.value.map((item) => ({
          ...item,
          componentProps: item.componentProps ? { ...item.componentProps, disabled: false } : undefined,
        }))
      : ruleFormConfig.value,
  );

  const basicFormRef = ref<InstanceType<typeof BasicForm>>();
  const previewOnlineRef = ref<InstanceType<typeof PreviewOnline>>();

  /** 上报时间格式化为 YYYY-MM-DD（详情展示用） */
  function formatReportTimeToDate(reportTime: string | undefined): string {
    if (!reportTime || !String(reportTime).trim()) return '';
    const s = String(reportTime).trim();
    if (s.length >= 10) return s.slice(0, 10);
    return s;
  }

  /** 附件 JSON [{file_name, url}] 转 FileItem 列表，供 UploadFiles 使用（新增/编辑/查看/审核统一展示） */
  function convertAttachmentJsonToFileItems(attachmentStr: string): FileItem[] {
    if (!attachmentStr || !String(attachmentStr).trim()) return [];
    try {
      const arr = JSON.parse(attachmentStr);
      if (!Array.isArray(arr)) return [];
      return arr.map((item: any, index: number) => {
        const fileName = item.file_name || item.fileName || `附件${index + 1}`;
        const url = item.url || item.fileUrl || '';
        const ext = (fileName || '').split('.').pop()?.toLowerCase() || '';
        let fileType = 'pdf';
        if (['doc', 'docx'].includes(ext)) fileType = 'word';
        else if (['xls', 'xlsx'].includes(ext)) fileType = 'excel';
        else if (['ppt', 'pptx'].includes(ext)) fileType = 'ppt';
        return { fileId: index + 1, fileName, fileType, fileSize: '0', fileUrl: url };
      });
    } catch {
      return [];
    }
  }

  const attachmentFileList = computed(() => convertAttachmentJsonToFileItems(ruleFormData.attachment || ''));

  async function handleAttachmentUploadSuccess(files: FileItem[]) {
    if (!files?.length) {
      ruleFormData.attachment = '';
      return;
    }
    try {
      const list = await formatAttachmentList(files);
      const jsonArr = (list || [])
        .map((r) => ({
          file_name: r.fileName,
          url: r.fileUrl || '',
        }))
        .filter((x) => x.url);
      ruleFormData.attachment = JSON.stringify(jsonArr);
    } catch (e) {
      console.error('附件上传失败:', e);
      ElMessage.error(e?.message || e?.data || '附件上传失败，请重试');
    }
  }

  // 审核相关
  const approveDialogVisible = ref(false);
  const approveForm = ref<ApproveEmployeeHazardReportReq>({
    hazardId: 0,
    node: 1,
    approvalStatus: 2,
    approvalContent: '',
  });

  const getDetail = async () => {
    if (!currentId.value) return;
    try {
      const res = await queryHiddenDangerById(currentId.value);
      if (res) {
        // 映射接口字段到表单字段，上报时间格式为 YYYY-MM-DD
        ruleFormData.categoryId = res.categoryId ?? 0;
        ruleFormData.hazardDesc = res.hazardDesc || '';
        ruleFormData.location = res.location || '';
        ruleFormData.reportTime = res.reportTime;
        ruleFormData.sourceTypeName = res.sourceTypeName || '';
        ruleFormData.sourceType = res.sourceType ?? 1;
        ruleFormData.taskSource = res.taskSource || '';
        ruleFormData.reporterName = res.reporterName || '';
        ruleFormData.reporterJobNo = res.reporterJobNo || '';
        ruleFormData.reporterMobile = res.reporterMobile || '';
        ruleFormData.attachment = res.attachment || '';
        ruleFormData.reportTime = res.reportTime || '';
        // 设置审核表单的隐患ID
        approveForm.value.hazardId = res.id;
      }
      cloneRuleFormData();
    } catch (e) {
      console.error('获取隐患上报详情失败:', e);
      ElMessage.error(e?.message || e?.data || '获取详情失败');
    }
  };

  const handlePreview = (url: string) => {
    if (url) {
      // 根据文件扩展名判断文件类型
      const extension = url.split('.').pop()?.toLowerCase() || '';
      let fileType: 'pdf' | 'word' | 'excel' | 'ppt' = 'pdf';
      if (extension === 'doc' || extension === 'docx') {
        fileType = 'word';
      } else if (extension === 'xls' || extension === 'xlsx') {
        fileType = 'excel';
      } else if (extension === 'ppt' || extension === 'pptx') {
        fileType = 'ppt';
      }
      previewOnlineRef.value?.open(url, fileType);
    }
  };

  const handleApproveClick = () => {
    approveDialogVisible.value = true;
  };

  const handleApproveDialogClose = () => {
    approveForm.value.approvalContent = '';
    approveForm.value.node = 1;
    approveForm.value.approvalStatus = 2;
  };

  const handleApproveSubmit = async () => {
    if (!approveForm.value.node || !approveForm.value.approvalStatus) {
      ElMessage.warning('请选择审批节点和审批状态');
      return;
    }
    try {
      await approveEmployeeHazardReport(approveForm.value);
      ElMessage.success('审核成功');
      approveDialogVisible.value = false;
      router.back();
    } catch (e) {
      console.error('审核失败:', e);
      ElMessage.error(e?.message || e?.data || '审核失败，请重试');
    }
  };

  const handleValidate = async () => {
    if (!basicFormRef.value) return false;
    return await basicFormRef.value.validateForm();
  };

  const handleSubmit = async () => {
    const ok = await handleValidate();
    if (!ok) return;
    try {
      const payload = {
        categoryId: ruleFormData.categoryId ?? 0,
        hazardDesc: ruleFormData.hazardDesc || '',
        location: ruleFormData.location || '',
        reportTime: ruleFormData.reportTime || '',
        sourceType: ruleFormData.sourceType ?? 1,
        taskSource: ruleFormData.taskSource || '',
        reporterName: ruleFormData.reporterName || '',
        reporterJobNo: ruleFormData.reporterJobNo || '',
        reporterMobile: ruleFormData.reporterMobile || '',
        attachment: ruleFormData.attachment ? JSON.parse(ruleFormData.attachment) : '',
      };
      if (
        operate.value === 'employee-report-hidden-trouble-create' ||
        operate.value === 'hidden-trouble-review-create'
      ) {
        await saveEmployeeHazardReport(payload);
        ElMessage.success('提交成功');
      } else if (currentId.value) {
        await updateEmployeeHazardReport({ id: currentId.value, ...payload });
        ElMessage.success('保存成功');
      }
      router.back();
    } catch (e) {
      console.error('提交失败:', e);
      ElMessage.error(e?.message || e?.data || '提交失败，请重试');
    }
  };

  const previewOnline = (url: string | undefined, type) => {
    if (url) {
      previewOnlineRef.value?.open(url, type);
    }
  };

  onMounted(() => {
    cloneRuleFormData();
    if (currentId.value) {
      getDetail();
    }
  });
</script>

<style scoped lang="scss">
  @use '@/styles/page-details-layout.scss' as *;
</style>
