<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import type { ExperimentItem } from '../types'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { gradeRule, gradeRuleList } from '@/utils/dictionary'
import { getExperimentGradeRule, updateExperimentGradeRule } from '../api'

interface Props {
  data: ExperimentItem
}

const props = defineProps<Props>()

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

const formRef = $ref<FormInstance>()
const form = reactive<any>({
  experiment_id: props.data.id,
  is_show: '1',
  rule_list: [{ name: '实验报告', type: 1, percent: 100, rule_mode: 1 }]
})

function fetchInfo() {
  getExperimentGradeRule({ experiment_id: props.data.id }).then(res => {
    const { detail } = res.data
    if (!detail.id) return
    let ruleList = []
    try {
      ruleList = JSON.parse(detail.rule_list).map((item: any) => {
        return { ...item, percent: parseFloat(item.percent) }
      })
    } catch (error) {
      console.log(error)
    }
    Object.assign(form, detail, { rule_list: ruleList })
  })
}
onMounted(() => {
  fetchInfo()
})

// 合计
const total = $computed(() => {
  return form.rule_list.reduce((result: number, item: any) => {
    return result + (item.percent || 0)
  }, 0)
})

// 添加
function handleAdd() {
  form.rule_list.push({ name: '', type: undefined, percent: undefined, rule_mode: 1 })
}
// 删除
function handleRemove(index: number) {
  form.rule_list.splice(index, 1)
}
// 提交
function handleSubmit(call?: any) {
  for (let i = 0; i < form.rule_list.length; i++) {
    const item = form.rule_list[i]
    if (!item.name || !item.type) {
      ElMessage.error(`第${i + 1}行规则配置错误，请检查后重试`)
      return
    }
    if (!item.percent) {
      ElMessage.error(`${item.name}权重不能为0！`)
      return
    }
    if (item.type === 5 && /实验报告|实验准备|实验结果|课堂活跃度/.test(item.name)) {
      ElMessage.error(`第${i + 1}行规则配置错误，自定义的名称不能包含“实验报告”、“实验准备”、“实验结果”和“课堂活跃度”`)
      return
    }
  }
  if (total < 100) {
    ElMessage.error('实验成绩规则项权重之和必须为100%！')
    return
  }

  formRef?.validate().then(() => {
    const params = { ...form, rule_list: JSON.stringify(form.rule_list) }
    updateExperimentGradeRule(params).then(() => {
      // call()
      console.log(call, 'call()')
      if (!call) {
        ElMessage({ message: '保存成功', type: 'success' })
        emit('update')
        emit('update:modelValue', false)
      } else {
        call()
      }
    })
  })
}

// 当前评分方法
function currentRuleNames(value: number) {
  const typeList = form.rule_list.map((item: any) => item.type)
  const tempList = gradeRuleList.filter(item => {
    return item.value === value || item.value === 5 || !typeList.includes(item.value)
  })
  if (props.data.type === '4') {
    // 数字营销实验
    return tempList.filter(item => [1, 5, 6, 7, 8, 9, 10].includes(item.value as number))
  } else {
    return tempList.filter((item: any) => item.value <= 5)
  }
}

function handleTypeChange(row: any) {
  row.rule_mode = 1
  if (row.type === 5) return
  row.name = gradeRule[row.type]
}
// 占比改变
function handlePercentChange(row: any, index: number) {
  const otherTotal = form.rule_list.reduce((result: number, item: any, i: number) => {
    if (index !== i) {
      result += item.percent || 0
    }
    return result
  }, 0)
  // 最大可输入占比
  nextTick(() => {
    row.percent = Math.min(100 - otherTotal, row.percent)
  })
}

function rowScore(percent = 0) {
  const score = parseFloat(props.data.score) || 0
  return (percent / 100) * score
}

// 编辑题
const handleEdit = function (type: number) {
  handleSubmit(function () {
    window.open(
      `/admin/lab/experiment/questions?id=${props.data.id}&type=${type}&name=${props.data.name}&type_name=${props.data.type_name}&score=${props.data.score}`
    )
  })
}
</script>

<template>
  <el-dialog
    title="编辑实验成绩规则"
    :close-on-click-modal="false"
    width="800px"
    @update:modelValue="$emit('update:modelValue')"
  >
    <el-form ref="formRef" :model="form" label-suffix="：">
      <el-form-item label="实验名称">{{ data?.name }}</el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="是否允许查看成绩明细" prop="is_show">
            <el-radio-group v-model="form.is_show">
              <el-radio label="1">是</el-radio>
              <el-radio label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="实验总成绩">{{ data?.score }}</el-form-item>
        </el-col>
      </el-row>
      <el-form-item>
        <el-row justify="space-between" style="width: 100%">
          <p>实验成绩规则：</p>
          <el-button type="primary" :icon="Plus" @click="handleAdd"></el-button>
        </el-row>
        <el-table :data="form.rule_list" row-key="id">
          <el-table-column prop="name" width="170">
            <template #default="{ row }">
              <el-input v-model="row.name" :maxlength="20" style="width: 100%" v-if="row.type === 5" />
              <el-select
                v-model="row.type"
                :disabled="row.type === 1"
                style="width: 100%"
                @change="handleTypeChange(row)"
                v-else
              >
                <el-option v-for="item in currentRuleNames(row.type)" :key="item.value" v-bind="item"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="percent" align="center" width="200">
            <template #default="{ row, $index }">
              <el-input-number v-model="row.percent" :min="0" @change="handlePercentChange(row, $index)" /> %
            </template>
          </el-table-column>
          <el-table-column prop="rule_mode" width="200">
            <template #default="{ row }">
              <el-radio-group v-model="row.rule_mode" size="small">
                <el-radio :label="1">人工评分</el-radio>
                <!-- <el-radio :label="2" v-if="[2, 3].includes(row.type)">自动评分</el-radio> -->
                <el-radio :label="2" :disabled="row.type === 1 || row.type === 8">自动评分</el-radio>
              </el-radio-group>
            </template>
          </el-table-column>
          <el-table-column width="90">
            <template #default="{ row }">满分：{{ 100 || rowScore(row.percent) }} </template>
          </el-table-column>
          <el-table-column align="right">
            <template #default="{ $index, row }">
              <div class="btn-box">
                <!-- || row.type === 8 -->
                <el-button
                  :disabled="row.type === 1"
                  style="padding: 0"
                  text
                  type="primary"
                  @click="handleEdit(row.type)"
                  v-if="row.type !== 1"
                  >编辑</el-button
                >
                <el-button style="padding: 0" text type="primary" @click="handleRemove($index)" v-if="row.type !== 1"
                  >删除</el-button
                >
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="total" v-if="form.rule_list.length">
          <p>合计：{{ total }}%</p>
        </div>
      </el-form-item>
    </el-form>
    <el-row justify="center">
      <el-button type="primary" round auto-insert-space @click="handleSubmit(0)">保存</el-button>
      <el-button round auto-insert-space @click="$emit('update:modelValue', false)">取消</el-button>
    </el-row>
  </el-dialog>
</template>

<style lang="scss" scoped>
.total {
  width: 100%;
  padding: 10px 200px;
  box-sizing: border-box;
  p {
    margin-left: 16px;
    display: inline-block;
    min-width: 150px;
    text-align: center;
    color: #016fa0;
    background-color: #ededed;
  }
}
</style>
