<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"
          header-align="center"
          align="left"
        />

        <el-table-column label="资料类型" width="200" align="center">
          <template slot-scope="scope">
            <span
              v-if="
                Number(scope.row.formatRequired) === 3 && scope.row.templateId
              "
              style="cursor: pointer"
              :title="'点击查看模板'"
            >
              {{ `预置模板(${getTemplateTypeName(scope.row.templateType)})` }}
            </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="uploadTime"
          label="上传时间"
          width="150"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.uploadTime ? scope.row.uploadTime : '--' }}
          </template>
        </el-table-column>
        <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')) ||
                (scope.row.taskNode === 'jtsy' &&
                  scope.row.auditedStatus === '0')
              "
              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="{ ...(currentTemplateRow || {}), ...surveyDetailData }"
      :is-view-mode="true"
      :request-type="2"
      :audited-unit-id="
        auditedUnitId ||
        (currentTemplateRow && currentTemplateRow.auditedUnitId) ||
        ''
      "
      :upload-id="
        (currentTemplateRow &&
          (currentTemplateRow.uploadId || currentTemplateRow.id)) ||
        ''
      "
      :survey-template-id="
        (currentTemplateRow &&
          (currentTemplateRow.templateId ||
            currentTemplateRow.surveyTemplateId)) ||
        ''
      "
      :catalog-id="
        catalogId || (currentTemplateRow && currentTemplateRow.catalogId) || ''
      "
    />

    <fixed-table-dialog
      :visible.sync="fixedDialogVisible"
      :is-view-mode="true"
      :request-type="2"
      :project-id="projectId"
      :audited-unit-id="
        auditedUnitId ||
        (currentTemplateRow && currentTemplateRow.auditedUnitId) ||
        ''
      "
      :upload-id="
        (currentTemplateRow &&
          (currentTemplateRow.uploadId || currentTemplateRow.id)) ||
        ''
      "
      :survey-template-id="
        (currentTemplateRow &&
          (currentTemplateRow.templateId ||
            currentTemplateRow.surveyTemplateId)) ||
        ''
      "
      :catalog-id="
        catalogId || (currentTemplateRow && currentTemplateRow.catalogId) || ''
      "
      :project-audit-periods="projectAuditPeriods"
      :project-audit-period="projectAuditPeriod"
      :audit-periods="auditPeriods"
      :fixed-fields="fixedFields || ''"
      :fixed-fieldids="fixedFieldids || ''"
      :table-items="tableItems"
    />

    <dynamic-table-dialog
      :visible.sync="dynamicDialogVisible"
      :is-view-mode="true"
      :request-type="2"
      :audited-unit-id="
        auditedUnitId ||
        (currentTemplateRow && currentTemplateRow.auditedUnitId) ||
        ''
      "
      :upload-id="
        (currentTemplateRow &&
          (currentTemplateRow.uploadId || currentTemplateRow.id)) ||
        ''
      "
      :survey-template-id="
        (currentTemplateRow &&
          (currentTemplateRow.templateId ||
            currentTemplateRow.surveyTemplateId)) ||
        ''
      "
      :catalog-id="
        catalogId || (currentTemplateRow && currentTemplateRow.catalogId) || ''
      "
      :table-data="dynamicTableData"
      :table-items="tableItems"
    />
  </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'
  import { getSingleRecordSurveyList } from '@/api/audit/survey'
  import { getDynamicTableData } from '@/api/audit/survey'
  import { getProjectInformationInfo } from '@/api/auditTaskProcessing'
  import { getSurveyDetail } from '@/api/audit/survey'

  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: () => [],
      },
      auditedUnitId: {
        type: [String, Number],
        default: '',
      },
      catalogId: {
        type: [String, Number],
        default: '',
      },
      // 任务ID，用于在缺少 uploadId 时回退查询详情
      taskId: {
        type: [String, Number],
        default: '',
      },
      // 立项信息ID（用于获取监审期间）
      projectId: {
        type: [String, Number],
        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,
        // 固定表/动态表所需的配置与数据（用于弹窗透传）
        fixedFields: '',
        fixedFieldids: '',
        tableItems: [],
        dynamicTableData: [],
        // 立项信息监审期间
        projectAuditPeriods: [],
        projectAuditPeriod: '',
        auditPeriods: [],
        // 详情回显数据（供单记录弹窗 survey-data 绑定使用）
        surveyDetailData: {},
        // 资料审核表单数据
        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 map = {
          1: '文档文件',
          2: 'excel',
          3: '预置模板',
        }
        const k = Number(formatRequired)
        return map[k] || '文档文件'
      },
      getTemplateTypeName(t) {
        const map = {
          1: '单记录',
          2: '固定表',
          3: '动态表',
        }
        const k = String(t || '').trim()
        return map[k] || map[Number(k)] || ''
      },
      // 资料初审按钮点击事件
      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}`)
        // 这里可以添加查看下载文件的逻辑
        if (row.fileUrl !== null) {
          this.handleFileView(row)
        } else {
          this.handleViewTemplate(row)
        }
      },
      handleFileView(row) {
        console.log(row, '这一行数据')
        try {
          const filePath =
            row?.filePath ||
            row?.filepath ||
            row?.fileUrl ||
            row?.url ||
            row?.path ||
            ''
          if (!filePath) {
            this.$message &&
              this.$message.warning &&
              this.$message.warning('未找到可预览的文件路径')
            return
          }
          const encodedUrl = encodeURIComponent(
            Base64.encode((window.context && window.context.form) + filePath)
          )
          window.open(`${host}:8012/onlinePreview?url=${encodedUrl}`)
          // 兼容保留：通知父组件
          this.$emit('handleFileView', row)
        } catch (e) {
          console.error('文件预览失败: ', e)
          // this.$message &&
          //   this.$message.error &&
          //   this.$message.error('文件预览失败')
        }
      },
      // 查看预置模板，按模板类型打开不同弹窗
      async handleViewTemplate(row) {
        this.currentTemplateRow = row || null
        const t = String(
          (row && (row.templateType || row.templatetype)) || ''
        ).trim()
        if (t === '1') {
          // 单记录：清理并预取详情（type=2），与 costSurvey 实现保持一致的回显逻辑
          this.surveyDetailData = {}
          await this.loadSingleRecordDetail()
          this.singleDialogVisible = true
        } else if (t === '2') {
          // 与 components 版本一致：先拉取固定表表头与项配置
          const surveyTemplateId =
            (row && (row.surveyTemplateId || row.templateId)) || ''
          Promise.all([
            this.initFixedTableData(surveyTemplateId),
            this.fetchProjectAuditPeriods(),
          ]).then(() => {
            this.fixedDialogVisible = true
          })
        } else if (t === '3') {
          await this.initDynamicTableData()
          this.dynamicDialogVisible = true
        } else {
          this.$message.warning('未知的模板类型，无法打开预置模板')
        }
      },
      // 预取动态表数据（type=2），与 costSurvey 一致的参数拼装，但本页使用 type=2
      async initDynamicTableData() {
        this.dynamicTableData = []
        const row = this.currentTemplateRow || {}
        const uploadId = row.uploadId || row.id || ''
        const auditedUnitId = row.auditedUnitId || this.auditedUnitId || ''
        const catalogId = row.catalogId || this.catalogId || ''
        const surveyTemplateId = row.templateId || row.surveyTemplateId || ''
        if (!uploadId) return
        try {
          const params = {
            uploadId,
            ...(auditedUnitId ? { auditedUnitId } : {}),
            catalogId,
            surveyTemplateId,
            type: 2,
          }
          const res = await getDynamicTableData(params)
          if (res && res.code === 200) {
            const records =
              (res.value && (res.value.records || res.value)) || []
            this.dynamicTableData = Array.isArray(records) ? records : []
          }
        } catch (e) {
          this.dynamicTableData = []
        }
      },
      // 获取立项信息监审期间，供固定表年份优先回显
      async fetchProjectAuditPeriods() {
        try {
          this.projectAuditPeriods = []
          this.projectAuditPeriod = ''
          const pid = this.projectId
          if (!pid) return
          const res = await getProjectInformationInfo(pid)
          const periodStr =
            (res &&
              res.value &&
              (res.value.auditPeriod || res.value.auditperiod)) ||
            ''
          if (typeof periodStr === 'string' && periodStr.trim()) {
            const arr = periodStr
              .split(',')
              .map((y) => String(y).trim())
              .filter((y) => /^(19|20)\d{2}$/.test(y))
            this.projectAuditPeriods = arr
            this.projectAuditPeriod = arr.join(',')
          }
        } catch (e) {
          console.error('获取立项信息监审期间失败', e)
          this.projectAuditPeriods = []
          this.projectAuditPeriod = ''
        }
      },
      // 预取单记录详情（type=2），将数组结果映射为 { rowid: rvalue } 的对象，供弹窗回显
      async loadSingleRecordDetail() {
        this.surveyDetailData = {}
        const row = this.currentTemplateRow || {}
        const uploadId = row.uploadId || row.id || ''
        const auditedUnitId = row.auditedUnitId || this.auditedUnitId || ''
        const hasUpload = Boolean(uploadId)
        const hasTask = Boolean(this.taskId)
        if (!hasUpload && !hasTask) return
        try {
          const params = hasUpload
            ? { uploadId, type: 2, ...(auditedUnitId ? { auditedUnitId } : {}) }
            : { taskId: this.taskId, type: 2 }
          const res = await getSurveyDetail(params)
          if (res && res.code === 200 && res.value) {
            const detail = {}
            const val = res.value
            if (Array.isArray(val)) {
              val.forEach((item) => {
                if (!item || typeof item !== 'object') return
                const key =
                  item.rowid !== undefined
                    ? item.rowid
                    : item.rowId !== undefined
                    ? item.rowId
                    : item.id !== undefined
                    ? item.id
                    : undefined
                const value =
                  item.rvalue !== undefined
                    ? item.rvalue
                    : item.rValue !== undefined
                    ? item.rValue
                    : item.value !== undefined
                    ? item.value
                    : item.val !== undefined
                    ? item.val
                    : ''
                if (key !== undefined) detail[key] = value
              })
            } else if (val && typeof val === 'object') {
              Object.assign(detail, val)
            }
            this.surveyDetailData = detail
          }
        } catch (e) {
          this.surveyDetailData = {}
        }
      },
      // 获取固定表配置（表头与项），与 components/task/components/submitData.vue 保持一致
      async initFixedTableData(surveyTemplateId) {
        try {
          this.fixedFields = ''
          this.fixedFieldids = ''
          this.tableItems = []
          if (!surveyTemplateId) return
          const params = { surveyTemplateId, type: 2 }
          const res = await getSingleRecordSurveyList(params)
          if (res && res.code === 200 && res.value) {
            this.fixedFields = res.value.fixedFields || ''
            this.fixedFieldids = res.value.fixedFieldids || ''
            const { itemlist } = res.value || {}
            if (Array.isArray(itemlist) && itemlist.length > 0) {
              this.tableItems = itemlist.map((item) => ({
                id: item.id || item.itemId || '',
                rowid: item.rowid || item.id || item.itemId || '',
                seq: item.序号,
                itemName: item.项目 || item.itemName || '',
                unit: item.unit || '',
                isCategory: item.isCategory || false,
                categorySeq: item.categorySeq || '',
                categoryId: item.categoryId || '',
                parentid:
                  item.parentid !== undefined
                    ? item.parentid
                    : item.parentId !== undefined
                    ? item.parentId
                    : '-1',
                validateRules: item.validateRules || {},
                linkageRules: item.linkageRules || {},
                children: item.children || [],
                ...item,
              }))
            }
          }
        } catch (e) {
          console.error('获取固定表配置失败:', e)
          this.tableItems = []
        }
      },
      // 查看报表
      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>
