<template>
  <el-dialog title="军事体育数据填报" :visible.sync="dialogVisible" width="60%">
    <el-form :model="formData" :rules="rules" ref="formRef">
      <el-table :data="formData.tableData" border>
        <el-table-column label="序号" width="60" type="index" align="center" />

        <el-table-column label="课目名称" prop="tiYuKaoPingKeMuMingCheng">
          <template slot-scope="scope">
            <template v-if="scope.$index === 0">
              {{ scope.row.tiYuKaoPingKeMuMingCheng }}
            </template>
            <template v-else>
              <el-form-item
                :prop="
                  'tableData.' + scope.$index + '.tiYuKaoPingKeMuMingCheng'
                "
                :rules="rules.tiYuKaoPingKeMuMingCheng"
              >
                <el-input
                  placeholder="请输入课目名称"
                  v-model="scope.row.tiYuKaoPingKeMuMingCheng"
                />
              </el-form-item>
            </template>
          </template>
        </el-table-column>

        <el-table-column label="成绩" prop="tiYuKaoPingKeMuChengJi">
          <template slot-scope="scope">
            <el-form-item
              :prop="'tableData.' + scope.$index + '.tiYuKaoPingKeMuChengJi'"
              :rules="rules.tiYuKaoPingKeMuChengJi"
            >
              <el-input
                v-model="scope.row.tiYuKaoPingKeMuChengJi"
                placeholder="请输入成绩"
              />
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column label="评定" prop="level">
          <template slot-scope="scope">
            <el-form-item
              :prop="'tableData.' + scope.$index + '.level'"
              :rules="rules.level"
            >
              <template v-if="scope.$index === 0">
                <el-select
                  style="width: 100%"
                  v-model="scope.row.level"
                  placeholder="请选择评定结果"
                >
                  <el-option
                    v-for="item in evaluationOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </template>
              <template v-else>
                <el-input
                  type="number"
                  @input="handleScoreInput($event, scope.$index)"
                  v-model="scope.row.level"
                  placeholder="请输入评定结果"
                />
              </template>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="120">
          <template slot-scope="scope">
            <el-button
              v-if="scope.$index === formData.tableData.length - 1"
              type="text"
              @click="handleAdd"
            >
              添加行
            </el-button>
            <el-button
              style="color: #ff390e"
              v-if="scope.$index !== 0 && formData.tableData.length > 1"
              type="text"
              @click="handleDelete(scope.$index)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  name: 'ScoreDialog',
  props: {
    tableData: {
      type: Array,
      default: () => [],
    },
  },

  data() {
    return {
      dialogVisible: false,
      formData: {
        tableData: [],
      },
      evaluationOptions: [
        {label: '合格', value: '合格'},
        {label: '不合格', value: '不合格'},
      ],
      rules: {
        tiYuKaoPingKeMuMingCheng: [
          {required: true, message: '请输入课目名称', trigger: 'blur'},
        ],
        tiYuKaoPingKeMuChengJi: [
          {required: true, message: '请输入成绩', trigger: 'blur'},
        ],
        level: [{required: true, message: '请输入评定', trigger: 'blur'}],
      },
    }
  },
  methods: {
    handleScoreInput(value, index) {
      // 限制只保留一位小数
      if (value.includes('.')) {
        const parts = value.split('.')
        if (parts[1].length > 1) {
          this.formData.tableData[index].tiYuKaoPingKeMuChengJi =
            Number(value).toFixed(1)
        }
      }
    },
    handleAdd() {
      this.formData.tableData.push({
        tiYuKaoPingKeMuMingCheng: '',
        tiYuKaoPingKeMuChengJi: '',
        level: '',
      })
    },
    handleDelete(index) {
      this.formData.tableData.splice(index, 1)
    },
    handleSubmit() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          const {tableData} = this.formData

          // 验证是否有体型数据
          const bodyTypeData = tableData.find(
            (item) => item.tiYuKaoPingKeMuMingCheng === '体型'
          )
          if (!bodyTypeData) {
            this.$message.error('缺少体型数据')
            return
          }

          // 计算除体型外的总分
          const totalScoreWithoutBodyType = tableData.reduce((acc, current) => {
            if (current.tiYuKaoPingKeMuMingCheng !== '体型') {
              return acc + Number(current.level)
            }
            return acc
          }, 0)

          // 判断体型是否合格
          const bodyTypeQualified = bodyTypeData.level === '合格'

          // 根据规则判定等级
          let grade
          if (!bodyTypeQualified || totalScoreWithoutBodyType < 240) {
            grade = '4'
          } else if (
            totalScoreWithoutBodyType >= 240 &&
            totalScoreWithoutBodyType < 320
          ) {
            grade = '3'
          } else if (
            totalScoreWithoutBodyType >= 320 &&
            totalScoreWithoutBodyType < 360
          ) {
            grade = '2'
          } else {
            grade = '1'
          }

          // 提交数据
          this.$emit('updateData', {
            list: this.formData.tableData,
            sum: totalScoreWithoutBodyType,
            grade,
          })

          this.dialogVisible = false
          this.$message.success('提交成功')
        } else {
          this.$message.error('请填写完整所有必填项')
          return false
        }
      })
    },
    open(data) {
      data = data.map((item, i) => {
        if (item.level && i !== 0) {
          item.level = item.level * 1
        }
        return item
      })
      this.formData.tableData = data
      this.dialogVisible = true
    },
  },
}
</script>

<style lang="scss" scoped>
.el-table {
  margin-bottom: 20px;
}
::v-deep .el-form-item {
  margin-bottom: 0 !important;
}
</style>
