<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import type { ContestItem } from '../types'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getContestRules, updateContestRules, getExamList } from '../api'
import { useMapStore } from '@/stores/map'
import { scoreRuleList } from '@/utils/dictionary'

interface Prop {
  disabled: boolean
}
defineProps<Prop>()

const emit = defineEmits<{
  (e: 'update'): void
  (e: 'update:modelValue', visible: boolean): void
}>()

const detail = $ref(inject('detail') as ContestItem)

// 评分方法
const scoreMethods = useMapStore().getMapValuesByKey('scoring_manner')

const formRef = $ref<FormInstance>()
const form = reactive<any>({
  name: detail.name,
  competition_id: detail.id,
  is_more_status: '0',
  rule_type: '1',
  lowest_number: undefined,
  detail_list: []
})
const rules = ref<FormRules>({
  rule_type: [{ required: true, message: '请选择多人评分成绩计算规则' }],
  lowest_number: [{ required: true, message: '请输入评分人数' }]
})

// 获取评分规则详情
function fetchInfo() {
  getContestRules({ competition_id: detail.id }).then(res => {
    const data = res.data.detail
    if (!data) return
    const detailList = data.details.map((item: any) => {
      return {
        id: item.id,
        exam_id: item.exam_id,
        name: item.name,
        old_score: parseFloat(item.old_score),
        ratio: parseFloat(item.ratio),
        type: item.type
      }
    })
    Object.assign(form, {
      detail_list: detailList,
      is_more_status: data.is_more_status,
      rule_type: data.rule_type,
      lowest_number: parseInt(data.lowest_number)
    })
  })
}
let examList = $ref<Record<string, any>[]>([])
// 获取关联考试列表
function fetchExamList() {
  getExamList({ project: 'x1', 'per-page': 1000 }).then(res => {
    examList = res.data.list || []
  })
}
onMounted(() => {
  fetchInfo()
  fetchExamList()
})

// 最低评分人数
const minLowestNumber = $computed(() => {
  return form.rule_type === '3' ? 3 : 2
})
// 合计
const total = $computed(() => {
  return form.detail_list.reduce((result: number, item: any) => {
    return result + (item.ratio || 0)
  }, 0)
})
// 添加
function handleAdd() {
  form.detail_list.push({ id: '0', exam_id: '', name: '', type: undefined, old_score: 100, ratio: undefined })
}

// 删除
function handleRemove(index: number) {
  form.detail_list.splice(index, 1)
}

// 提交
function handleSubmit() {
  for (let i = 0; i < form.detail_list.length; i++) {
    const item = form.detail_list[i]
    if (!item.name || !item.type || !item.old_score || !item.ratio || (item.type === '2' && !item.exam_id)) {
      ElMessage.error(`第${i + 1}行规则配置错误，请检查后重试`)
      return
    }
  }
  if (total < 100) {
    ElMessage.error('占比总和未达到100')
    return
  }
  formRef?.validate().then(() => {
    const detailList = form.detail_list.map((item: any) => {
      item.exam_id = item.exam_id || '0'
      return item
    })
    const params = Object.assign({}, form, { detail_list: detailList })
    updateContestRules(params).then(() => {
      ElMessage({ message: '保存成功', type: 'success' })
      emit('update')
      emit('update:modelValue', false)
    })
  })
}
// 当前评分方法
function currentScoreMethods(value: string) {
  const found = form.detail_list.find((item: any) => ['2', '3'].includes(item.type))
  if (!['2', '3'].includes(value) && found) {
    return scoreMethods.filter(item => !['2', '3'].includes(item.value))
  }
  return scoreMethods
}
// 评分方法改变
function handleTypeChange(row: any) {
  row.exam_id = ''
  if (row.type === '2') {
    row.old_score = 100
  }
}
// 占比改变
function handleRatioChange(row: any, index: number) {
  const otherTotal = form.detail_list.reduce((result: number, item: any, i: number) => {
    if (index !== i) {
      result += item.ratio || 0
    }
    return result
  }, 0)
  // 最大可输入占比
  nextTick(() => {
    row.ratio = Math.min(100 - otherTotal, row.ratio)
  })
}
</script>

<template>
  <el-dialog
    title="评分规则"
    :close-on-click-modal="false"
    width="800px"
    @update:modelValue="$emit('update:modelValue')">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="170px" :disabled="disabled">
      <el-form-item label="赛项名称">
        <el-input v-model="form.name" disabled />
      </el-form-item>
      <el-form-item label="多人评分" prop="is_more_status">
        <el-radio-group v-model="form.is_more_status">
          <el-radio label="1">是</el-radio>
          <el-radio label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <template v-if="form.is_more_status === '1'">
        <el-form-item label="多人评分成绩计算规则" prop="rule_type">
          <el-radio-group v-model="form.rule_type">
            <el-radio v-for="item in scoreRuleList" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="最低评分人数" prop="lowest_number">
          <el-input-number v-model="form.lowest_number" step-strictly :min="minLowestNumber" :controls="false" />
          <p class="tips">
            此处填写对应计算规则的最低评分人数。<br />
            综合得分法>=3，其余方法>=2
          </p>
        </el-form-item>
      </template>
      <el-form-item class="form-table-list">
        <el-row justify="end" style="width: 100%; margin-bottom: 10px">
          <el-button type="primary" :icon="Plus" @click="handleAdd"></el-button>
        </el-row>
        <el-table :data="form.detail_list" :header-cell-style="{ background: '#ededed' }">
          <el-table-column prop="date" label="评分规则" align="center">
            <template #default="{ row }">
              <el-input v-model="row.name" />
            </template>
          </el-table-column>
          <el-table-column prop="date" label="评分方法" align="center" width="124">
            <template #default="{ row }">
              <el-select v-model="row.type" @change="handleTypeChange(row)">
                <el-option
                  v-for="item in currentScoreMethods(row.type)"
                  :key="item.id"
                  :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="date" label="关联考试" align="center">
            <template #default="{ row }">
              <el-select v-model="row.exam_id" filterable v-if="row.type === '2'">
                <el-option
                  v-for="item in examList"
                  :key="item.exam_id"
                  :label="item.name"
                  :value="item.exam_id"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="date" label="分值" align="center" width="100">
            <template #default="{ row }">
              <el-input-number
                v-model="row.old_score"
                :min="0"
                :controls="false"
                :disabled="row.type === '2'"
                style="width: 100%" />
            </template>
          </el-table-column>
          <el-table-column prop="date" label="占比（%）" align="center" width="100">
            <template #default="{ row, $index }">
              <el-input-number
                v-model="row.ratio"
                :min="0"
                :controls="false"
                @change="handleRatioChange(row, $index)"
                style="width: 100%" />
            </template>
          </el-table-column>
          <el-table-column prop="date" label="操作" align="center" width="90">
            <template #default="{ $index }">
              <el-button text type="primary" @click="handleRemove($index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="total" v-if="form.detail_list.length">
          <p>合计：{{ total }}%</p>
        </div>
      </el-form-item>
      <el-row justify="center">
        <el-button type="primary" round auto-insert-space @click="handleSubmit">保存</el-button>
        <el-button round auto-insert-space @click="$emit('update:modelValue', false)">取消</el-button>
      </el-row>
    </el-form>
  </el-dialog>
</template>

<style lang="scss" scoped>
.tips {
  margin-left: 10px;
  font-size: 12px;
  line-height: 1.2;
  color: #979393;
}
.form-table-list {
  :deep(.el-form-item__content) {
    margin-left: 0 !important;
  }
}
.total {
  width: 100%;
  padding: 10px 90px;
  text-align: right;
  box-sizing: border-box;
  p {
    display: inline-block;
    min-width: 100px;
    text-align: center;
    color: #016fa0;
    background-color: #ededed;
  }
}
</style>
