<!-- 成果列表 -->
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="文件名称" prop="wjmc">
        <el-input v-model="queryParams.wjmc" placeholder="请输入文件名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="资料类型" prop="zllx">
        <el-select v-model="queryParams.zllx" placeholder="请选择资料类型" clearable>
          <el-option
            v-for="item in zllxOptions"
            :key="item.id"
            :label="item.lxmc"
            :value="item.lxmc">
          </el-option>
        </el-select>
        
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['yscgWjscqk:wjscqk:add']">新增</el-button>
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['yscgWjscqk:wjscqk:edit']">修改</el-button>
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['yscgWjscqk:wjscqk:remove']">删除</el-button>
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['yscgWjscqk:wjscqk:export']">导出</el-button>
      </el-form-item>
    </el-form>


    <el-table border v-loading="loading" :data="wjscqkList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="文件名称" align="center" prop="wjmc" min-width="120" show-overflow-tooltip />
      <el-table-column label="资料类型" align="center" prop="zllx" min-width="100" show-overflow-tooltip />
      <el-table-column label="上传时间" align="center" prop="createdTime" min-width="170" show-overflow-tooltip />
      <el-table-column label="操作" min-width="110" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['yscgWjscqk:wjscqk:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['yscgWjscqk:wjscqk:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改成果管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="89px">
       
      <el-form-item label="资料类型" prop="zllx">
        <el-select v-model="form.zllx" placeholder="请选择资料类型" clearable>
          <el-option
            v-for="item in zllxOptions"
            :key="item.id"
            :label="item.lxmc"
            :value="item.lxmc">
          </el-option>
        </el-select>
      </el-form-item>

       <el-form-item label="文件上传" prop="fileList">
         <el-upload
           ref="fileUpload"
           :action="uploadUrl"
           :headers="uploadHeaders"
           :file-list="fileList"
           :before-upload="handleBeforeUpload"
           :on-success="handleUploadSuccess"
           :on-error="handleUploadError"
           :on-remove="handleRemove"
           :on-exceed="handleExceed"
           :on-change="handleFileChange"
           :data="uploadData"
           drag
           class="upload-dragger"
         >
           <i class="el-icon-upload"></i>
           <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
           <div class="el-upload__tip" slot="tip">
             支持 doc、docx、pdf、xls、xlsx、ppt、pptx、txt、jpg、jpeg、png、gif 格式文件，单个文件不超过50MB<br/>
             <span style="color: #409EFF;">上传新文件将自动替换已有文件</span>
           </div>
         </el-upload>
       </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listWjscqk, getWjscqk, delWjscqk, addWjscqk, updateWjscqk } from "@/api/yscgWjscqk/wjscqk"
import { selectZllx } from "@/api/yscgZllx/zllx"
import { getToken } from "@/utils/auth"

export default {
  name: "Wjscqk",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 成果管理表格数据
      wjscqkList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: null,
        xmid: null,
        wjmc: null,
        zllx: null,
        wjlj: null,
        createdBy: null,
        createdTime: null,
        ext1: null,
        ext2: null,
        ext3: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      // 资料类型选项
      zllxOptions: [],
      // 文件列表
      fileList: [],
      // 上传配置
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      uploadHeaders: {
        Authorization: "Bearer " + getToken()
      },
      uploadData: {}
    }
  },
  created() {
    // 获取路由参数中的id
    if (this.$route.query.xmid) {
      this.queryParams.xmid = this.$route.query.xmid
    }
    this.getList()
    this.getZllxOptions()
  },
  watch: {
    // 监听路由参数变化
    '$route.query.xmid'(newId) {
      if (newId) {
        this.queryParams.xmid = newId
        this.getList()
      }
    }
  },
  methods: {
    /** 查询成果管理列表 */
    getList() {
      console.log(this.queryParams.xmid,6666);
      this.loading = true
      listWjscqk(this.queryParams).then(response => {
        const mergedRows = this.mergeRowsById(response.rows || [])
        this.wjscqkList = mergedRows
        this.total = mergedRows.length
        this.loading = false
      })
    },
      /** 将相同id的记录进行合并（合并文件名与文件路径） */
      mergeRowsById(rows) {
        const idToRowMap = {}
        const mergeCommaSeparated = (first, second) => {
          const parts = []
          if (first) parts.push(...String(first).split(',').filter(Boolean))
          if (second) parts.push(...String(second).split(',').filter(Boolean))
          const seen = new Set()
          return parts.filter(item => {
            if (seen.has(item)) return false
            seen.add(item)
            return true
          }).join(',') || null
        }
        rows.forEach(row => {
          const key = row.id
          if (key == null) {
            // 无id的记录直接保留为独立项
            const tempKey = `__no_id__${Math.random()}_${Date.now()}`
            idToRowMap[tempKey] = { ...row }
            return
          }
          if (!idToRowMap[key]) {
            idToRowMap[key] = { ...row }
          } else {
            const existing = idToRowMap[key]
            existing.wjmc = mergeCommaSeparated(existing.wjmc, row.wjmc)
            existing.wjlj = mergeCommaSeparated(existing.wjlj, row.wjlj)
            // 其它字段保持首次出现的值，或可在此按需处理
          }
        })
        return Object.values(idToRowMap)
      },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        xmid: null,
        wjmc: null,
        zllx: null,
        wjlj: null,
        createdBy: null,
        createdTime: null,
        updateBy: null,
        updateTime: null,
        ext1: null,
        ext2: null,
        ext3: null
      }
      this.fileList = []
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      // 设置xmid参数
      if (this.queryParams.xmid) {
        this.form.xmid = this.queryParams.xmid
      }
      this.open = true
      this.title = "添加成果管理"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getWjscqk(id).then(response => {
        this.form = response.data
        // 确保xmid参数被保持
        if (this.queryParams.xmid) {
          this.form.xmid = this.queryParams.xmid
        }
        // 如果有文件信息，加载到文件列表中（单文件）
        if (this.form.wjmc && this.form.wjlj) {
          this.fileList = [{
            name: this.form.wjmc,
            url: this.form.wjlj,
            status: 'success',
            uid: Date.now()
          }]
        }
        this.open = true
        this.title = "修改成果管理"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateWjscqk(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addWjscqk(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除成果管理编号为"' + ids + '"的数据项？').then(function () {
        return delWjscqk(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => { })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('yscgWjscqk/wjscqk/export', {
        ...this.queryParams
      }, `wjscqk_${new Date().getTime()}.xlsx`)
    },
    /** 获取资料类型选项 */
    getZllxOptions() {
      selectZllx().then(response => {
        this.zllxOptions = response.rows || []
      }).catch(() => {
        this.zllxOptions = []
      })
    },
    /** 上传前校验 */
    handleBeforeUpload(file) {
      // 校验文件类型
      const allowedTypes = ['doc', 'docx', 'pdf', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'jpg', 'jpeg', 'png', 'gif']
      const fileExt = file.name.split('.').pop().toLowerCase()
      if (!allowedTypes.includes(fileExt)) {
        this.$modal.msgError('文件格式不正确，请上传支持的文件格式！')
        return false
      }
      
      // 校验文件大小
      const isLt50M = file.size / 1024 / 1024 < 50
      if (!isLt50M) {
        this.$modal.msgError('上传文件大小不能超过 50MB!')
        return false
      }
      
      return true
    },
    /** 文件状态改变 */
    handleFileChange(file, fileList) {
      // 如果文件列表超过1个，只保留最新的文件
      if (fileList.length > 1) {
        this.fileList = [fileList[fileList.length - 1]]
      } else {
        this.fileList = fileList
      }
      this.updateFormFiles()
    },
    /** 上传成功 */
    handleUploadSuccess(response, file, fileList) {
      this.fileList = fileList
      this.updateFormFiles()
      this.$modal.msgSuccess('文件上传成功')
    },
    /** 上传失败 */
    handleUploadError(err, file, fileList) {
      this.$modal.msgError('文件上传失败')
    },
    /** 删除文件 */
    handleRemove(file, fileList) {
      this.fileList = fileList
      this.updateFormFiles()
    },
    /** 文件数量超出限制 */
    handleExceed(files, fileList) {
      // 由于已实现自动替换，此方法不再需要显示错误提示
      // 新文件会自动替换旧文件
    },
    /** 更新表单文件信息 */
    updateFormFiles() {
      if (this.fileList && this.fileList.length > 0) {
        // 单文件上传，直接取第一个文件
        const file = this.fileList[0]
        this.form.wjmc = file.name
        this.form.wjlj = file.response ? file.response.url : file.url
      } else {
        this.form.wjmc = null
        this.form.wjlj = null
      }
    }
  }
}
</script>
