<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="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入主键"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="会议id" prop="hyid">
        <el-input
          v-model="queryParams.hyid"
          placeholder="请输入会议id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      
      <el-form-item label="附件名字" prop="fileName">
        <el-input
          v-model="queryParams.fileName"
          placeholder="请输入附件名字"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="附件时间" prop="fileTime">
        <el-date-picker clearable
          v-model="queryParams.fileTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择附件时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="创建人" prop="createdBy">
        <el-input
          v-model="queryParams.createdBy"
          placeholder="请输入创建人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createdTime">
        <el-date-picker clearable
          v-model="queryParams.createdTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="备用1" prop="ext1">
        <el-input
          v-model="queryParams.ext1"
          placeholder="请输入备用1"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="备用2" prop="ext2">
        <el-input
          v-model="queryParams.ext2"
          placeholder="请输入备用2"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="备用3" prop="ext3">
        <el-input
          v-model="queryParams.ext3"
          placeholder="请输入备用3"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </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-form-item>
    </el-form> -->

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['hyjyxxFile:file:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['hyjyxxFile:file:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['hyjyxxFile:file:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['hyjyxxFile:file:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="fileList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="60" align="center" />
      <el-table-column label="缩略图" align="center">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.fileUrl"
            :src="getImageUrl(scope.row.fileUrl)"
            :preview-src-list="[getImageUrl(scope.row.fileUrl)]"
            fit="cover"
            style="width: 80px; height: 80px; cursor: pointer;"
            lazy
          >
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
          <span v-else>暂无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="附件时间" align="center" prop="fileTime" width="280">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.fileTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['hyjyxxFile:file:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['hyjyxxFile:file: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="100px">
        <!-- 图片上传 -->
        <el-form-item label="附件图片" prop="fileUrl">
          <el-upload
            :headers="upload.headers"
            :action="upload.url"
            :auto-upload="true"
            accept="image/*"
            :on-success="handleImageSuccess"
            :on-error="handleImageError"
            :on-remove="handleImageRemove"
            :on-change="handleImageChange"
            :file-list="imageFileList"
            list-type="picture-card"
          >
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">支持 jpg/png/gif 格式，大小不超过 10MB（上传新文件将自动替换已有文件）</div>
          </el-upload>
        </el-form-item>
        <!-- 附件时间 -->
        <el-form-item label="附件时间" prop="fileTime">
          <el-date-picker
            clearable
            v-model="form.fileTime"
            type="datetime"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择附件时间"
            style="width: 100%;"
          >
          </el-date-picker>
        </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 { listFile, getFile, delFile, addFile, updateFile } from "@/api/hyjyxxFile/file"
import { getToken } from "@/utils/auth"

export default {
  name: "File",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 会议纪要_附件表格数据
      fileList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 图片上传配置
      upload: {
        headers: { Authorization: "Bearer " + getToken() },
        url: process.env.VUE_APP_BASE_API + "/common/upload"
      },
      // el-upload 图片文件列表（用于编辑时回显）
      imageFileList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: null,
        hyid: null,
        fileUrl: null,
        fileName: null,
        fileTime: null,
        createdBy: null,
        createdTime: null,
        ext1: null,
        ext2: null,
        ext3: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        fileUrl: [
          { required: true, message: "请上传附件图片", trigger: "change" }
        ],
        fileTime: [
          { required: true, message: "请选择附件时间", trigger: "change" }
        ]
      }
    }
  },
  created() {
    // 获取路由参数中的hyid，用于过滤数据
    if (this.$route.query.hyid) {
      this.queryParams.hyid = this.$route.query.hyid
    }
    this.getList()
  },
  methods: {
    /** 查询会议纪要_附件列表 */
    getList() {
      this.loading = true
      listFile(this.queryParams).then(response => {
        this.fileList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        hyid: null,
        fileUrl: null,
        fileName: null,
        fileTime: null,
        createdBy: null,
        createdTime: null,
        updateBy: null,
        updateTime: null,
        ext1: null,
        ext2: null,
        ext3: null
      }
      this.resetForm("form")
      this.imageFileList = []
    },
    /** 搜索按钮操作 */
    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()
      // 如果存在hyid参数，自动填充到表单中
      if (this.queryParams.hyid) {
        this.form.hyid = this.queryParams.hyid
      }
      this.open = true
      this.title = "添加会议纪要附件"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getFile(id).then(response => {
        this.form = response.data
        // 回显已上传的图片
        this.imageFileList = []
        if (this.form && this.form.fileUrl) {
          this.imageFileList = [{
            name: this.form.fileName || this.getFileName(this.form.fileUrl),
            url: this.getImageUrl(this.form.fileUrl)
          }]
        }
        this.open = true
        this.title = "修改会议纪要附件"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const payload = { ...this.form }
          // 如果附件时间是Date对象，转换为字符串
          if (payload.fileTime instanceof Date) {
            payload.fileTime = this.parseTime(payload.fileTime, '{y}-{m}-{d} {h}:{i}:{s}')
          }
          if (this.form.id != null) {
            updateFile(payload).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addFile(payload).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    // 图片上传成功
    handleImageSuccess(response, file) {
      if (response && response.code === 200) {
        // 后端返回的文件名或url字段可能为 fileName/url
        this.form.fileUrl = response.fileName || response.url || ""
        // 取文件名用于显示/保存到 fileName
        this.form.fileName = response.originalFilename || ""
        // 更新图片文件列表中的URL（on-change已经更新了文件列表，这里只需要更新URL）
        if (this.imageFileList.length > 0) {
          const latestFile = this.imageFileList[this.imageFileList.length - 1]
          latestFile.url = this.getImageUrl(this.form.fileUrl)
        }
        this.$modal.msgSuccess("上传成功")
      } else {
        this.$modal.msgError((response && response.msg) || "上传失败")
      }
    },
    // 图片上传失败
    handleImageError() {
      this.$modal.msgError("上传失败，请重试")
    },
    // 图片移除（用于自动替换时清空旧文件）
    handleImageRemove() {
      this.form.fileUrl = null
      this.form.fileName = null
      this.imageFileList = []
    },
    // 图片文件状态改变（实现自动替换）
    handleImageChange(file, fileList) {
      // 如果文件列表超过1个，只保留最新的文件
      if (fileList.length > 1) {
        this.imageFileList = [fileList[fileList.length - 1]]
      } else {
        this.imageFileList = fileList
      }
    },
    // 获取图片绝对地址
    getImageUrl(path) {
      if (!path) return ""
      if (/^https?:\/\//i.test(path)) return path
      const base = process.env.VUE_APP_BASE_API || ""
      return `${base}${path}`
    },
    getFileName(fullPath) {
      if (!fullPath) return ""
      const idx = fullPath.lastIndexOf('/')
      return idx >= 0 ? fullPath.slice(idx + 1) : fullPath
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除会议纪要_附件编号为"' + ids + '"的数据项？').then(function() {
        return delFile(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('hyjyxxFile/file/export', {
        ...this.queryParams
      }, `file_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>