<template>
  <div class="safety-platform-container">
    <header class="safety-platform-container__header">
      <div class="breadcrumb-title">{{ detailData?.problem || '-' }}</div>
      <div class="detail-content">
        <span>创建人：{{ detailData?.creatorName || '-' }}</span>
        <span>创建时间：{{ detailData?.createdAt || '-' }}</span>
      </div>
    </header>
    <main class="safety-platform-container__main">
      <div class="audit-content">
        <h4 class="section-title">
          <el-icon class="section-title__icon"><Document /></el-icon>
          <span>基本信息</span>
        </h4>
        <div class="detail-ct detail-ct--table">
          <div class="row">
            <div class="col">
              <div class="label">隐患问题：</div>
              <div class="value">{{ detailData?.problem || '-' }}</div>
            </div>
            <div class="col">
              <div class="label">状态：</div>
              <div class="value">{{ detailData?.statusName || '-' }}</div>
            </div>
          </div>
          <div class="row">
            <div class="col">
              <div class="label">下发数：</div>
              <div class="value">{{ detailData?.issueCount ?? '-' }}</div>
            </div>
            <div class="col">
              <div class="label">反馈数：</div>
              <div class="value">{{ detailData?.feedbackCount ?? '-' }}</div>
            </div>
          </div>
          <div class="row">
            <div class="col">
              <div class="label">计划开始日期：</div>
              <div class="value">{{ detailData?.planStartDate || detailData?.dangerProposeDate || '-' }}</div>
            </div>
            <div class="col">
              <div class="label">计划完成日期：</div>
              <div class="value">{{ detailData?.associationOtTimeLimit || '-' }}</div>
            </div>
          </div>
        </div>

        <h4 class="section-title">
          <el-icon class="section-title__icon"><Document /></el-icon>
          <span>举一反三要求</span>
        </h4>
        <div class="detail-ct requirement-block">
          <div class="value value-text">{{ detailData?.associationOneThree || '-' }}</div>
        </div>

        <h4 class="section-title">
          <el-icon class="section-title__icon"><Document /></el-icon>
          <span>材料上传</span>
        </h4>
        <div class="detail-ct detail-ct--table attachment-row">
          <div class="row">
            <div class="col">
              <div class="label">上传附件：</div>
              <div class="value value--attachment">
                <template v-if="attachmentFileList.length">
                  <div
                    class="file-container--div"
                    v-for="item in attachmentFileList"
                    :key="item.fileUrl || item.fileName"
                  >
                    <img
                      class="file-container--div__icon"
                      :src="FILE_TYPE_ICON[item.fileType]"
                      @click="previewOnline(item.fileUrl, item.fileType)"
                    />
                    <span
                      class="file-container--div__name"
                      @click="previewOnline(item.fileUrl, item.fileType)"
                    >
                      {{ item.fileName }}
                    </span>
                    <img
                      class="file-container--div__download"
                      :src="DownloadIcon"
                      @click="downloadFile(item.fileUrl, item.fileName)"
                    />
                  </div>
                </template>
                <span v-else class="empty-text">-</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
    <footer class="safety-platform-container__footer">
      <el-button @click="router.back()">返回</el-button>
      <el-button type="primary" @click="handleReject" v-if="!isViewMode">审核不通过</el-button>
      <el-button type="primary" @click="handleApprove" v-if="!isViewMode">审核通过</el-button>
    </footer>

    <el-dialog
      v-model="showRejectDialog"
      title="审核不通过原因"
      width="560px"
      :close-on-click-modal="false"
      destroy-on-close
      @close="rejectReason = ''"
    >
      <el-input
        v-model="rejectReason"
        type="textarea"
        :rows="6"
        maxlength="300"
        show-word-limit
        placeholder="请填写审核不通过原因（限300字）"
      />
      <template #footer>
        <el-button @click="showRejectDialog = false">取消</el-button>
        <el-button type="primary" @click="handleRejectSubmit">确定</el-button>
      </template>
    </el-dialog>
    <PreviewOnline ref="previewOnlineRef" />
  </div>
</template>

<script setup lang="ts">
  import { computed, onMounted, ref } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { ElMessage } from 'element-plus';
  import { Document } from '@element-plus/icons-vue';
  import PreviewOnline from '@/views/disaster/components/PreviewOnline.vue';
  import { getDrawLessonsAdminTowDetail, approveDrawLessons } from '@/api/drawLessons';
  import { FILE_TYPE_ICON } from '@/components/UploadFiles/constants';
  import DownloadIcon from '@/views/disaster/disaster-control/src/svg/download.svg';
  import { downloadFile } from '@/views/disaster/utils';

  const router = useRouter();
  const route = useRoute();
  const id = computed(() => Number(route.query.id));
  const operate = computed(() => (route.query.operate as string) || 'one-by-one-audit-detail');
  const isViewMode = computed(() => operate.value === 'one-by-one-audit-view');

  const detailData = ref<{
    problem?: string;
    creatorName?: string;
    createdAt?: string;
    statusName?: string;
    issueCount?: number;
    feedbackCount?: number;
    planStartDate?: string;
    dangerProposeDate?: string;
    associationOtTimeLimit?: string;
    associationOneThree?: string;
    attachments?: string;
    attachmentList?: Array<{ fileName?: string; fileUrl?: string; fileNameOrUrl?: string; url?: string }>;
    issueId?: number;
  } | null>(null);

  const showRejectDialog = ref(false);
  const rejectReason = ref('');
  const submitting = ref(false);
  const previewOnlineRef = ref<InstanceType<typeof PreviewOnline>>();

  const attachmentFileList = computed(() => {
    const d = detailData.value;
    if (!d) return [];
    const normalize = (items: Array<{ fileUrl?: string; url?: string; fileName?: string; fileNameOrUrl?: string }>) => {
      return items.map((raw, index) => {
        const url = raw.fileUrl || raw.url || raw.fileNameOrUrl || '';
        const nameFromData = raw.fileName || raw.fileNameOrUrl;
        const fileName = nameFromData || (url ? url.split('/').pop() || `附件${index + 1}` : `附件${index + 1}`);
        const ext = fileName.split('.').pop()?.toLowerCase() || '';
        let fileType: 'pdf' | 'word' | 'excel' | 'ppt' = 'pdf';
        if (ext === 'doc' || ext === 'docx') fileType = 'word';
        else if (ext === 'xls' || ext === 'xlsx') fileType = 'excel';
        else if (ext === 'ppt' || ext === 'pptx') fileType = 'ppt';
        return {
          fileUrl: url,
          fileName,
          fileType,
        };
      });
    };
    if (Array.isArray(d.attachmentList) && d.attachmentList.length) {
      return normalize(d.attachmentList);
    }
    if (!d.attachments) return [];
    try {
      const parsed = JSON.parse(d.attachments);
      if (Array.isArray(parsed) && parsed.length) {
        return normalize(parsed as Array<{ fileUrl?: string; url?: string; fileName?: string; fileNameOrUrl?: string }>);
      }
    } catch {
      const list = d.attachments
        .split(',')
        .map((s) => s.trim())
        .filter(Boolean)
        .map((s) => ({ fileNameOrUrl: s, fileUrl: s }));
      if (list.length) return normalize(list);
    }
    return [];
  });

  const getDetail = async () => {
    if (!id.value) return;
    try {
      const res = await getDrawLessonsAdminTowDetail(id.value);
      const data = (res as any)?.data ?? res;
      if (data && typeof data === 'object') {
        const records = Array.isArray(data.issueRecords) ? data.issueRecords : [];
        detailData.value = {
          problem: data.problem,
          creatorName: data.creatorName,
          createdAt: data.createdAt,
          statusName: data.statusName,
          issueCount: data.issueCount,
          feedbackCount: data.feedbackCount ?? records.filter((r: any) => r.statusId === 5 || r.statusName === '已完成' || r.feedbackAt).length,
          planStartDate: data.planStartDate,
          dangerProposeDate: data.dangerProposeDate,
          associationOtTimeLimit: data.associationOtTimeLimit,
          associationOneThree: data.associationOneThree,
          attachments: data.attachments,
          attachmentList: data.attachmentList,
          issueId: data.issueId,
        };
      }
    } catch (e) {
      console.error('获取举一反三详情失败:', e);
      ElMessage.error(e?.message || e?.data || '获取详情失败');
    }
  };

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

  const handleReject = () => {
    showRejectDialog.value = true;
  };

  const handleRejectSubmit = async () => {
    if (!rejectReason.value?.trim()) {
      ElMessage.warning('请填写审核不通过原因');
      return;
    }
    if (!id.value) return;
    submitting.value = true;
    try {
      await approveDrawLessons({
        id: id.value,
        statusId: 6,
        statusName: '已作废',
        reviewReason: rejectReason.value?.trim() || undefined,
      });
      ElMessage.success('审核不通过操作成功');
      showRejectDialog.value = false;
      rejectReason.value = '';
      router.back();
    } catch (e) {
      console.error('审核不通过失败:', e);
      ElMessage.error(e?.message || e?.data || '操作失败，请重试');
    } finally {
      submitting.value = false;
    }
  };

  const handleApprove = async () => {
    if (!id.value) return;
    submitting.value = true;
    try {
      await approveDrawLessons({
        id: detailData.value.issueId ?? '',
        statusId: 5,
        statusName: '已完成',
      });
      ElMessage.success('审核通过操作成功');
      router.back();
    } catch (e) {
      console.error('审核通过失败:', e);
      ElMessage.error(e?.message || e?.data || '操作失败，请重试');
    } finally {
      submitting.value = false;
    }
  };

  onMounted(() => {
    getDetail();
  });
</script>

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

  .detail-content {
    display: flex;
    gap: 30px;
    margin: 10px 0;
    font-size: 14px;
  }

  .audit-content {
    padding: 0 16px;

    .section-title {
      display: flex;
      align-items: center;
      gap: 8px;
      margin: 20px 0 12px 0;
      font-size: 16px;
      font-weight: 600;
      color: #333;

      .section-title__icon {
        font-size: 18px;
        color: #333;
      }
    }

    .section-title:first-child {
      margin-top: 0;
    }

    .detail-ct {
      font-size: 14px;
      margin-bottom: 20px;

      &--table {
        border: 1px solid #dcdfe6;
        .row {
          display: flex;
          border-bottom: 1px solid #dcdfe6;

          &:last-child {
            border-bottom: none;
          }
        }
        .col {
          display: flex;
          flex: 1;
          min-height: 40px;
          align-items: stretch;

          &.col--wide {
            flex: 2;
          }

          .label {
            display: flex;
            align-items: center;
            justify-content: flex-end;
            flex-shrink: 0;
            width: 140px;
            padding: 0 12px;
            background-color: #f5f5f5;
            border-right: 1px solid #dcdfe6;
            color: #333;
          }

          .value {
            flex: 1;
            display: flex;
            align-items: center;
            padding: 10px 20px;
            background-color: #fff;
            border-right: 1px solid #dcdfe6;
            color: #333;
          }
        }

        .row .col:last-child .value {
          border-right: none;
        }

        .row .col:nth-child(2) .label {
          border-left: 1px solid #dcdfe6;
        }
      }

      &.requirement-block {
        border: 1px solid #e0e0e0;
        background-color: #fff;
        padding: 16px 20px;
        min-height: 60px;

        .value-text {
          white-space: pre-wrap;
          word-break: break-word;
          color: #333;
          line-height: 1.5;
        }
      }

      &.attachment-row .value--attachment {
        flex-wrap: wrap;
        align-items: flex-start;

        .empty-text {
          color: #999;
        }
      }
    }
  }
</style>
