<template>
  <div class="audit-review">
    <div
      v-for="category in materialCategories"
      :key="category.type"
      class="material-category"
    >
      <h3 class="category-title">{{ category.typeName }}</h3>
      <el-table
        v-loading="loading"
        :data="category.items"
        stripe
        style="width: 100%"
      >
        <el-table-column
          prop="orderNum"
          label="序号"
          width="80"
          align="center"
        />

        <el-table-column
          prop="informationName"
          label="报送资料"
          min-width="200"
        />

        <el-table-column label="资料类型" width="150" align="center">
          <template slot-scope="scope">
            <span
              v-if="
                Number(scope.row.formatRequired) === 2 && scope.row.templateId
              "
              class="template-tag"
              style="cursor: pointer"
              title="点击查看模板"
              @click="handleViewTemplate(scope.row)"
            >
              预置模板
            </span>
            <span v-else>
              {{ getFormatType(scope.row.formatRequired) }}
            </span>
          </template>
        </el-table-column>

        <el-table-column label="是否必项" width="100" align="center">
          <template slot-scope="scope">
            {{ scope.row.isRequired === '1' ? '是' : '否' }}
          </template>
        </el-table-column>

        <el-table-column label="是否上传" width="100" align="center">
          <template slot-scope="scope">
            <span
              :style="{
                color: scope.row.isUpload === '1' ? '#67C23A' : '#F56C6C',
              }"
            >
              {{ scope.row.isUpload === '1' ? '已上传' : '未上传' }}
            </span>
          </template>
        </el-table-column>

        <el-table-column
          prop="createTime"
          label="上传时间"
          width="150"
          align="center"
        />
        <el-table-column label="初审结果" width="100" align="center">
          <template slot-scope="scope">
            <span
              :class="{
                'result-pending':
                  !scope.row.auditedStatus || scope.row.auditedStatus === '0',
                'result-pass': scope.row.auditedStatus === '1',
                'result-fail': scope.row.auditedStatus === '2',
              }"
            >
              {{
                !scope.row.auditedStatus || scope.row.auditedStatus === '0'
                  ? '未审核'
                  : scope.row.auditedStatus === '1'
                  ? '通过'
                  : '不通过'
              }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-button
              v-if="
                scope.row.auditedStatus === '0' &&
                (currentStatus === 200 || currentStatus === '200') &&
                (currentNode === 'clcs' || currentNode === 'sdsh')
              "
              type="text"
              size="small"
              @click="handleAuditMaterial(scope.row)"
            >
              审核
            </el-button>
            <el-button
              type="text"
              size="small"
              @click="handleViewDownload(scope.row)"
            >
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 资料审核弹窗 -->
    <el-dialog
      title="资料审核"
      :visible.sync="showAuditDialog"
      width="400px"
      center
      :modal="false"
      append-to-body
    >
      <div class="audit-material-info">
        <p>
          <strong>资料名称：</strong>
          {{
            (currentAuditMaterial && currentAuditMaterial.informationName) || ''
          }}
        </p>
      </div>
      <el-form ref="auditForm" :model="auditForm" label-width="80px">
        <el-form-item label="审核结果" prop="auditedStatus">
          <el-radio-group v-model="auditForm.auditedStatus">
            <el-radio label="1">审核通过</el-radio>
            <el-radio label="2">不通过</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showAuditDialog = false">取消</el-button>
        <el-button type="primary" @click="handleAuditSubmit">提交</el-button>
      </div>
    </el-dialog>
    <!-- 单记录弹窗 -->
    <survey-form-dialog
      :visible.sync="singleDialogVisible"
      :survey-data="{}"
      :is-view-mode="true"
      :audited-unit-id="
        (currentTemplateRow && currentTemplateRow.auditedUnitId) || ''
      "
      :upload-id="(currentTemplateRow && currentTemplateRow.uploadId) || ''"
      :survey-template-id="
        (currentTemplateRow &&
          (currentTemplateRow.templateId ||
            currentTemplateRow.surveyTemplateId)) ||
        ''
      "
      :catalog-id="(currentTemplateRow && currentTemplateRow.catalogId) || ''"
    />

    <!-- 固定表弹窗（查看模式） -->
    <fixed-table-dialog
      :visible.sync="fixedDialogVisible"
      :is-view-mode="true"
      :audited-unit-id="
        (currentTemplateRow && currentTemplateRow.auditedUnitId) || ''
      "
      :upload-id="(currentTemplateRow && currentTemplateRow.uploadId) || ''"
      :survey-template-id="
        (currentTemplateRow &&
          (currentTemplateRow.templateId ||
            currentTemplateRow.surveyTemplateId)) ||
        ''
      "
      :catalog-id="(currentTemplateRow && currentTemplateRow.catalogId) || ''"
    />

    <!-- 动态表弹窗（查看模式） -->
    <dynamic-table-dialog
      :visible.sync="dynamicDialogVisible"
      :is-view-mode="true"
      :audited-unit-id="
        (currentTemplateRow && currentTemplateRow.auditedUnitId) || ''
      "
      :upload-id="(currentTemplateRow && currentTemplateRow.uploadId) || ''"
      :survey-template-id="
        (currentTemplateRow &&
          (currentTemplateRow.templateId ||
            currentTemplateRow.surveyTemplateId)) ||
        ''
      "
      :catalog-id="(currentTemplateRow && currentTemplateRow.catalogId) || ''"
    />
  </div>
</template>

<style scoped>
  .result-pending {
    color: #909399;
  }

  .result-pass {
    color: #67c23a;
  }

  .result-fail {
    color: #f56c6c;
  }
</style>

<script>
  import {
    getTaskRequirementList,
    addOrUpdateTaskRequirement,
  } from '@/api/audit/auditIndex'
  import {
    getDataPreliminaryReviewButton,
    doProcessBtn,
  } from '@/api/dataPreliminaryReview'
  import SurveyFormDialog from '@/views/EntDeclaration/auditTaskManagement/components/SurveyFormDialog.vue'
  import FixedTableDialog from '@/views/EntDeclaration/auditTaskManagement/components/FixedTableDialog.vue'
  import DynamicTableDialog from '@/views/EntDeclaration/auditTaskManagement/components/DynamicTableDialog.vue'

  export default {
    name: 'AuditReview',
    components: {
      SurveyFormDialog,
      FixedTableDialog,
      DynamicTableDialog,
    },
    props: {
      id: {
        type: [String, Number],
        default: null,
      },
      currentNode: {
        type: String,
        default: '',
      },
      currentStatus: {
        type: String,
        default: '',
      },
      materials: {
        type: Array,
        default: () => [],
      },
    },
    data() {
      return {
        buttonData: [], //资料初审按钮数据
        activeTab: 'materials', // 当前激活的标签页
        showRejectDialog: false, // 初审退回弹窗显示状态
        showAbortDialog: false, // 中止监审弹窗显示状态
        loading: false, // 加载状态
        // 初审退回表单数据
        rejectForm: {
          opinion: '在初审阶段，需补充完善相关材料。',
          sendMethods: ['站内消息', '短信通知'],
        },
        // 中止监审表单数据
        abortForm: {
          opinion:
            '在初审阶段，该企业资料不符合审查要求，中止该单位成本监审资格。',
          sendMethods: ['站内消息', '短信通知'],
        },

        // 资料审核弹窗状态
        showAuditDialog: false,
        // 当前审核的资料
        currentAuditMaterial: null,
        // 模板查看相关
        currentTemplateRow: null,
        singleDialogVisible: false,
        fixedDialogVisible: false,
        dynamicDialogVisible: false,
        // 资料审核表单数据
        auditForm: {
          auditedStatus: '通过', // 默认审核通过
        },
        // 报送资料表格数据
        materialData: [],
        // 按类型分组的材料数据
        materialCategories: [],
      }
    },
    watch: {
      activeTab(newTab) {
        if (newTab === 'costSurvey') {
          this.loadCostSurveyData()
        }
      },
      materials: {
        handler(newList) {
          if (Array.isArray(newList) && newList.length > 0) {
            this.materialData = newList
            this.processMaterialData()
          }
        },
        deep: true,
        immediate: true,
      },
    },
    created() {
      if (Array.isArray(this.materials) && this.materials.length > 0) {
        this.materialData = this.materials
        this.processMaterialData()
      } else {
        this.loadMaterialData()
      }
    },
    mounted() {
      console.log(this.currentNode, '123')
      console.log(this.currentStatus, '222')
    },
    methods: {
      // 加载报送资料数据
      async loadMaterialData() {
        try {
          this.loading = true
          const response = await getTaskRequirementList(this.id)
          console.log('接口返回数据:', response)
          // 尝试多种可能的数据结构
          this.materialData = response.value || response.data || response || []
          // 确保 materialData 是数组
          if (!Array.isArray(this.materialData)) {
            this.materialData = []
          }
          this.processMaterialData()
        } catch (error) {
          console.error('获取报送资料数据失败:', error)
          // this.$message.error('获取报送资料数据失败')
        } finally {
          this.loading = false
        }
      },
      // 处理材料数据按类型分组
      processMaterialData() {
        // 确保 materialData 存在且为数组
        if (!this.materialData || !Array.isArray(this.materialData)) {
          this.materialCategories = []
          return
        }
        const typeMap = {
          1: '综合性资料',
          2: '财务会计资料',
          3: '其他资料',
        }
        const groupedData = {}
        this.materialData.forEach((item) => {
          const type = item.informationType
          if (!groupedData[type]) {
            groupedData[type] = {
              type: type,
              typeName: typeMap[type] || '其他资料',
              items: [],
            }
          }
          groupedData[type].items.push(item)
        })
        // 按指定顺序排列并为每个分类下的材料重新分配序号
        this.materialCategories = []
        ;['1', '2', '3'].forEach((type) => {
          if (groupedData[type]) {
            // 为当前分类下的材料重新分配序号，从1开始递增
            groupedData[type].items.forEach((item, index) => {
              item.orderNum = index + 1
            })
            this.materialCategories.push(groupedData[type])
          }
        })
      },
      // 获取格式类型
      getFormatType(formatRequired) {
        const formatMap = {
          1: '文档文件',
          2: '预置模板',
          3: 'Excel文件',
        }
        return formatMap[formatRequired] || '文档文件'
      },
      // 资料初审按钮点击事件
      handleAuditPass(row) {
        this.$confirm(`确定要${row.value}吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            // 这里可以添加初审通过的API调用逻辑
            doProcessBtn({
              taskId: this.id,
              key: row.key,
            })
              .then((res) => {
                console.log('接口返回数据:', res)
                if (res.code === 200 && res.value) {
                  this.$message({ type: 'success', message: res.value })
                } else {
                  this.$message({ type: 'error', message: res.message })
                }
              })
              .catch((err) => {
                this.$message({ type: 'error', message: err.message })
              })
          })
          .catch(() => {
            this.$message({ type: 'info', message: '已取消操作' })
          })
      },
      // 查看下载文件
      handleViewDownload(row) {
        // this.$message.info(`查看下载文件：${row.name}`)
        // 这里可以添加查看下载文件的逻辑
        this.handleViewTemplate(row)
      },
      // 查看预置模板，按模板类型打开不同弹窗
      handleViewTemplate(row) {
        this.currentTemplateRow = row || null
        const t = String(
          (row && (row.templateType || row.templatetype)) || ''
        ).trim()
        if (t === '1') {
          this.singleDialogVisible = true
        } else if (t === '2') {
          this.fixedDialogVisible = true
        } else if (t === '3') {
          this.dynamicDialogVisible = true
        } else {
          this.$message.warning('未知的模板类型，无法打开预置模板')
        }
      },
      // 查看报表
      handleViewReport(row) {
        this.$message.info(`查看报表：${row.name}`)
        // 这里可以添加查看报表的逻辑
      },
      // 处理资料审核点击事件
      handleAuditMaterial(row) {
        this.currentAuditMaterial = { ...row } // 复制当前行数据
        this.auditForm = {
          auditedStatus:
            this.currentAuditMaterial.auditStatus === '1' ? '通过' : '不通过',
          auditOpinion: '',
        }
        this.showAuditDialog = true
      },

      // 提交资料审核结果
      async handleAuditSubmit() {
        try {
          this.loading = true
          // 更新当前审核材料的审核状态
          this.currentAuditMaterial.auditedStatus = this.auditForm.auditedStatus
          this.currentAuditMaterial.auditResult = this.auditForm.auditedStatus

          // 调用接口提交整个对象
          await addOrUpdateTaskRequirement(this.currentAuditMaterial)

          this.$message({ type: 'success', message: '资料审核操作已提交' })

          // 更新本地数据，使表格显示最新审核结果
          this.loadMaterialData()

          this.showAuditDialog = false
        } catch (error) {
          console.error('资料审核提交失败:', error)
          // this.$message.error('资料审核提交失败，请重试')
        } finally {
          this.loading = false
        }
      },
    },
  }
</script>
<style scoped>
  .audit-review {
    padding: 5px;
    background-color: #ffffff;
  }

  .btn-group {
    margin-bottom: 20px;
  }

  .btn-group .el-button {
    margin-right: 10px;
  }

  .material-category {
    margin-bottom: 30px;
  }

  .category-title {
    margin: 0 0 15px 0;
    padding: 8px 12px;
    background-color: #f5f7fa;
    border-left: 4px solid #409eff;
    font-size: 16px;
    font-weight: 600;
    color: #303133;
  }

  .template-tag {
    background-color: #e6f7ff;
    color: #1677ff;
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 12px;
  }

  .result-pass {
    color: #67c23a;
    font-weight: bold;
  }

  .result-fail {
    color: #f56c6c;
    font-weight: bold;
  }

  /* 表格样式调整 */
  .el-table th {
    background-color: #fafafa;
  }

  /* 弹窗样式调整 */
  .el-dialog__body {
    padding: 20px;
  }

  .audit-material-info {
    margin-bottom: 15px;
    padding: 10px;
    background-color: #f5f7fa;
    border-radius: 4px;
  }

  .audit-material-info p {
    margin: 0;
  }
</style>
