<template>
  <div class="extract-material-container">
    <div class="extract-controls">
      <el-button type="primary" @click="handleAddExtract">添加资料</el-button>
      <!-- <el-button
        type="danger"
        :disabled="selectedRows.length === 0"
        @click="handleBatchDelete"
      >
        批量删除
      </el-button> -->
    </div>

    <el-table
      v-loading="loading"
      :data="extractMaterials"
      style="width: 100%"
      stripe
      border
      size="small"
    >
      <!-- <el-table-column
        type="selection"
        width="55"
        align="center"
      ></el-table-column> -->
      <el-table-column prop="id" label="编号" width="80">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column
        prop="materialName"
        label="材料名称"
        width="200"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        prop="pages"
        label="页数"
        width="100"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="remark"
        label="备注"
        min-width="200"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        prop="createTime"
        label="提取时间"
        width="200"
        :formatter="formatDate"
        align="center"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="操作" width="180" fixed="right">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="handleEditExtract(scope.row)"
          >
            修改
          </el-button>
          <el-button
            type="text"
            size="small"
            @click="handleDeleteExtract(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
      :modal="false"
      append-to-body
      custom-class="extract-material-dialog"
    >
      <div class="dialog-content">
        <el-form
          ref="extractForm"
          :model="extractForm"
          :rules="rules"
          class="extract-form"
          label-width="0"
        >
          <el-form-item
            prop="materialName"
            label="资料名称:"
            class="custom-form-item"
          >
            <el-input
              v-model="extractForm.materialName"
              placeholder="请输入材料名称"
            ></el-input>
          </el-form-item>
          <el-form-item prop="pageCount" label="页数:" class="custom-form-item">
            <el-input-number
              v-model.number="extractForm.pageCount"
              placeholder="请输入页数"
              :min="1"
              :step="1"
            ></el-input-number>
          </el-form-item>
          <el-form-item prop="orderNum" label="序号:" class="custom-form-item">
            <el-input-number
              v-model.number="extractForm.orderNum"
              placeholder="请输入序号"
              :min="1"
              :step="1"
            ></el-input-number>
          </el-form-item>
          <el-form-item prop="remark" label="备注:" class="custom-form-item">
            <el-input
              v-model="extractForm.remark"
              type="textarea"
              placeholder="请输入备注"
              :rows="4"
            ></el-input>
          </el-form-item>
          <el-form-item
            prop="fileList"
            label="上传扫描件:"
            class="custom-form-item"
          >
            <div class="upload-wrapper">
              <el-upload
                class="upload-demo"
                :action="''"
                :http-request="handleFileUpload"
                :on-remove="handleFileRemove"
                :before-upload="beforeFileUpload"
                :on-success="handleFileUploadSuccess"
                :on-error="handleFileUploadError"
                :on-progress="handleFileUploadProgress"
                :file-list="extractForm.fileList"
                :limit="1"
                :on-exceed="handleFileExceed"
              >
                <el-button
                  v-show="
                    !extractForm.fileList || extractForm.fileList.length === 0
                  "
                  type="primary"
                  size="small"
                  class="upload-btn"
                >
                  选择文件
                </el-button>
                <div class="upload-tip">
                  多张扫描图片请插入一个word文档中上传
                </div>
              </el-upload>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  // 暂时使用mock数据，后续根据实际API调整
  import {
    getExtractMaterialList,
    addTaskEvidence,
    updateTaskEvidence,
    deleteTaskEvidence,
  } from '@/api/audit/taskEvidence'
  import { uploadFile } from '@/api/file'

  export default {
    name: 'ExtractMaterial',
    props: {
      id: {
        type: [String, Number],
        default: null,
      },
    },
    data() {
      return {
        loading: false,
        extractMaterials: [],
        selectedRows: [],
        dialogVisible: false,
        dialogTitle: '添加提取材料',
        isEdit: false,
        extractForm: {
          id: '',
          materialName: '',
          pageCount: null,
          orderNum: null,
          remark: '',
          fileList: [],
          attachmentUrl: '',
        },
        rules: {
          materialName: [
            { required: true, message: '请输入材料名称', trigger: 'blur' },
            {
              min: 1,
              max: 100,
              message: '材料名称长度应在1-100个字符之间',
              trigger: 'blur',
            },
          ],
          pageCount: [
            {
              required: true,
              message: '请输入页数',
              trigger: ['blur', 'change'],
            },
            {
              type: 'number',
              message: '页数必须为数字',
              trigger: ['blur', 'change'],
            },
            {
              validator: (rule, value, callback) => {
                if (value === null || value === undefined || value === '') {
                  callback()
                  return
                }
                if (typeof value !== 'number' || isNaN(value)) {
                  callback(new Error('页数必须为数字'))
                  return
                }
                if (value < 1) {
                  callback(new Error('页数必须大于0'))
                  return
                }
                callback()
              },
              trigger: ['blur', 'change'],
            },
          ],
          orderNum: [
            {
              required: true,
              message: '请输入序号',
              trigger: ['blur', 'change'],
            },
            {
              type: 'number',
              message: '序号必须为数字',
              trigger: ['blur', 'change'],
            },
            {
              validator: (rule, value, callback) => {
                if (value === null || value === undefined || value === '') {
                  callback()
                  return
                }
                if (typeof value !== 'number' || isNaN(value)) {
                  callback(new Error('序号必须为数字'))
                  return
                }
                if (value < 1) {
                  callback(new Error('序号必须大于0'))
                  return
                }
                callback()
              },
              trigger: ['blur', 'change'],
            },
          ],
        },
      }
    },
    mounted() {
      this.getExtractMaterials()
    },
    beforeDestroy() {
      // 清理定时器等资源
      this.loading = false
    },
    methods: {
      // 处理选中行变化
      handleSelectionChange(selection) {
        this.selectedRows = selection
      },

      // 获取提取材料列表
      async getExtractMaterials() {
        if (!this.id) {
          return
        }

        try {
          this.loading = true
          const res = await getExtractMaterialList({
            taskId: this.id,
          })

          if (res && res.value) {
            // 统一字段名：如果后端返回的是 pageCount，映射为 pages
            this.extractMaterials = (res.value || []).map((item) => ({
              ...item,
              pages: item.pages !== undefined ? item.pages : item.pageCount,
            }))
          } else {
            this.extractMaterials = []
          }
        } catch (error) {
          // this.$message.error('获取提取材料列表失败')
          console.error('获取提取材料列表失败:', error)
          this.extractMaterials = []
        } finally {
          this.loading = false
        }
      },

      // 添加资料
      handleAddExtract() {
        this.isEdit = false
        this.dialogTitle = '添加提取材料'
        this.extractForm = {
          id: '',
          materialName: '',
          pageCount: null,
          orderNum: null,
          remark: '',
          fileList: [],
          attachmentUrl: '',
        }
        // 重置表单验证状态
        if (this.$refs.extractForm) {
          this.$refs.extractForm.resetFields()
        }
        this.dialogVisible = true
      },

      // 编辑资料
      handleEditExtract(row) {
        this.isEdit = true
        this.dialogTitle = '编辑提取材料'
        // 确保字段名统一，如果后端返回的是 pages，映射为 pageCount
        // 处理文件列表
        let fileList = []
        if (row.attachmentUrl) {
          fileList = [
            {
              name: row.fileName || '附件',
              url: row.attachmentUrl,
              response: { savePath: row.attachmentUrl },
            },
          ]
        }
        this.extractForm = {
          ...row,
          pageCount: row.pageCount !== undefined ? row.pageCount : row.pages,
          orderNum: row.orderNum !== undefined ? row.orderNum : row.orderNumber,
          fileList: fileList,
          attachmentUrl: row.attachmentUrl || '',
        }
        this.dialogVisible = true
      },

      // 删除资料
      async handleDeleteExtract(row) {
        try {
          await this.$confirm('确定要删除该提取材料吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })

          const res = await deleteTaskEvidence({ id: row.id })

          if (res.code === 200) {
            this.$message.success('删除成功')
            // 重新获取列表
            this.getExtractMaterials()
          } else {
            this.$message.error(res.message || '删除失败')
          }
        } catch (error) {
          if (error !== 'cancel') {
            // this.$message.error('删除失败')
            console.error('删除提取材料失败:', error)
          }
        }
      },

      // 批量删除
      async handleBatchDelete() {
        if (this.selectedRows.length === 0) {
          this.$message.warning('请选择要删除的提取材料')
          return
        }

        try {
          await this.$confirm(
            `确定要删除选中的 ${this.selectedRows.length} 条提取材料吗？`,
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }
          )

          // 批量删除，逐条调用删除接口
          const deletePromises = this.selectedRows.map((row) =>
            deleteTaskEvidence({ id: row.id })
          )
          const results = await Promise.all(deletePromises)

          // 检查是否有失败的
          const failedCount = results.filter((res) => res.code !== 200).length
          if (failedCount === 0) {
            this.$message.success('批量删除成功')
            this.selectedRows = [] // 清空选择
            // 重新获取列表
            this.getExtractMaterials()
          } else {
            this.$message.warning(
              `批量删除完成，${
                results.length - failedCount
              } 条成功，${failedCount} 条失败`
            )
            // 即使有失败的，也刷新列表以获取最新数据
            this.selectedRows = []
            this.getExtractMaterials()
          }
        } catch (error) {
          if (error !== 'cancel') {
            // this.$message.error('批量删除失败')
            console.error('批量删除提取材料失败:', error)
          }
        }
      },

      // 提交表单
      async handleSubmit() {
        try {
          await this.$refs.extractForm.validate()

          const formData = {
            id: this.extractForm.id,
            materialName: this.extractForm.materialName,
            pageCount: this.extractForm.pageCount,
            orderNum: this.extractForm.orderNum,
            remark: this.extractForm.remark,
            attachmentUrl: this.extractForm.attachmentUrl,
            taskId: this.id,
          }

          let res
          if (this.isEdit) {
            // 编辑模式，调用更新接口
            res = await updateTaskEvidence(formData)
          } else {
            // 添加模式，调用新增接口
            res = await addTaskEvidence(formData)
          }

          if (res.code === 200) {
            this.$message.success(this.isEdit ? '更新成功' : '添加成功')
            this.dialogVisible = false
            this.getExtractMaterials()
          } else {
            this.$message.error(
              res.message || (this.isEdit ? '更新失败' : '添加失败')
            )
          }
        } catch (error) {
          if (error !== 'cancel') {
            // this.$message.error(this.isEdit ? '更新失败' : '添加失败')
            console.error(
              this.isEdit ? '更新提取材料失败:' : '添加提取材料失败:',
              error
            )
          }
        }
      },

      // 文件上传前验证
      beforeFileUpload(file) {
        const allowedTypes = [
          'application/pdf',
          'application/msword',
          'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
          'application/vnd.ms-excel',
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
          'text/csv',
        ]

        const allowedExtensions = [
          '.pdf',
          '.doc',
          '.docx',
          '.xls',
          '.xlsx',
          '.csv',
        ]
        const fileExtension = '.' + file.name.split('.').pop().toLowerCase()

        // 检查文件格式
        const isCorrectType = allowedTypes.includes(file.type)
        const isCorrectExtension = allowedExtensions.includes(fileExtension)

        if (!isCorrectType && !isCorrectExtension) {
          this.$message.error(
            '只允许上传 pdf, doc, docx, xls, xlsx, csv 格式的文件！'
          )
          return false
        }

        // 检查文件大小 (50MB)
        const isLt50M = file.size / 1024 / 1024 < 50
        if (!isLt50M) {
          this.$message.error('文件大小不能超过 50MB!')
          return false
        }

        return true
      },

      // 自定义上传方法
      async handleFileUpload(options) {
        const { file, onProgress, onSuccess, onError } = options

        // 检查是否已经上传了文件
        if (
          this.extractForm.fileList &&
          this.extractForm.fileList.length >= 1
        ) {
          this.$message.warning('只能上传一个文件，请先删除已上传的文件')
          if (onError) {
            onError(new Error('只能上传一个文件'))
          }
          return
        }

        const formData = new FormData()
        formData.append('file', file)

        try {
          // 显示上传进度
          if (onProgress) {
            onProgress({ percent: 0 })
          }

          // 调用上传API
          const uploadRes = await uploadFile('/api/file/v1/upload', formData, {
            onUploadProgress: (progressEvent) => {
              // 计算上传进度
              if (progressEvent.total) {
                const percent = Math.round(
                  (progressEvent.loaded * 100) / progressEvent.total
                )
                if (onProgress) {
                  onProgress({ percent })
                }
              }
            },
          })

          // 检查上传结果
          if (uploadRes && uploadRes.code === 200 && uploadRes.value) {
            const fileInfo = uploadRes.value
            // 构造文件信息对象，符合element-ui upload组件的格式
            const fileObj = {
              uid: file.uid,
              name: file.name,
              status: 'success',
              size: file.size,
              response: fileInfo,
              url: fileInfo.savePath || fileInfo.url,
            }

            if (onSuccess) {
              onSuccess(fileInfo, fileObj)
              this.extractForm.attachmentUrl = fileInfo.savePath || fileInfo.url
            }

            this.$message.success(`${file.name} 上传成功`)
          } else {
            throw new Error(uploadRes?.message || '上传失败，请稍后重试')
          }
        } catch (error) {
          console.error('文件上传失败:', error)
          // this.$message.error(`文件上传失败：${error.message || '未知错误'}`)
          if (onError) {
            onError(error)
          }
        }
      },

      // 上传成功回调
      handleFileUploadSuccess(response, file, fileList) {
        // 更新文件列表，添加文件URL信息
        this.extractForm.fileList = fileList.map((item) => {
          if (item.uid === file.uid && response) {
            return {
              ...item,
              url: response.savePath || response.url || item.url,
              response: response,
            }
          }
          return item
        })
      },

      // 上传进度回调
      handleFileUploadProgress(event, file, fileList) {
        // element-ui 会自动处理上传进度显示
      },

      // 上传失败回调
      handleFileUploadError(err, file, fileList) {
        console.error('文件上传错误:', err)
        this.$message.error(`${file.name} 上传失败`)
        // 从文件列表中移除失败的文件
        this.extractForm.fileList = fileList.filter(
          (item) => item.uid !== file.uid
        )
      },

      // 超出文件数量限制
      handleFileExceed(files, fileList) {
        this.$message.warning(
          `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${fileList.length} 个文件`
        )
      },

      // 移除文件
      handleFileRemove(file, fileList) {
        this.extractForm.fileList = fileList
        this.extractForm.attachmentUrl = ''
        this.$message.info(`${file.name} 已移除`)
      },

      // 格式化日期
      formatDate(row, column, cellValue) {
        if (!cellValue) return ''
        try {
          const date = new Date(cellValue)
          if (isNaN(date.getTime())) return ''
          return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
            2,
            '0'
          )}-${String(date.getDate()).padStart(2, '0')} ${String(
            date.getHours()
          ).padStart(2, '0')}:${String(date.getMinutes()).padStart(
            2,
            '0'
          )}:${String(date.getSeconds()).padStart(2, '0')}`
        } catch (error) {
          return cellValue
        }
      },
    },
  }
</script>

<style scoped>
  /* .extract-material-container {
    padding: 20px;
  } */

  .extract-controls {
    margin-bottom: 20px;
    text-align: left;
  }

  /* 操作按钮样式优化 */
  .el-button--small {
    margin-right: 8px;
  }

  /* 表格行悬停效果 */
  .el-table--enable-row-hover .el-table__body tr:hover > td {
    background-color: #f5f7fa;
  }
</style>

<style>
  /* 弹窗样式 */
  .extract-material-dialog .dialog-content {
    padding: 20px;
  }

  .extract-material-dialog .extract-form {
    margin: 0;
  }

  .extract-material-dialog .custom-form-item {
    display: flex;
    align-items: flex-start;
    margin-bottom: 20px;
  }

  .extract-material-dialog .custom-form-item .el-form-item__label {
    width: 100px !important;
    text-align: center !important;
    /* color: #409eff !important; */
    font-size: 14px;
    flex-shrink: 0;
    padding: 0 !important;
    line-height: 32px;
  }

  .extract-material-dialog .custom-form-item .el-form-item__content {
    flex: 1;
    margin-left: 0 !important;
  }

  .extract-material-dialog .custom-form-item .el-input,
  .extract-material-dialog .custom-form-item .el-textarea,
  .extract-material-dialog .custom-form-item .el-input-number {
    width: 100%;
  }

  .extract-material-dialog .upload-wrapper {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }

  .extract-material-dialog .upload-tip {
    font-size: 12px;
    color: #909399;
    line-height: 1.5;
    margin-top: 10px;
  }

  .extract-material-dialog .upload-btn {
    align-self: flex-start;
  }

  .extract-material-dialog .el-upload {
    text-align: left;
  }

  .extract-material-dialog .dialog-footer {
    text-align: center;
    padding: 10px 0;
  }

  .extract-material-dialog .dialog-footer .el-button {
    margin: 0 10px;
  }
</style>
