<template>
  <div style="padding: 20px; background-color: #f9f9f9; border-radius: 4px">
    <div
      style="
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
      "
    >
      <div style="font-size: 16px; font-weight: 500">档案目录核对</div>
      <div>
        <el-button style="margin-right: 10px" @click="handlePrevStep">
          上一步
        </el-button>
        <el-button type="primary" @click="handleNextStep">下一步</el-button>
      </div>
    </div>
    <el-table
      v-loading="loading"
      :data="proofreadData"
      border
      style="width: 100%"
    >
      <el-table-column type="index" label="序号" width="60" align="center">
        <template slot-scope="{ row }">
          {{ row.orderNum }}
        </template>
      </el-table-column>
      <el-table-column
        prop="materialName"
        label="资料名称"
        min-width="300"
        align="left"
      />
      <el-table-column
        prop="pageCount"
        label="资料页数"
        width="120"
        align="center"
      />
      <el-table-column
        prop="pageRange"
        label="起止页码"
        width="120"
        align="center"
      />
      <el-table-column label="操作" width="200" align="center" fixed="right">
        <template slot-scope="{ row }">
          <el-button
            v-if="row.canGenerate === '1' && row.documentType === 1"
            type="text"
            size="small"
            @click="handleGenerate(row)"
          >
            编辑生成
          </el-button>
          <el-button
            v-if="row.documentType === 0"
            type="text"
            size="small"
            @click="handleViewFiles(row)"
          >
            查看
          </el-button>
          <el-button
            v-if="row.documentType === 2"
            type="text"
            size="small"
            @click="handleViewCatalog(row)"
          >
            编辑生成
          </el-button>
          <el-button
            v-if="row.documentType === 3"
            type="text"
            size="small"
            @click="handleViewCatalog(row)"
          >
            编辑生成
          </el-button>
          <el-button
            v-if="[1, 2, 3].includes(row.documentType) && row.attachmentUrl"
            type="text"
            size="small"
            @click="handlePreviewFile(row)"
          >
            查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 文件列表弹窗（只读模式） -->
    <CostAuditDialog
      :visible.sync="fileListDialogVisible"
      title="文件列表"
      :show-confirm-btn="false"
      :show-footer="false"
      width="80%"
      @cancel="fileListDialogVisible = false"
    >
      <!-- 资料信息展示 -->
      <div
        v-if="currentViewingMaterial"
        style="
          margin-bottom: 20px;
          padding: 15px;
          background-color: #f5f7fa;
          border-radius: 4px;
        "
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <span style="color: #606266; font-size: 14px; margin-right: 10px">
              资料名称：
            </span>
            <span style="font-weight: 500; font-size: 16px">
              {{ currentViewingMaterial.materialName }}
            </span>
          </el-col>
          <el-col :span="12">
            <span style="color: #606266; font-size: 14px; margin-right: 10px">
              资料序号：
            </span>
            <span style="font-weight: 500; font-size: 16px">
              {{
                currentViewingMaterial.materialOrderNum ||
                currentViewingMaterial.orderNum
              }}
            </span>
          </el-col>
        </el-row>
      </div>

      <!-- 文件列表（只读模式，使用表格展示） -->
      <el-table
        v-loading="fileListLoading"
        :data="fileListData"
        border
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column
          prop="documentName"
          label="文书名称"
          min-width="200"
          align="left"
        />
        <el-table-column
          prop="documentNumber"
          label="文号"
          width="200"
          align="center"
        />
        <el-table-column
          prop="auditedUnitName"
          label="被监审单位"
          min-width="150"
          align="left"
        />
        <el-table-column
          prop="fileSource"
          label="文件来源"
          width="150"
          align="center"
        />
        <el-table-column
          prop="pageCount"
          label="页数"
          width="100"
          align="center"
        >
          <template slot-scope="{ row }">
            {{ row.pageCount || 0 }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center" fixed="right">
          <template slot-scope="{ row }">
            <el-button
              v-if="row.attachmentUrl"
              type="text"
              size="small"
              @click="handlePreviewFile(row)"
            >
              查看文件
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" style="text-align: right; margin-top: 20px">
        <el-button @click="fileListDialogVisible = false">关闭</el-button>
      </div>
    </CostAuditDialog>

    <!-- 卷内目录弹窗 -->
    <CostAuditDialog
      :visible.sync="catalogDialogVisible"
      title="卷内目录"
      :show-confirm-btn="false"
      :show-footer="true"
      width="60%"
      @cancel="handleCancelCatalog"
    >
      <!-- 目录表格（只读） -->
      <el-table
        v-loading="catalogLoading"
        :data="catalogData"
        border
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="100" align="center" />
        <el-table-column
          prop="materialName"
          label="资料名称"
          min-width="300"
          align="left"
        />
        <el-table-column
          prop="pageRange"
          label="开始页码-结束页码"
          width="200"
          align="center"
        />
        <!-- <el-table-column
          prop="remark"
          label="备注"
          min-width="200"
          align="left"
        /> -->
      </el-table>

      <div slot="footer" style="text-align: right">
        <el-button @click="handleCancelCatalog">关闭</el-button>
        <el-button type="primary" @click="handleGenerateCatalog">
          生成
        </el-button>
      </div>
    </CostAuditDialog>

    <!-- 生成文书弹窗 -->
    <CostAuditDialog
      :visible.sync="generateDialogVisible"
      :title="generateDialogTitle"
      :show-confirm-btn="false"
      :show-footer="true"
      width="50%"
      @cancel="handleCancelGenerate"
    >
      <el-form
        ref="generateForm"
        :model="generateForm"
        :rules="generateRules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="保管期限" prop="retentionPeriod">
              <el-input-number
                v-model="generateForm.retentionPeriod"
                :min="1"
                :controls="false"
                placeholder="请输入保管期限"
                style="width: 100%"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="卷宗号" prop="archiveNo">
              <el-input
                v-model="generateForm.archiveNo"
                placeholder="请输入卷宗号"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" style="text-align: right">
        <el-button @click="handleCancelGenerate">取消</el-button>
        <el-button type="primary" @click="handleConfirmGenerate">
          确定
        </el-button>
      </div>
    </CostAuditDialog>

    <!-- 卷宗封底说明弹窗 (documentType=3) -->
    <CostAuditDialog
      :visible.sync="coverRemarkDialogVisible"
      title="卷宗封底说明"
      :show-confirm-btn="false"
      :show-footer="true"
      width="50%"
      @cancel="handleCancelCoverRemark"
    >
      <el-form
        ref="coverRemarkForm"
        :model="coverRemarkForm"
        :rules="coverRemarkRules"
        label-width="120px"
      >
        <el-form-item label="封底说明" prop="remark">
          <el-input
            v-model="coverRemarkForm.remark"
            type="textarea"
            :rows="6"
            placeholder="请输入卷宗封底说明内容"
            maxlength="1000"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" style="text-align: right">
        <el-button @click="handleCancelCoverRemark">取消</el-button>
        <el-button type="primary" @click="handleConfirmCoverRemark">
          确定
        </el-button>
      </div>
    </CostAuditDialog>
  </div>
</template>

<script>
  import {
    getArchiveProofreadList,
    saveArchiveDocument,
  } from '@/api/audit/dataProofread'
  import { getDetailListByMasterList } from '@/api/audit/dataInduction'
  import CostAuditDialog from '@/components/costAudit/CostAuditDialog.vue'
  import { Base64 } from 'js-base64'

  export default {
    name: 'ArchiveProofread',
    components: {
      CostAuditDialog,
    },
    props: {
      taskId: {
        type: String,
        default: '',
      },
    },
    data() {
      return {
        loading: false,
        proofreadData: [],
        // 文件列表弹窗相关
        fileListDialogVisible: false,
        fileListData: [],
        fileListLoading: false,
        currentViewingMaterial: null,
        // 卷内目录弹窗相关
        catalogDialogVisible: false,
        catalogData: [],
        catalogLoading: false,
        currentCatalogRow: null,
        // 生成文书弹窗相关
        generateDialogVisible: false,
        generateDialogTitle: '生成文书',
        generateForm: {
          id: '',
          taskId: '',
          documentType: null,
          retentionPeriod: null,
          archiveNo: '',
        },
        generateRules: {
          retentionPeriod: [
            { required: true, message: '请输入保管期限', trigger: 'blur' },
          ],
          archiveNo: [
            { required: true, message: '请输入卷宗号', trigger: 'blur' },
          ],
        },
        currentGenerateRow: null,
        // 卷宗封底说明弹窗相关 (documentType=3)
        coverRemarkDialogVisible: false,
        coverRemarkForm: {
          id: '',
          taskId: '',
          documentType: 3,
          remark: '',
        },
        coverRemarkRules: {
          remark: [
            { required: true, message: '请输入封底说明内容', trigger: 'blur' },
          ],
        },
        currentCoverRemarkRow: null,
        tableRow: {},
      }
    },
    watch: {
      taskId: {
        handler(newVal) {
          if (newVal) {
            this.loadProofreadData()
          }
        },
        immediate: true,
      },
    },
    methods: {
      async loadProofreadData() {
        if (!this.taskId) return

        try {
          this.loading = true
          const response = await getArchiveProofreadList({
            taskId: this.taskId,
          })
          if (response && response.value) {
            this.proofreadData = Array.isArray(response.value)
              ? response.value
              : response.value.list || []
          } else {
            this.proofreadData = []
          }
        } catch (error) {
          console.error('加载卷宗校对列表失败:', error)
          this.proofreadData = []
          this.$message.error('数据加载失败')
        } finally {
          this.loading = false
        }
      },
      handleGenerate(row) {
        this.tableRow = row
        // 处理生成操作
        this.currentGenerateRow = row

        // 根据 documentType 设置弹窗标题
        const titleMap = {
          1: '生成案卷封面',
          2: '生成卷内目录',
          3: '生成案卷封底',
        }
        this.generateDialogTitle = titleMap[row.documentType] || '生成文书'

        // 重置表单数据
        this.generateForm = {
          id: row.id || '',
          taskId: this.taskId,
          documentType: row.documentType,
          retentionPeriod: row.retentionPeriod || null,
          archiveNo: row.archiveNo || '',
        }

        this.generateDialogVisible = true
      },
      handleEdit(row) {
        // 处理编辑操作
        this.$emit('edit', row)
      },
      handleViewFiles(row) {
        // 处理查看文件列表操作
        this.currentViewingMaterial = row
        this.fileListDialogVisible = true
        // 兼容不同的ID字段名称
        const masterId = row.relatedId
        if (!masterId) {
          this.$message.warning('无法获取资料ID')
          console.warn('资料数据缺少ID字段:', row)
          return
        }
        this.loadFileList(masterId)
      },
      handlePreviewFile(row) {
        const rawUrl = row.attachmentUrl || row.url || row.fileUrl
        if (!rawUrl) {
          this.$message.warning('暂无文件！')
          return
        }
        const absoluteUrl = rawUrl.startsWith('http')
          ? rawUrl
          : (window.context?.form || '') + rawUrl
        const baseHost =
          typeof host !== 'undefined' && host ? host : window.location.origin
        const encodedUrl = encodeURIComponent(Base64.encode(absoluteUrl))
        window.open(`${baseHost}:8012/onlinePreview?url=${encodedUrl}`)
      },
      handleViewCatalog(row) {
        // 查看卷内目录（documentType = 2）或卷宗封底说明（documentType = 3）
        if (row.documentType === 2) {
          this.currentCatalogRow = row
          this.catalogDialogVisible = true
          this.loadCatalogData()
        } else if (row.documentType === 3) {
          // 处理 documentType=3 的情况，打开卷宗封底说明弹窗
          this.currentCoverRemarkRow = row

          // 设置表单数据
          this.coverRemarkForm = {
            id: row.id || '',
            taskId: this.taskId,
            documentType: 3,
            remark: row.remark || '',
          }

          this.coverRemarkDialogVisible = true
        }
      },
      async loadCatalogData() {
        try {
          this.catalogLoading = true
          console.log('开始加载卷内目录数据')
          const response = await getArchiveProofreadList({
            taskId: this.taskId,
          })
          console.log('卷内目录响应:', response)

          if (response && response.value) {
            this.catalogData = Array.isArray(response.value)
              ? response.value
              : response.value.list || []

            // 过滤掉前两条记录
            if (this.catalogData.length > 2) {
              this.catalogData = this.catalogData.slice(2)
            } else {
              this.catalogData = []
            }

            console.log('卷内目录数据:', this.catalogData)
          } else {
            this.catalogData = []
            console.warn('卷内目录响应数据为空')
          }
        } catch (error) {
          console.error('加载卷内目录失败:', error)
          this.catalogData = []
          this.$message.error(
            '数据加载失败: ' + (error.message || '请检查网络连接')
          )
        } finally {
          this.catalogLoading = false
        }
      },
      handleCancelCatalog() {
        // 关闭卷内目录弹窗
        this.catalogDialogVisible = false
        this.currentCatalogRow = null
        this.catalogData = []
      },
      async handleGenerateCatalog() {
        // 生成卷内目录，调用 documentType=2 的保存接口
        try {
          this.catalogLoading = true

          const submitData = {
            taskId: this.taskId,
            documentType: 2, // 卷内目录
          }

          // 如果当前行有ID，说明是编辑
          if (this.currentCatalogRow && this.currentCatalogRow.id) {
            submitData.id = this.currentCatalogRow.id
          }

          console.log('生成卷内目录数据:', submitData)

          // 调用保存文书的API接口
          const response = await saveArchiveDocument(submitData)
          if (response && response.success !== false) {
            this.$message.success(response.message || '生成成功')
            this.catalogDialogVisible = false
            this.loadProofreadData() // 重新加载列表
          } else {
            this.$message.error(response.message || '生成失败')
          }
        } catch (error) {
          console.error('生成卷内目录失败:', error)
          this.$message.error(
            '生成失败：' + (error.message || '请检查网络连接')
          )
        } finally {
          this.catalogLoading = false
        }
      },
      async loadFileList(masterId) {
        if (!masterId) {
          console.error('加载文件列表失败: masterId 为空')
          return
        }

        try {
          this.fileListLoading = true
          console.log('开始加载文件列表, masterId:', masterId)
          const response = await getDetailListByMasterList(masterId)
          console.log('文件列表响应:', response)

          if (response && response.value) {
            this.fileListData = Array.isArray(response.value)
              ? response.value
              : response.value.list || []
            console.log('文件列表数据:', this.fileListData)
          } else {
            this.fileListData = []
            console.warn('文件列表响应数据为空')
          }
        } catch (error) {
          console.error('加载文件列表失败:', error)
          this.fileListData = []
          this.$message.error(
            '文件列表加载失败: ' + (error.message || '请检查网络连接')
          )
        } finally {
          this.fileListLoading = false
        }
      },
      handlePrevStep() {
        // 处理上一步操作
        this.$emit('prev-step')
      },
      handleNextStep() {
        // 检查卷宗封面、卷内目录和案卷封底是否有文件数据
        let missingFiles = []

        // 查找各类型的文档
        const coverFile = this.proofreadData.find(
          (item) => item.documentType === 1
        ) // 卷宗封面
        const catalogFile = this.proofreadData.find(
          (item) => item.documentType === 2
        ) // 卷内目录
        const bottomFile = this.proofreadData.find(
          (item) => item.documentType === 3
        ) // 案卷封底

        // 检查各文件是否存在且有附件
        if (!coverFile || !coverFile.attachmentUrl) {
          missingFiles.push('卷宗封面')
        }

        if (!catalogFile || !catalogFile.attachmentUrl) {
          missingFiles.push('卷内目录')
        }

        if (!bottomFile || !bottomFile.attachmentUrl) {
          missingFiles.push('案卷封底')
        }

        // 如果有缺失的文件，提示用户
        if (missingFiles.length > 0) {
          this.$message.warning(`以下文件未生成：${missingFiles.join('、')}`)
          return
        }

        // 如果所有文件都已生成，则继续下一步
        this.$emit('next-step')
      },
      handleCancelGenerate() {
        // 取消生成
        this.generateDialogVisible = false
        this.currentGenerateRow = null
        this.$nextTick(() => {
          if (this.$refs.generateForm) {
            this.$refs.generateForm.resetFields()
          }
        })
      },

      handleCancelCoverRemark() {
        // 取消卷宗封底说明
        this.coverRemarkDialogVisible = false
        this.currentCoverRemarkRow = null
        this.$nextTick(() => {
          if (this.$refs.coverRemarkForm) {
            this.$refs.coverRemarkForm.resetFields()
          }
        })
      },

      async handleConfirmCoverRemark() {
        // 确认卷宗封底说明
        this.$refs.coverRemarkForm.validate(async (valid) => {
          if (!valid) return false

          try {
            // 准备提交数据
            const submitData = {
              taskId: this.coverRemarkForm.taskId,
              documentType: this.coverRemarkForm.documentType,
              remark: this.coverRemarkForm.remark,
            }

            // 如果有ID，说明是编辑
            if (this.coverRemarkForm.id) {
              submitData.id = this.coverRemarkForm.id
            }

            console.log('生成卷宗封底说明数据:', submitData)

            // 调用保存文书的API接口（与documentType=1和documentType=2相同的方法）
            const response = await saveArchiveDocument(submitData)
            if (response && response.success !== false) {
              this.$message.success(response.message || '生成成功')
              this.coverRemarkDialogVisible = false
              this.loadProofreadData() // 重新加载列表
            } else {
              this.$message.error(response.message || '生成失败')
            }
          } catch (error) {
            console.error('生成卷宗封底说明失败:', error)
            this.$message.error(
              '生成失败：' + (error.message || '请检查网络连接')
            )
          }
        })
      },

      async handleConfirmGenerate() {
        // 确认生成
        this.$refs.generateForm.validate(async (valid) => {
          if (!valid) return false

          try {
            // 准备提交数据
            const submitData = {
              taskId: this.generateForm.taskId,
              documentType: this.generateForm.documentType,
              retentionPeriod: this.generateForm.retentionPeriod,
              archiveNo: this.generateForm.archiveNo,
              relatedId: this.tableRow.relatedId,
            }

            // 如果有ID，说明是编辑
            if (this.generateForm.id) {
              submitData.id = this.generateForm.id
            }

            console.log('生成文书数据:', submitData)

            // 调用生成文书的API接口
            const response = await saveArchiveDocument(submitData)
            if (response && response.success !== false) {
              this.$message.success(response.message || '生成成功')
              this.generateDialogVisible = false
              this.loadProofreadData() // 重新加载列表
            } else {
              this.$message.error(response.message || '生成失败')
            }
          } catch (error) {
            console.error('生成文书失败:', error)
            this.$message.error(
              '生成失败：' + (error.message || '请检查网络连接')
            )
          }
        })
      },
    },
  }
</script>

<style scoped lang="scss"></style>
