<template>
  <el-dialog :title="title" append-to-body :modelValue="openShow" width="70%" @close="closeDialog">
    <div style="margin-bottom: 12px" v-if="moldAddMore">
      <el-button type="primary" @click="addTable">插入一行</el-button>
      <el-button type="danger" @click="delTable">删除选中行</el-button>
    </div>
    <!-- 单个 Form 包裹整个表格 -->
    <el-form ref="tableForm" :model="form" :rules="formRules" label-width="0px">
      <!-- 全局错误提示 -->
      <div v-if="formError" class="error-message" style="color: #f56c6c; margin-bottom: 10px">
        {{ formError }}
      </div>
      <el-table :data="form.tableData" @select="selectChange" border>
        <el-table-column type="selection" width="55"></el-table-column>
        <!-- 绩效任务名称 -->
        <el-table-column align="center" label="绩效任务名称">
          <template #header>
            <span><i style="color: red">*</i>绩效任务名称</span>
          </template>
          <template #default="scope">
            <el-form-item :prop="`tableData[${scope.$index}].taskName`" :rules="formRules.taskName">
              <el-input v-model="scope.row.taskName" placeholder="请输入"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <!-- 绩效填报人 -->
        <el-table-column align="center" label="绩效填报人">
          <template #header>
            <span><i style="color: red">*</i>绩效填报人</span>
          </template>
          <template #default="scope">
            <el-form-item
              :prop="`tableData[${scope.$index}].reportUser`"
              :rules="formRules.reportUser"
            >
              <el-select
                v-model="scope.row.reportUser"
                placeholder="请选择绩效填报人"
                filterable
                                remote
                reserve-keyword
                :remote-method="remoteMethod"
                :loading="loading"
              >
                <el-option
                  v-for="item in userData"
                  :key="item.id"
                  :label="item.realName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { submitBsEfficiencyTemp } from '@/api/performanceManagement/templateMaintenance';
import { getList } from '@/api/system/user';
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false,
    },
    moldAddMore: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: '',
    },
    checkRow: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      openShow: false,
      formError: '',
      form: {
        tableData: [],
      },
      loading: false,
      userData: [],
      formRules: {
                // 表格数据数组的整体校验（可选：如最少1行数据）
        tableData: [
          {
            required: true,
            message: '请至少添加一行数据',
            trigger: 'submit',
            type: 'array', // 明确类型为数组
          },
          {
            validator: (rule, value, callback) => {
              if (value.length === 0) {
                callback(new Error('请至少添加一行数据'));
              } else {
                callback();
              }
            },
            trigger: 'submit',
          },
        ],
         // 数组中每一项的 wcId 字段校验
        taskName: [
          { required: true, message: '请输入绩效任务名称', trigger: ['change', 'submit'] },
        ],
         // 数组中每一项的 wcId 字段校验
        reportUser: [
          { required: true, message: '请选择绩效填报人', trigger: ['change', 'submit'] },
        ],
      },
      detailRow: {},
    };
  },
  created() {
    this.openShow = this.showDialog;
    // 先赋值 detailRow，再调用远程方法！
    if (this.title == '新增') {
      this.form.tableData = [];
      this.addTable();
    } else {
      this.detailRow = JSON.parse(JSON.stringify(this.checkRow));
      this.form.tableData = [];
      this.form.tableData.push(this.detailRow);
    }
    // 最后再加载用户列表！！！
    this.remoteMethod('');
  },
  methods: {
    closeDialog(val) {
      this.openShow = false;
      this.$emit('closeDialog', val);
    },
    addTable() {
      this.form.tableData.push({
        _select: false,
        taskName: '',
        reportUser: '',
      });
    },
    selectChange(list, row) {
      row._select = !row._select;
    },
    // 删除选中行
    delTable() {
      this.form.tableData = this.form.tableData.filter(row => !row._select);
    },
    // 远程搜索方法
    remoteMethod(query) {
      this.loading = true;
      const page = { currentPage: 1, pageSize: 500 };
      const queryParams = Object.assign({}, this.query || {}, {
        status: this.auditMode ? 0 : 1,
        userName: query,
      });
      getList(page.currentPage, page.pageSize, queryParams)
        .then(res => {
          const data = res.data.data;
          this.userData = data.records;
          if (this.detailRow.reportUser){
            // 判断：如果id不在数组里，就插入到第一个
            const hasItem = this.userData.some(item => item.id == this.detailRow.reportUser);
            if (!hasItem) {
              // 插入到数组最前面
              this.userData.unshift({
                id: this.detailRow.reportUser,
                realName: this.detailRow.reportUserName,
              });
            }
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 提交表单（单次校验所有行）
    submitForm() {
      this.formError = '';
      // 调用单个 Form 的校验方法
      this.$refs.tableForm.validate((isValid, invalidFields) => {
        if (!isValid) {
          // 校验失败：显示提示并滚动到第一个错误字段
          this.formError = '存在未完善的字段，请检查表格中的红色提示';
          this.$nextTick(() => {
            // 找到第一个错误字段并滚动到视图
            const firstError = document.querySelector('.el-form-item.is-error');
            if (firstError) {
              firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
            }
          });
          return;
        }
        // 校验通过：准备提交数据（过滤无用字段）
        const submitData = this.form.tableData.map(row => {
          const { _select, ...validData } = row; // 剔除选择状态字段
          return validData;
        });
        if (this.title == '新增') {
          submitBsEfficiencyTemp(submitData).then(res => {
            if (res.data.code == 200) {
              this.$message.success('新增成功');
              this.closeDialog(true);
            }
          });
        } else {
          submitBsEfficiencyTemp(submitData).then(res => {
            if (res.data.code == 200) {
              this.$message.success('修改成功');
              this.closeDialog(true);
            }
          });
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
// 优化表单字段样式
:deep(.el-table .el-form-item) {
  margin-bottom: 0; // 去掉默认边距
}

// 错误提示样式优化
:deep(.el-form-item__error) {
  font-size: 12px;
  white-space: nowrap;
  z-index: 10;
  background: #fff;
  padding: 2px 4px;
  border: 1px solid #f56c6c;
  border-radius: 4px;
}

// 表格行高适配 textarea
.el-table__row {
  height: 80px !important;
}

.el-table__cell {
  vertical-align: middle !important;
}

.error-message {
  font-size: 14px;
  line-height: 1.5;
}
:deep(.el-table .el-table__cell) {
  height: 50px !important;
  padding: 0 !important;
  line-height: 50px !important;
}
</style>