<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="tzdl">
        <el-input v-model="queryParams.tzdl" placeholder="请输入特征大类" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="特征名称" prop="tzxl">
        <el-input v-model="queryParams.tzxl" placeholder="请输入特征名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="特征代码" prop="tzdm">
        <el-input v-model="queryParams.tzdm" placeholder="请输入特征代码" 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-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:ztxxTzsj:add']">新增</el-button>
      </el-form-item>
    </el-form>


    <el-table border v-loading="loading" :data="ztxxTzsjList" @selection-change="handleSelectionChange"
      style="width: 100%" height="calc(100vh - 240px)">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="特征大类" align="center" min-width="100" prop="tzdl" />
      <el-table-column label="特征类型" align="center" min-width="100" prop="tzxl" />
      <el-table-column label="特征代码" align="center" min-width="100" prop="tzdm" />
      <el-table-column label="示例图" align="center" min-width="200" prop="slt">
        <template slot-scope="scope">
          <el-image style="width: 80px; height: 50px" :src="scope.row.slt" :preview-src-list="[scope.row.slt]"
            fit="cover">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="操作" 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="['system:ztxxTzsj:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:ztxxTzsj: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="80px">
        <el-form-item label="特征大类" prop="tzdl">
          <el-select v-model="form.tzdl" placeholder="请选择特征大类" style="width: 480px;">
            <el-option v-for="dict in dict.type.zttzlx" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="特征类型" prop="tzxl">
          <el-input v-model="form.tzxl" placeholder="请输入特征名称" />
        </el-form-item>
        <el-form-item label="特征代码" prop="tzdm">
          <el-input v-model="form.tzdm" placeholder="请输入特征代码" />
        </el-form-item>
        <el-form-item label="示例图" prop="slt">
          <el-upload ref="uploadRef" class="avatar-uploader" :action="uploadUrl" :headers="headers"
            :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :limit="1"
            :on-exceed="handleExceed">
            <img v-if="form.slt" :src="form.slt" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <el-button v-if="form.slt" size="mini" type="danger" style="margin-top: 10px;"
            @click="handleRemoveImage">删除图片</el-button>
        </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 { listZtxxTzsj, getZtxxTzsj, delZtxxTzsj, addZtxxTzsj, updateZtxxTzsj } from "@/api/system/ztxxTzsj";
import { getToken } from "@/utils/auth";

export default {
  name: "ZtxxTzsj",
  dicts: ['zttzlx'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 特征数据表格数据
      ztxxTzsjList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        tzdl: null,
        tzxl: null,
        tzdm: null,
        slt: null
      },
      // 表单参数
      form: {},
      // 图片上传配置
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken()
      },
      // 表单校验
      rules: {
        tzdl: [
          { required: true, message: "特征大类不能为空", trigger: "change" }
        ],
        tzxl: [
          { required: true, message: "特征类型不能为空", trigger: "blur" }
        ],
        tzdm: [
          { required: true, message: "特征代码不能为空", trigger: "blur" }
        ],
        slt: [
          { required: true, message: "示例图不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询特征数据列表 */
    getList() {
      this.loading = true;
      listZtxxTzsj(this.queryParams).then(response => {
        this.ztxxTzsjList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        tzdl: null,
        tzxl: null,
        tzdm: null,
        createTime: null,
        remark: null,
        slt: null
      };
      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();
      this.open = true;
      this.title = "添加特征数据";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getZtxxTzsj(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改特征数据";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateZtxxTzsj(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addZtxxTzsj(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 delZtxxTzsj(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/ztxxTzsj/export', {
        ...this.queryParams
      }, `ztxxTzsj_${new Date().getTime()}.xlsx`)
    },

    /** 图片上传成功处理 */
    handleAvatarSuccess(res, file) {
      if (res.code === 200) {
        this.form.slt = 'https://10.68.249.114:8088/pdc-api' + res.fileName;
        this.$refs.uploadRef.clearFiles(); // 关键：上传成功后清空文件列表
        this.$modal.msgSuccess("上传成功");
      } else {
        this.$modal.msgError("上传失败");
      }
    },
    /** 文件超出个数限制时的钩子 */
    handleExceed(files, fileList) {
      this.$message.warning("只能上传一张图片，如需更换请先删除当前图片");
    },

    /** 上传前图片格式大小校验 */
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
        return false;
      }
      // 不再做“只能上传一张图片”的判断，交给 handleAvatarSuccess 统一清理
      return true;
    },
    /** 删除图片按钮操作 */
    handleRemoveImage() {
      this.$refs.uploadRef.clearFiles();
      this.form.slt = null;
      this.$message.success('图片已删除');
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-table--medium .el-table__cell {
  padding: 2px 0 !important;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
