<template>
  <div>
    <Card :bordered="false" style="background-color: #E5F1FF;">
        <Row>
            <Col span="5">姓名：{{keyPersonUser.name}}</Col>
            <Col span="5">性别：{{ keyPersonUser.sex }}</Col>
            <Col span="5">身份证号：{{ keyPersonUser.card_no }}</Col>
            <Col span="4">民族：{{ keyPersonUser.folk }}</Col>
            <Col span="5">本人联系方式：{{ keyPersonUser.phone }}</Col>
        </Row>
    </Card>
    <div class="header-container" v-if="this.params.isHide">
        <div class="title-wrapper">
            <div class="title-bar"></div>
            <h3 class="title-text">本次评分</h3>
        </div>
    </div>
      <Table border :columns="columns" :data="dataList" v-if="this.params.isHide">
        <template slot-scope="{ row, index }" slot="select">
            <RadioGroup v-model="dataList[index].is_whether">
                <Radio label="1">有</Radio>
                <Radio label="2">无</Radio>
            </RadioGroup>
        </template>
        <template slot-scope="{ row, index }" slot="score">
            <InputNumber v-model="dataList[index].details" min="dataList[index].min_num" max="dataList[index].max_num" :placeholder="dataList[index].min_num + '至' + dataList[index].max_num" :disabled="dataList[index].is_whether === '2'"></InputNumber>
        </template>
        <template slot-scope="{ row, index }" slot="remarks">
            <Input v-model="dataList[index].remarks" placeholder="请填写备注" :disabled="dataList[index].is_whether === '2'"></Input>
        </template>
      </Table>
      <div class="disputetype" style="padding: 10px;" v-if="this.params.isHide">
        <div>
          <Row type="flex" class="">
              <Col span="10">
                <span>参会人员：</span>
                <Input v-model="ratingUsers" placeholder="请输入" style="width: 65%"/>
              </Col>
              <Col span="10">
                <span>评分时间：</span>
                <DatePicker type="datetime" v-model="ratingTime" format="yyyy-MM-dd HH:mm:ss"></DatePicker>
              </Col>
          </Row>
        </div>
      </div>
      <div style="display: flex; justify-content: center; gap: 10px; margin-top: 20px;" v-if="loding">
        <Poptip confirm title="确认提交？" placement="top" transfer @on-ok="saveRating">
          <Button type="primary" style="margin-top: 20px;" v-if="this.params.isHide">提交</Button>
        </Poptip>
        <Button style="margin-top: 20px;" @click="$router.go(-1)">返回</Button>
      </div>
      <div class="header-container">
        <div class="title-wrapper">
            <div class="title-bar"></div>
            <h3 class="title-text">本次历史评分</h3>
        </div>
    </div>
      <Table border :columns="summaryColumns" :data="SummaryRatingDetailsList" style="margin-top: 20px;">
        <template slot-scope="{ row, index }" slot="action">
          <Button type="info" size="small" style="margin-right: 5px" @click="showSummaryRatingDetail(row)" >详情</Button>
        </template>
      </Table>
      <Page class="page_style" :total="params.totalRecord" :current="params.pageNo" :page-size="params.pageSize" @on-change="changePageNo" show-total show-sizer @on-page-size-change="size" />
      <Modal footer-hide v-model="indicatory" :title="modalName" width="900" >
         <Table border :columns="SummaryRatingDetailsListColumns" :data="SummaryDetailsList"></Table>
      </Modal>
    <Modal
      v-model="showErrorModal"
      title="校验错误"
      width="500px"
      :closable="false"
    >
      <div style="max-height: 300px; overflow-y: auto; padding: 10px;">
        <ul style="margin: 0; padding-left: 20px;">
          <!-- 循环展示所有错误信息 -->
          <li v-for="(error, index) in errorList" :key="index" style="color: #ff4d4f; margin: 8px 0;">
            {{ error }}
          </li>
        </ul>
      </div>
      <div slot="footer">
        <Button @click="showErrorModal = false">确认</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import {
  selectRatingDictList, // 查询评分项
  getKeyPersonUser, // 查询重点人员信息
  saveRatingDetails, // 添加分数
  selectRatingSummaryByPersonIdList, // 评分详情
  selectSummaryRatingDetailsList // 历史详情
} from '@/api/key-person'
import xeUtil from 'xe-utils'
export default {
  data () {
    return {
      formItem: {}, // 存储每行的选择（键为行索引）
      keyPersonUser: {},
      loding: true,
      SummaryRatingDetailsList: [],
      SummaryDetailsList: [],
      modalName: '',
      params: this.$route.params,
      pageParams: {
        pageNo: 1,
        pageSize: 10,
        totalRecord: 0
      },
      columns: [
        { title: '序号', type: 'index', width: 70, align: 'center' },
        { title: '评估类别', key: 'evaluate_type', minWidth: 100, align: 'center' },
        { title: '评估选项', key: 'scoring_project', minWidth: 220, align: 'center' },
        { title: '选择', slot: 'select', align: 'center' },
        { title: '分值', slot: 'score', align: 'center' },
        { title: '备注', slot: 'remarks', align: 'left' }
      ],
      dataList: [],
      SummaryRatingDetailsListColumns: [
        { title: '序号', type: 'index', width: 70, align: 'center' },
        { title: '评估类别', key: 'evaluate_type', minWidth: 100, align: 'center' },
        { title: '评估选项', key: 'scoring_project', minWidth: 220, align: 'center' },
        { title: '选择', key: 'is_whether', align: 'center' },
        { title: '分值', key: 'details', align: 'center' },
        { title: '备注', key: 'rating_remarks', align: 'left' }
      ],
      indicatory: false,
      summaryColumns: [
        { title: '序号', type: 'index', width: 70, align: 'center' },
        { title: '评分人员', key: 'rating_personnel', minWidth: 100, align: 'center' },
        { title: '评分部门', key: 'rating_company', minWidth: 100, align: 'center' },
        { title: '参会人员', key: 'rating_users', minWidth: 100, align: 'center' },
        { title: '评分时间', key: 'rating_time', minWidth: 100, align: 'center' },
        { title: '评分风险等级', key: 'rating_type', minWidth: 100, align: 'center' },
        { title: '分数', key: 'rating', minWidth: 100, align: 'center' },
        { title: '操作', slot: 'action', align: 'center' }
      ],
      showErrorModal: false, // 控制错误弹窗显示/隐藏
      errorList: [], // 存储所有错误信息
      ratingUsers: '', // 存储参会人员
      ratingTime: '' // 存储评分时间
    }
  },
  methods: {
    init () {
      this.ratingTime = xeUtil.toDateString(new Date(), 'yyyy-MM-dd HH:mm:ss')
      selectRatingDictList({ rating_dict_type: this.params.ratingDictType }).then((ret) => {
        if (ret.data.errcode === 0) {
          // this.dataList = ret.data.data
          ret.data.data.forEach(item => {
            this.dataList.push({
              ...item, // 继承原始数据中的字段（如 min_num、max_num）
              is_whether: '1', // 默认选中“有”
              details: null // 初始化详情为空
            })
          })
        } else {
          this.$Notice.error({ title: '查询失败！', desc: ret.data.errmsg })
        }
      })
      getKeyPersonUser(this.params).then((ret) => {
        if (ret.data.errcode === 0) {
          this.keyPersonUser = ret.data.data
        } else {
          this.$Notice.error({ title: '查询失败！', desc: ret.data.errmsg })
        }
      })
    },
    summaryByPerson () {
      this.pageParams.id = this.params.id
      this.pageParams.rating_history_id = this.params.historyId
      // 评分完成重新查询一下历史id
      selectRatingSummaryByPersonIdList(this.pageParams).then((ret) => {
        if (ret.data.errcode === 0) {
          this.params.totalRecord = ret.data.data.totalRecord
          this.SummaryRatingDetailsList = ret.data.data.results
        } else {
          this.$Notice.error({ title: '查询失败！', desc: ret.data.errmsg })
        }
      })
    },
    size (pageSize) {
      this.pageParams.pageSize = pageSize
      this.changePageNo(1)
    },
    changePageNo (pageNo) {
      this.pageParams.pageNo = pageNo
      this.summaryByPerson(this.params)
    },
    showSummaryRatingDetail (row) {
      this.modalName = '历史评分（' + String(row.rating_custom_time == null ? row.rating_time : row.rating_custom_time) + '）' + (row.rating_users == null ? '' : '参会人员(' + row.rating_users + ')')
      this.indicatory = true
      selectSummaryRatingDetailsList({ key_person_rating_summary_id: row.id }).then((ret) => {
        if (ret.data.errcode === 0) {
          this.SummaryDetailsList = ret.data.data
        } else {
          this.$Notice.error({ title: '查询失败！', desc: ret.data.errmsg })
        }
      })
    },
    // 1. 新增：表单校验方法
    // 1. 修改校验方法：收集所有错误信息
    validateForm () {
      this.errorList = [] // 清空历史错误
      this.dataList.forEach((item, index) => {
        if (item.is_whether === '1') {
          // 空值校验
          if (item.details === null || item.details === undefined) {
            this.errorList.push(
              `第${index + 1}项【${item.scoring_project}】选择“有”，请填写分值`
            )
          } else if (item.details < item.min_num || item.details > item.max_num) {
            // 范围校验（仅在有值时检查，避免空值重复提示）
            this.errorList.push(
              `第${index + 1}项【${item.scoring_project}】分值需在${item.min_num}-${item.max_num}之间`
            )
          } else if (item.remarks === null || item.remarks === undefined || item.remarks.trim() === '') {
            // 备注空值校验
            this.errorList.push(
              `第${index + 1}项【${item.scoring_project}】选择“有”，请填写备注`
            )
          }
        }
      })
      if (this.ratingUsers === null || this.ratingUsers === undefined || this.ratingUsers.trim() === '') {
        this.errorList.push(`请填写参会人员`)
      }
      if (this.ratingTime === null || this.ratingTime === undefined || this.ratingTime === '') {
        this.errorList.push(`请填写评分时间`)
      }
      // 若有错误，显示弹窗；否则返回校验通过
      if (this.errorList.length > 0) {
        this.showErrorModal = true
        return false
      }
      return true
    },
    // 2. 修改：提交方法（先校验，再提交）
    // 2. 提交方法（逻辑不变，依赖上述校验）
    saveRating () {
      if (!this.validateForm()) {
        return // 校验失败，终止提交
      }
      // 原有提交逻辑不变...
      this.loding = false
      const ratingDetailsList = this.dataList
      // 第二步：筛选数据——仅保留 is_whether = '1'（有）的项，其他不传给后台
      // const ratingDetailsList = this.dataList.filter(item => {
      //   return item.is_whether === '1' // 只保留“有”的记录
      // })
      this.params.ratingDetailsList = ratingDetailsList
      this.params.ratingUsers = this.ratingUsers
      this.params.ratingTime = this.ratingTime
      saveRatingDetails(this.params).then((ret) => {
        if (ret.data.errcode === 0) {
          this.$Notice.success({ title: '评分成功' })
          this.summaryByPerson()
        } else {
          this.$Notice.error({ title: '评分失败', desc: ret.data.errmsg })
        }
        this.loding = true
      }).catch(() => {
        this.loding = true
        this.$Notice.error({ title: '网络异常', desc: '请稍后重试' })
      })
    }
  },
  mounted () {
    // this.severUserInfo = this.$store.state.user.severUserInfo
    this.init()
    this.summaryByPerson()
  }
}
</script>

<style scoped>
.header-container {
  margin-bottom: 16px; /* 可选：调整与下方内容的间距 */
  margin-top: 10px;
}

.title-wrapper {
  display: flex;
  align-items: center; /* 垂直居中 */
}

.title-bar {
  width: 4px;
  height: 16px;
  background-color: #2d8cf0; /* iView 主色调蓝色 */
  margin-right: 8px; /* 调整与文字的间距 */
}

.title-text {
  margin: 0;
  font-size: 16px;
  font-weight: bold;
  color: #17233d; /* iView 标题文字颜色 */
}

.page_style {
  margin-top: 10px;
  text-align: right;
}
</style>
