<template>
  <div class="container">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="考生省份" prop="province">
          <el-select v-model="form.province" placeholder="请选择省份">
            <el-option v-for="(item,index) in state.provinceList" :key="index" :label="item.name" :value="item.code"/>
          </el-select>
        </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="考生科目" prop="cognitioPolyclinic">
            <el-radio-group v-model="form.cognitioPolyclinic">
              <el-radio label="文科">历史组</el-radio>
              <el-radio label="理科">物理组</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="专业类别" prop="professionalCategory">
            <el-select v-model="form.professionalCategory" placeholder="请选择专业类别"  @change="handleProfessionalCateGoryChange">
              <el-option v-for="(item,index) in state.professionalCategoryList" :key="index" :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="state.subjectsList && state.subjectsList.length>0">
          <el-form-item label="专业选课" prop="subjectList">
            <el-select v-model="form.subjectList" multiple @change="handleSubjectsSelectChange">
              <el-option v-for="(item,index) in state.subjectsList" :key="index" :label="item.label" :value="item.value" :disabled="item.exclude && form.subjectList.includes(item.exclude)"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20" v-if="form.subjectList && form.subjectList.length>0">
        <el-col :span="12" v-for="(item,index) in form.subjectList" :key="index">
          <!--音乐-->
          <el-form-item label="音表声乐" :prop="convertSubjectToField(item)" v-if="item ==='音乐表演声乐'">
            <el-input type="number" min="0" max="300" v-model="form.yybysy" @input="validateInput(item)" :placeholder="'请输入'+item"></el-input>
          </el-form-item>
          <el-form-item label="音表器乐" :prop="convertSubjectToField(item)" v-else-if="item ==='音乐表演器乐'">
            <el-input type="number" min="0" max="300" v-model="form.yybyqy" @input="validateInput(item)" :placeholder="'请输入'+item"></el-input>
          </el-form-item>
          <el-form-item :label="item" :prop="convertSubjectToField(item)" v-else-if="item ==='音乐教育'">
            <el-input type="number" min="0" max="300" v-model="form.yyjy" @input="validateInput(item)" :placeholder="'请输入'+item"></el-input>
          </el-form-item>
          <!--表演-->
          <el-form-item :label="item" :prop="convertSubjectToField(item)" v-else-if="item ==='服装表演'">
            <el-input type="number" min="0" max="300" v-model="form.fzby" @input="validateInput(item)" :placeholder="'请输入'+item"></el-input>
          </el-form-item>
          <el-form-item :label="item" :prop="convertSubjectToField(item)" v-else-if="item ==='戏剧影视导演'">
            <el-input type="number" min="0" max="300" v-model="form.xjysdy" @input="validateInput(item)" :placeholder="'请输入'+item"></el-input>
          </el-form-item>
          <el-form-item :label="item" :prop="convertSubjectToField(item)" v-else-if="item ==='戏剧影视表演'">
            <el-input type="number" min="0" max="300" v-model="form.xjysby" @input="validateInput(item)" :placeholder="'请输入'+item"></el-input>
          </el-form-item>

        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12" v-if="form.professionalCategory!=='表演类' && form.professionalCategory!=='音乐类' ">
          <el-form-item :label="dynamicProfessionalCategoryLabel()" prop="professionalScore">
            <el-input type="number" min="0" max="300" v-model="form.professionalScore" :placeholder="'请输入'+dynamicProfessionalCategoryLabel()"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="文化成绩" prop="culturalScore">
            <el-input type="number" min="0" max="300" v-model="form.culturalScore" placeholder="请输入文化成绩"></el-input>
          </el-form-item>
        </el-col>

      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="语文成绩" prop="chineseScore">
            <el-input type="number" min="0" max="300" v-model="form.chineseScore" placeholder="请输入语文成绩"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="英语成绩" prop="englishScore">
            <el-input type="number" min="0" max="300" v-model="form.englishScore" placeholder="请输入英语成绩"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item>
        <el-button style="width: 300px;" type="primary" @click="submitForm">确定</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref} from 'vue';
import StaticConstant from '@/utils/StaticConstant';
import {SubjectsEntity} from '@/types/index'
import ApiConstant from "@/utils/ApiConstant";
import axiosInstance from '@/utils/http';
import { getScore } from '@/axios/api';
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
const router = useRouter();
const state= reactive({
  provinceList:[
    {name: "河南", code: "河南"},
  ],
  professionalCategoryList:StaticConstant.professionalCategoryList,
  subjectsList:[] as Array<SubjectsEntity>,//专业选课
})
const form = reactive({
  province: '河南',//省份
  cognitioPolyclinic: '文科',//科类
  professionalCategory: '',//报考方向
  culturalScore: '',//文化分
  professionalScore: '',//统考分
  chineseScore: '',//语文成绩
  englishScore: '',//英语成绩
  subjectList:[] as Array<string>,//专业选课
  yybysy:'',//音乐表演声乐
  yybyqy:'',//音乐表演器乐
  yyjy:'',//音乐教育
  fzby:'',//服装表演
  xjysdy:'',//戏剧影视导演
  xjysby:'',//戏剧影视表演
});
const rules = ref({})

const formRef = ref<HTMLFormElement | any>({});

const submitForm = () => {
  formRef.value.validate((valid: boolean) => {
    if(!valid){
      // 表单验证失败
      console.log('Validation failed');
      return false
    }
    // 表单验证通过，可以提交表单数据
    let submitForm = {
      ...form,
      professionalCategoryChildren: form.subjectList.join(',')
    }
    console.log('Form submitted:', submitForm);
    axiosInstance({
      url: ApiConstant.Score.scoreSave,
      method: 'post',
      data: submitForm,
      /*showLoading: false,//是否显示加载图标*/
    }).then((response) => {
      return response.data
    }).then((data) => {
      console.log('qqq')
      console.log(data)
      if(data.success){
        ElMessage.success('保存成功');
        getScore()
        setTimeout(function(){
          router.push({
            path: "/index"
          });
          window.location.reload()
        }, 1000);
      }else{
        ElMessage.error(data.message);
      }
      //有数据情况下
    }).catch((error: any) => {
      console.log(error);
    }).finally(() => {
    });

  });
};

onMounted(()=>{
  try {
    const programType = import.meta.env.VITE_PROGRAM_TYPE;
    if(programType === '体育志愿宝'){
      state.professionalCategoryList = StaticConstant.professionalCategoryList.filter(item => item.value === '体育类')
    }

    reloadScore()
  } catch (error) {
    getScore()
  }
})

function reloadScore(){
  let scoreInfoStr = localStorage.getItem('scoreInfo')
  if(scoreInfoStr){
      let scoreInfo = JSON.parse(scoreInfoStr)
      form.professionalCategory = scoreInfo.professionalCategory
      form.cognitioPolyclinic = scoreInfo.cognitioPolyclinic
      form.province = scoreInfo.province
      form.culturalScore = scoreInfo.culturalScore
      form.professionalScore = scoreInfo.professionalScore
      form.chineseScore = scoreInfo.chineseScore
      form.englishScore = scoreInfo.englishScore
      handleProfessionalCateGoryChange()
      if(scoreInfo.professionalCategoryChildren){
        form.subjectList = scoreInfo.professionalCategoryChildren.split(',')
      }
      form.yybysy = scoreInfo.yybysy
      form.yybyqy = scoreInfo.yybyqy
      form.yyjy = scoreInfo.yyjy
      form.fzby = scoreInfo.fzby
      form.xjysdy = scoreInfo.xjysdy
      form.xjysby = scoreInfo.xjysby
      console.log(scoreInfo)
    }

    reloadRules()
}

//切换专业类别事件
const handleProfessionalCateGoryChange=()=>{
  form.subjectList = []
  state.subjectsList = []
  //判断选择专业是不是有专业选课
  state.professionalCategoryList.forEach(item=>{
    if(item.value === form.professionalCategory && item.children){
      //有专业选课
      state.subjectsList = item.children as Array<SubjectsEntity>
    }
  })
  reloadRules()
}

//选择专业选课事件
const handleSubjectsSelectChange=(value:string[])=>{
  if (value.includes('a')) {
    form.subjectList = value.filter((item) => item !== 'b');
  } else if (value.includes('b')) {
    form.subjectList = value.filter((item) => item !== 'a');
  }
  reloadRules()
}

//动态更改统考成绩文本
const dynamicProfessionalCategoryLabel=()=>{
  if(form.professionalCategory === '音乐类'){
    return "主项成绩";
  }
  return "统考成绩";
}

// 将专业选课转换成字段
const convertSubjectToField = (subjectList: string) => {
  switch (subjectList) {
    case '音乐表演声乐':
      return 'yybysy';
    case '音乐表演器乐':
      return 'yybyqy';
    case '音乐教育':
      return 'yyjy';
    case '服装表演':
      return 'fzby';
    case '戏剧影视导演':
      return 'xjysdy';
    case '戏剧影视表演':
      return 'xjysby';
  }
}
const validateInput = (subjectList:any)=>{
  if(subjectList === '音乐表演声乐'){
    form.yybysy = form.yybysy.replace(/\D/g, '')
  }else if(subjectList === '音乐表演器乐'){
    form.yybyqy = form.yybyqy.replace(/\D/g, '')
  }else if(subjectList === '音乐教育'){
    form.yyjy = form.yyjy.replace(/\D/g, '')
  }else if(subjectList === '服装表演'){
    form.fzby = form.fzby.replace(/\D/g, '')
  }else if(subjectList === '戏剧影视导演'){
    form.xjysdy = form.xjysdy.replace(/\D/g, '')
  }else if(subjectList === '戏剧影视表演'){
    form.xjysby = form.xjysby.replace(/\D/g, '')
  }
}

function reloadRules(){
  if(state.subjectsList){
    let ru = {
      province: [{ required: true, message: '请选择省份', trigger: 'change' }],
      professionalCategory: [{ required: true, message: '请选择专业类别', trigger: 'change' }],
      cognitioPolyclinic: [{ required: true, message: '请选择考生科目', trigger: 'change' }],
      professionalScore: [{ required: true, message: '请输入'+dynamicProfessionalCategoryLabel(), trigger: 'blur' }],
      culturalScore: [{ required: true, message: '请输入文化成绩', trigger: 'blur' }],
      chineseScore: [{ required: true, message: '请输入语文成绩', trigger: 'blur' }],
      englishScore: [{ required: true, message: '请输入英语成绩', trigger: 'blur' }],
      subjectList: [{ required: true, message: '请选择专业选课', trigger: 'change' }],
    }
    if(form.subjectList && form.subjectList.length>0){
      form.subjectList.forEach(item=>{
        ru[convertSubjectToField(item)] = [{ required: true, message: '请输入'+item, trigger: 'change' }]
      })
    }
    rules.value = ru
  }else{
    rules.value = {
      province: [{ required: true, message: '请选择省份', trigger: 'change' }],
      professionalCategory: [{ required: true, message: '请选择专业类别', trigger: 'change' }],
      cognitioPolyclinic: [{ required: true, message: '请选择考生科目', trigger: 'change' }],
      professionalScore: [{ required: true, message: '请输入'+dynamicProfessionalCategoryLabel(), trigger: 'blur' }],
      culturalScore: [{ required: true, message: '请输入文化成绩', trigger: 'blur' }],
      chineseScore: [{ required: true, message: '请输入语文成绩', trigger: 'blur' }],
      englishScore: [{ required: true, message: '请输入英语成绩', trigger: 'blur' }],
    }
  }
}
</script>

<style scoped lang="scss">
.container {
  margin: 20px;
}
:deep(.el-form-item__content){
  max-width: 80%;
}
</style>
