<template>
  <el-dialog
    :visible.sync="visible"
    width="80%"
    top="5vh"
    append-to-body
    @close="close"
  >
    <!-- 动态统一录入区 -->
    <el-row slot="title" class="batch-header">
      <span>批量修改</span>
    </el-row>
    <el-row>
      <el-form inline size="mini">
        <el-form-item label=" " />
        <el-form-item
          v-for="field in dynamicInputs"
          :key="field.paramName"
          :label="field.paramComment"
        >
          <el-input
            v-model="globalMap[field.paramName]"
            :placeholder="'统一' + field.paramComment"
            style="width: 140px"
            @input="syncGlobal(field.paramName)"
          />
        </el-form-item>
      </el-form>
    </el-row>

    <!-- 表格：每行就是原来的一条记录，列=所有字段 -->
    <el-table
      ref="multipleTable"
      :data="tableData"
      border
      size="mini"
      max-height="450"
      @selection-change="handleSelectionChange"
    >
      <!-- 1. 表格内置多选框 -->
      <el-table-column type="selection" width="55" align="center" />

      <!-- 2. 其余字段列 -->
      <el-table-column
        v-for="col in allCol"
        :key="col.paramName"
        :label="col.paramComment"
        show-overflow-tooltip
      >
        <template slot-scope="{ row }">
          <el-input
            v-model="row[col.paramName]"
            size="mini"
            :disabled="!col.allowEdit"
          />
        </template>
      </el-table-column>
    </el-table>

    <div slot="footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :loading="loading" @click="submit"
        >确 定</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
import request from "@/utils/request";

export default {
  name: "ParameterBatch",
  data() {
    return {
      visible: false,
      loading: false,
      tableData: [], // 多条记录
      allCol: [], // 所有字段（含只读）
      buttonInfo: {},
      masterId: "",
      globalMap: {}, // 每个字段一个统一值  { paramName: value }
      dynamicInputs: [], // 需要出输入框的字段
      selectedRows: [], // 表格勾选的行数据
    };
  },
  methods: {
    /* 打开弹窗
     * btn: 当前按钮配置
     * masterId: 主表 id
     * rows: 被勾选的原始行数据
     * queryData: 父组件的列配置，用于把列注释映射到字段
     */
    open(btn, masterId, rows, queryData) {
      this.buttonInfo = btn;
      this.masterId = masterId;
      // 1. 表格列（过滤隐藏）
      this.allCol = (btn.paramList || []).filter((p) => p.ifHide !== true);

      // 2. 顶部动态输入框字段：未隐藏 且 可编辑
      this.dynamicInputs = this.allCol.filter((p) => p.allowEdit === true);

      // 3. 初始化 globalMap
      this.globalMap = this.dynamicInputs.reduce((acc, f) => {
        acc[f.paramName] = "";
        return acc;
      }, {});

      // 4. 表格数据
      this.tableData = rows.map((r) => {
        const obj = {};
        this.allCol.forEach((p) => {
          const commentKey = queryData?.find(
            (q) => q.id === p.columnId
          )?.columnComment;
          obj[p.paramName] = commentKey ? r[commentKey] : "";
        });
        return obj;
      });
      this.selectedRows = []; // 初始清空
      this.visible = true;
    },

    /* el-table 勾选事件 */
    handleSelectionChange(val) {
      this.selectedRows = val;
    },

    /* 仅对已勾选的行赋值 */
    syncGlobal(fieldName) {
      if (!this.selectedRows.length) return;
      const val = this.globalMap[fieldName];
      this.selectedRows.forEach((row) => {
        row[fieldName] = val;
      });
    },

    close() {
      this.visible = false;
      this.tableData = [];
      this.globalMap = {};
      this.dynamicInputs = [];
      this.selectedRows = [];
    },

    /* 一次性提交整包数组 */
    async submit() {
      this.loading = true;
      try {
        // 组装成后端需要的结构：List<Map<paramName, value>>
        const payload = this.tableData.map((row) =>
          this.allCol.reduce((acc, p) => {
            acc[p.paramName] = row[p.paramName] ?? "";
            return acc;
          }, {})
        );

        // 如果后端只能单条，就循环；支持数组就直接发
        const { restMethod = "post", interfaceUrl } = this.buttonInfo;
        await request({
          method: restMethod,
          url: interfaceUrl,
          data: payload, // 整包数组
        });

        this.$message.success("批量保存成功");
        this.close();
        this.$emit("success");
      } catch (e) {
        this.$message.error(e.message || "保存失败");
      } finally {
        this.loading = false;
      }
    },
  },
};
</script>

<style scoped>
.batch-header {
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
}

.batch-header .el-form {
  display: flex;
  align-items: center;
}

.batch-header .el-form-item {
  margin-right: 15px;
  margin-bottom: 0;
}
</style>
