<script>
import graceChecker from "@/common/graceChecker";
import StaticConstant from "@/common/StaticConstant";
import ApiConstant from "@/common/ApiConstant";
import Request from '@/common/request'
import {arrayIsNotEmpty, stringIsNotEmpty} from "@/common/util";

let request = new Request()
export default {
  name: "socre-edit",
  computed: {
    StaticConstant() {
      return StaticConstant
    }
  },
  data() {
    return {
      saveScoreInfo: {},
      scoreInfo: {
        id: '',
        province: '河南',//省份
        cognitioPolyclinic: '理科',//科类
        professionalCategory: '',//报考方向
        culturalScore: '',//文化分
        professionalScore: '',//统考分
        chineseScore: '',
        englishScore: ''
      },
      provinceArray: [{name: "河南"}],//
      cognitioPolyclinicArray: StaticConstant.categoryList,//文理分科
      //===========================================================
      professionalCategoryArray: StaticConstant.professionalCategoryList,//专业类别大类array
      professionalCategoryVisible: false,//专业类别 是否显示
      professionalCategoryIndex: null,
      pCategoryChildrenList: [],//子级选择
      professionalCategoryScoreMax: '',//选择的专业最高分
      contentHeight: 600
    }
  },
  onShow() {
    this.getUserScore()
  },
  methods: {
    //获取用户的分数信息
    getUserScore() {
      request.get(ApiConstant.Score.getScore, {}).then(res => {
        if (res.success) {
          this.scoreInfo = res.result
          //设置 报考方向 选择
          let professionalCategory = this.scoreInfo.professionalCategory
          for (let i = 0; i < this.professionalCategoryArray.length; i++) {
            if (this.professionalCategoryArray[i].value === professionalCategory) {
              this.professionalCategoryScoreMax = this.professionalCategoryArray[i].scoreMax
              this.professionalCategoryIndex = i
            }
          }
          let professionalCategoryChildren = this.scoreInfo.professionalCategoryChildren
          if (professionalCategoryChildren !== undefined && professionalCategoryChildren !== '') {
            this.pCategoryChildrenList = professionalCategoryChildren.split(',')
          }
        }
      }).catch(err => {
      }).finally(() => {
      });
    },
    //保存用户的分数信息
    saveScore() {
      //调整参数
      this.saveScoreInfo = {...this.scoreInfo}
      if (arrayIsNotEmpty(this.pCategoryChildrenList)) {
        this.saveScoreInfo.professionalCategoryChildren = this.pCategoryChildrenList.join(",")
      } else {
        this.saveScoreInfo.professionalCategoryChildren = ''
      }
      this.saveScoreInfo.professionalCategory = this.professionalCategoryArray[this.professionalCategoryIndex].value
      //==
      request.post(ApiConstant.Score.scoreSave, {
        ...this.saveScoreInfo
      }).then(res => {
        if (res.success) {
          uni.setStorageSync('scoreInfo', this.saveScoreInfo)
          uni.removeStorageSync('fillVolunteer')//清除可报志愿数量
          this.getRecommendMajorCount()
        }
      }).catch(err => {
      }).finally(() => {
      });
    },
    getRecommendMajorCount() {
      request.get(ApiConstant.Major.recommendMajorCount, {}).then(res => {
        if (res.success) {
          let result = res.result
          //将数据存入 缓存
          let fillVolunteer = {
            all: result.allNumber,
            kcj: result.kcj,
            jwt: result.jwt,
            nlq: result.nan,
            kbd: result.kbd
          }
          uni.setStorageSync('fillVolunteer', fillVolunteer)
        }
      }).catch(err => {
      }).finally(() => {
        setTimeout(function () {
          uni.showToast({title: '保存成功', icon: "none"});
          //回到首页
          uni.switchTab({
            url: '/pages/zyb/home'
          });
        }, 500)
      });
    },
    //选择考区
    bindPicker_provinceChange: function (e) {
      console.log('考区picker发送选择改变，携带值为：' + e)
      this.scoreInfo.province = this.provinceArray[e.detail.value].name
    },
    //选择科目
    bindPicker_cognitioPolyclinicChange: function (e) {
      console.log('科目picker发送选择改变，携带值为：' + e.detail.value)
      this.scoreInfo.cognitioPolyclinic = this.cognitioPolyclinicArray[e.detail.value].name
    },
    //选择报考方向
    bindPicker_professionalCategoryChange: function (e) {
      console.log('报考方向picker发送选择改变，携带值为：' + e.detail.value)
      this.scoreInfo.professionalCategory = this.professionalCategoryArray[e.detail.value].value
    },
    formSubmit: function (e) {
      let that = this
      console.log('form发生了submit事件，携带数据为：' + JSON.stringify(e.detail.value))
      //判断 输入分数
      // 子级专业类别
      if (arrayIsNotEmpty(this.pCategoryChildrenList)) {
        for (let i = 0; i < this.pCategoryChildrenList.length; i++) {
          let name = this.pCategoryChildrenList[i]
          //获取字节专业的属性，判断参数是否合格
          let key = this.checkChildrenNameToKey(name)
          let value = this.scoreInfo[key]

          if (value === undefined || value === '') {
            uni.showToast({title: '请输入' + name, icon: "none"});
            return
          }
          let score = parseInt(value)
          if (typeof (score) !== 'number') {
            uni.showToast({title: name + '输入参数有误', icon: "none"});
            return
          }
          if (parseInt(score) > this.professionalCategoryScoreMax) {
            uni.showToast({title: name + '请输入0~' + this.professionalCategoryScoreMax + "之间", icon: "none"});
            return
          }
          this.scoreInfo[key] = score
        }
      } else {
        this.scoreInfo.yybysy = 0
        this.scoreInfo.yybyqy = 0
        this.scoreInfo.yyjy = 0
        this.scoreInfo.fzby = 0
        this.scoreInfo.xjysdy = 0
        this.scoreInfo.xjysby = 0
      }
      //判断统考成绩
      let professionalScore = parseInt(this.scoreInfo.professionalScore)
      console.log('professionalScore:' + professionalScore)
      if (isNaN(professionalScore) || professionalScore < 0 || professionalScore > this.professionalCategoryScoreMax) {
        if (this.professionalCategoryArray[this.professionalCategoryIndex].label === '音乐类') {
          uni.showToast({title: '请输入主项成绩', icon: "none"});
        } else {
          uni.showToast({title: '统考成绩请输入0~' + this.professionalCategoryScoreMax + '之间', icon: "none"});
        }
        return;
      }
      //文化成绩
      let culturalScore = parseInt(this.scoreInfo.culturalScore)
      if (isNaN(professionalScore) || culturalScore < 0 || culturalScore > 750) {
        uni.showToast({title: '文化分请输入0~750之间', icon: "none"});
        return;
      }
      this.scoreInfo.professionalScore = parseInt(this.scoreInfo.professionalScore)
      this.scoreInfo.culturalScore = culturalScore
      uni.showModal({
        title: '确认高考成绩',
        content: '文化成绩:' + this.scoreInfo.culturalScore + " " + (this.scoreInfo.professionalScore ? (this.pCategoryChildrenList && this.pCategoryChildrenList.length > 0 ? '主项成绩:' : '统考成绩:') + this.scoreInfo.professionalScore : ""),
        confirmText: '确定',
        cancelText: '取消',
        success: function (res) {
          if (res.confirm) {
            that.saveScore()
          }
        }
      });
    },
    formReset: function (e) {
      console.log('清空数据')
    },
    onProfessionalCategory() {
      this.professionalCategoryVisible = true;
    },
    onProfessionalCategoryClose() {
      //如果 当前选择的包括方向 有子级
      if (this.professionalCategoryIndex && this.professionalCategoryArray[this.professionalCategoryIndex].children) {
        if (this.pCategoryChildrenList.length === 0) {
          //没有选择子级，提示选择
          uni.showToast({title: '请选择类别', icon: "none"});
          return
        }
      }
      console.log('关闭')
      this.professionalCategoryVisible = false
    },
    onProfessionalCategoryOpen() {
      console.log('打开')
    },
    onProfessionalCategoryBottom() {
      console.log('触底');
    },
    /*选择 大类*/
    clickprofessionalCategoryItem(e, index) {
      console.log(e)
      this.professionalCategoryIndex = index
      this.professionalCategoryScoreMax = this.professionalCategoryArray[this.professionalCategoryIndex].scoreMax
      if (!e.children) {
        this.professionalCategoryVisible = false
      }
      this.pCategoryChildrenList = []
    },
    /*选择 子类*/
    professionalCategoryChildrenChange(e) {
      console.log(e)
      this.pCategoryChildrenList = e.detail.value
    },
    checkChildrenNameToKey(e) {
      if (e === '音乐表演声乐') {
        return 'yybysy';
      } else if (e === '音乐表演器乐') {
        return 'yybyqy';
      } else if (e === '音乐教育') {
        return 'yyjy';
      } else if (e === '服装表演') {
        return 'fzby';
      } else if (e === '戏剧影视导演') {
        return 'xjysdy';
      } else if (e === '戏剧影视表演') {
        return 'xjysby';
      }
    }
  }
}
</script>

<template>
  <view>
    <!--    <page-head title=""></page-head>-->
    <view class="uni-padding-wrap">
      <view class="uni-title uni-common-mt">
        统考/省联考成绩
        <text>\n暂仅支持统考及省组织的联考科类成绩评估</text>
      </view>
    </view>
    <view class="uni-padding-wrap uni-common-mt">
      <form class="form" @submit="formSubmit" @reset="formReset">
        <view class="uni-form-item uni-column">
          <view class="title">考区<span class="red">*</span></view>
          <view class="uni-list">
            <view class="uni-list-cell">
              <view class="uni-list-cell-left">
                当前选择
              </view>
              <view class="uni-list-cell-db">
                <picker @change="bindPicker_provinceChange" :value="scoreInfo.province" :range="provinceArray"
                        range-key="name">
                  <view class="uni-input">{{ scoreInfo.province }}</view>
                </picker>
              </view>
            </view>
          </view>
        </view>
        <view class="uni-form-item uni-column">
          <view class="title">科目<span class="red">*</span></view>
          <view class="uni-list">
            <view class="uni-list-cell">
              <view class="uni-list-cell-left">
                当前选择
              </view>
              <view class="uni-list-cell-db">
                <picker @change="bindPicker_cognitioPolyclinicChange" :value="scoreInfo.cognitioPolyclinic"
                        :range="cognitioPolyclinicArray" range-key="name">
                  <view class="uni-input">{{ scoreInfo.cognitioPolyclinic }}</view>
                </picker>
              </view>
            </view>
          </view>
        </view>
        <view class="uni-form-item uni-column">
          <view class="title">报考方向<span class="red">*</span></view>
          <view class="uni-list" @click="onProfessionalCategory">
            <view class="uni-list-cell">
              <view class="uni-list-cell-left">
                当前选择
              </view>
              <view class="uni-list-cell-db uni-input" style="height: auto !important;">
                <!--选择了-->
                <text style="line-height: 50rpx;"
                      v-if="professionalCategoryIndex!==null &&professionalCategoryArray && (!pCategoryChildrenList || pCategoryChildrenList.length===0)">
                  {{ professionalCategoryArray[professionalCategoryIndex].label }}
                </text>
                <view style="line-height: 35rpx;"
                      v-if="professionalCategoryIndex!==undefined && pCategoryChildrenList &&pCategoryChildrenList.length>0">
                  <text class="flex" v-for="(item,index) in pCategoryChildrenList" :key="index">
                    {{ item }}
                  </text>
                </view>

              </view>
            </view>
          </view>
        </view>
        <view class="uni-form-item uni-column" v-if="professionalCategoryIndex!==undefined"
              v-for="(item,index) in pCategoryChildrenList" :key="index">
          <view class="title">{{ item }}成绩<span class="red">*</span></view>
          <input class="uni-input" type="number" v-model="scoreInfo[checkChildrenNameToKey(item)]" name="culturalScore"
                 :placeholder="'请输入专业分（满分'+professionalCategoryScoreMax+'）'"/>
        </view>
        <view class="uni-form-item uni-column">
          <view class="title" v-if="professionalCategoryArray &&professionalCategoryIndex!==undefined">
            {{
              professionalCategoryArray[professionalCategoryIndex] && professionalCategoryArray[professionalCategoryIndex].label === '音乐类' ? '主项成绩' : '统考成绩'
            }}<span
              class="red">*</span></view>
          <input class="uni-input" type="number" v-model="scoreInfo.professionalScore" name="professionalScore"
                 v-if="professionalCategoryArray[professionalCategoryIndex] && professionalCategoryArray[professionalCategoryIndex].label==='音乐类'"
                 :placeholder="'请输入主项成绩'"/>
          <input class="uni-input" type="number" v-model="scoreInfo.professionalScore" name="professionalScore" v-else
                 :placeholder="'请输入统考分（'+professionalCategoryScoreMax+'）'"/>
        </view>
        <view class="uni-form-item uni-column">
          <view class="title">文化成绩<span class="red">*</span></view>
          <input class="uni-input" type="number" v-model="scoreInfo.culturalScore" name="culturalScore"
                 placeholder="请输入文化分(满分750)"/>
        </view>
        <view class="uni-form-item uni-column">
          <view class="title">英语成绩</view>
          <input class="uni-input" type="number" v-model="scoreInfo.englishScore" name="englishScore"
                 placeholder="请输入英语成绩（选填）"/>
        </view>
        <view class="uni-form-item uni-column">
          <view class="title">语文成绩</view>
          <input class="uni-input" type="number" v-model="scoreInfo.chineseScore" name="chineseScore"
                 placeholder="请输入语文成绩（选填）"/>
        </view>


        <view class="uni-btn-v">
          <button form-type="submit">可修改2次</button>
        </view>
      </form>
    </view>
  </view>

  <!-- 每次弹出重新计算内容高度适用动态数据加载 -->
  <px-popup-bottom :visible.sync="professionalCategoryVisible" title="请选择专业类别"
                   @reachBottom="onProfessionalCategoryBottom"
                   maxHeight="800" radius="40" @close="onProfessionalCategoryClose" @open="onProfessionalCategoryOpen">
    <view class="flex">

      <scroll-view scroll-y="true" class="professionalCategoryPopup" style="height: 500rpx;"
                   :class="professionalCategoryIndex&&professionalCategoryArray[professionalCategoryIndex].children?'flex-item-5':'flex-item-10'">
        <view>
          <view class="flex professionalCategoryItem" :class="professionalCategoryIndex===index?'active':''"
                @click="clickprofessionalCategoryItem(item,index)" v-for="(item,index) in professionalCategoryArray"
                :key="index">
            <text class="text">{{ item.label }}</text>
          </view>
        </view>
      </scroll-view>
      <view class="professionalCategoryChildren flex-item-5"
            v-if="professionalCategoryIndex&&professionalCategoryArray[professionalCategoryIndex].children">
        <checkbox-group @change="professionalCategoryChildrenChange">
          <view class="childrenItem"
                v-for="(item,index) in professionalCategoryArray[professionalCategoryIndex].children" :key="index">
            <label>
              <checkbox :checked="pCategoryChildrenList.length>0 && pCategoryChildrenList.includes(item.value)"
                        :disabled="pCategoryChildrenList.length>0 && pCategoryChildrenList.includes(professionalCategoryArray[professionalCategoryIndex].children[index].exclude)"
                        :value="item.value">{{ item.label }}
              </checkbox>
            </label>
          </view>
        </checkbox-group>
      </view>
    </view>
  </px-popup-bottom>

</template>

<style scoped lang="scss">
.uni-form-item .title {
  padding: 20rpx 0;
}

.uni-picker-tips {
  font-size: 12px;
  color: #666;
  margin-bottom: 15px;
  padding: 0 15px;
  /* text-align: right; */
}

/*底部抽屉 报考方向内容 start*/
.professionalCategoryPopup .professionalCategoryItem {
  margin: 20rpx;
  padding: 20rpx;
  text-align: center;
  border: 1rpx solid #f1f2f3;

  .text {
    margin: 0 auto;
  }
}

.active {
  background-color: #3e89fe;
  color: white;
  border-radius: 15rpx;
}

.professionalCategoryChildren .childrenItem {
  margin: 20rpx;
}

/*底部抽屉 报考方向内容 end*/
</style>
