<template>
  <div class="score-input">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
      <!-- 基础分 -->
      <el-form-item label="基础分" prop="baseScore">
        <el-input-number
          v-model="form.baseScore"
          :min="0"
          :max="10"
          :step="0.1"
          :precision="2"
          controls-position="right"
          @change="handleCalculate"
        ></el-input-number>
      </el-form-item>

      <!-- 扣分项 -->
      <el-form-item label="扣分项">
        <el-tag
          v-for="(deduction, index) in form.deductions"
          :key="index"
          closable
          @close="handleRemoveDeduction(index)"
          class="deduction-tag"
        >
          {{ deduction.name }} (-{{ deduction.score }}分)
        </el-tag>
        <el-button
          size="small"
          type="primary"
          plain
          @click="showDeductionSelector"
        >
          添加扣分项
        </el-button>
      </el-form-item>

      <!-- 总扣分 -->
      <el-form-item label="总扣分">
        <el-tag type="danger">-{{ totalDeduction }}分</el-tag>
      </el-form-item>

      <!-- 最终得分 -->
      <el-form-item label="最终得分">
        <el-tag :type="getScoreType(finalScore)" size="large" class="final-score-tag">
          {{ finalScore }}分
        </el-tag>
      </el-form-item>

      <!-- 备注 -->
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="form.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入备注信息"
        ></el-input>
      </el-form-item>
    </el-form>

    <!-- 扣分项选择器弹窗 -->
    <el-dialog
      v-model="deductionDialogVisible"
      title="选择扣分项"
      width="600px"
    >
      <el-checkbox-group v-model="selectedDeductions">
        <div class="deduction-list">
          <el-checkbox
            v-for="item in deductionList"
            :key="item.id"
            :label="item.id"
            class="deduction-item"
          >
            <span class="deduction-name">{{ item.name }}</span>
            <span class="deduction-score">-{{ item.score }}分</span>
          </el-checkbox>
        </div>
      </el-checkbox-group>
      <template #footer>
        <el-button @click="deductionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmDeductions">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getDeductionList } from '@/api/martial/deduction'

export default {
  name: 'ScoreInput',

  props: {
    modelValue: {
      type: Object,
      default: () => ({
        baseScore: 10,
        deductions: [],
        remark: ''
      })
    },
    projectId: {
      type: Number,
      required: true
    }
  },

  emits: ['update:modelValue', 'change'],

  data() {
    return {
      form: {
        baseScore: 10,
        deductions: [],
        remark: ''
      },
      rules: {
        baseScore: [
          { required: true, message: '请输入基础分', trigger: 'blur' }
        ]
      },
      deductionDialogVisible: false,
      deductionList: [],
      selectedDeductions: []
    }
  },

  computed: {
    totalDeduction() {
      return this.form.deductions.reduce((sum, item) => sum + item.score, 0)
    },

    finalScore() {
      const score = this.form.baseScore - this.totalDeduction
      return Math.max(0, parseFloat(score.toFixed(2)))
    }
  },

  watch: {
    modelValue: {
      handler(newVal) {
        if (newVal) {
          this.form = { ...newVal }
        }
      },
      immediate: true,
      deep: true
    },

    projectId: {
      handler(newVal) {
        if (newVal) {
          this.loadDeductions()
        }
      },
      immediate: true
    }
  },

  methods: {
    async loadDeductions() {
      try {
        const res = await getDeductionList({
          projectId: this.projectId
        })
        if (res.data && res.data.records) {
          this.deductionList = res.data.records
        }
      } catch (error) {
        console.error('加载扣分项失败:', error)
      }
    },

    handleCalculate() {
      this.emitChange()
    },

    showDeductionSelector() {
      this.selectedDeductions = this.form.deductions.map(item => item.id)
      this.deductionDialogVisible = true
    },

    handleConfirmDeductions() {
      this.form.deductions = this.deductionList.filter(item =>
        this.selectedDeductions.includes(item.id)
      ).map(item => ({
        id: item.id,
        name: item.name,
        score: item.score
      }))

      this.deductionDialogVisible = false
      this.emitChange()
    },

    handleRemoveDeduction(index) {
      this.form.deductions.splice(index, 1)
      this.emitChange()
    },

    emitChange() {
      const value = {
        ...this.form,
        totalDeduction: this.totalDeduction,
        finalScore: this.finalScore
      }
      this.$emit('update:modelValue', value)
      this.$emit('change', value)
    },

    getScoreType(score) {
      if (score >= 9) return 'success'
      if (score >= 8) return 'warning'
      if (score >= 7) return 'info'
      return 'danger'
    },

    async validate() {
      return await this.$refs.formRef.validate()
    }
  }
}
</script>

<style lang="scss" scoped>
.score-input {
  .deduction-tag {
    margin-right: 8px;
    margin-bottom: 8px;
  }

  .final-score-tag {
    font-size: 24px;
    font-weight: bold;
    padding: 10px 20px;
  }

  .deduction-list {
    display: flex;
    flex-direction: column;
    gap: 10px;
    max-height: 400px;
    overflow-y: auto;
  }

  .deduction-item {
    display: flex;
    justify-content: space-between;
    padding: 10px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;

    &:hover {
      background-color: #f5f7fa;
    }
  }

  .deduction-name {
    flex: 1;
  }

  .deduction-score {
    color: #f56c6c;
    font-weight: bold;
  }
}
</style>
