<template>
  <div style="width: 90%; margin:0 auto" >
    <div class="zhiyuan-filter">
      <div class="header">
        <h3 class="f-666">您的选考科目为：<em>{{ formSubject.firstSubject }}<em v-for="item in formSubject.lastSubject"
        >,{{ item }}</em> </em>， 请手动选择志愿</h3>
      </div>
      <div class="filters">
        <!-- 院校筛选条件 -->
        <filter-form :filter="filter_form" :levelHide="true"></filter-form>
        <!--其他筛选 -->
        <el-row class="radioInput">
          <div>
            <span class="radiaTitle">院校层次:</span>
          </div>
          <el-radio-group v-model="filter_form.pickType">
            <el-radio-button label="">所有</el-radio-button>
            <el-radio-button v-for="item in localFilters.picks" :key="item.value" :label="item.value" style="margin-bottom:10px"
            >
              {{ item.label }}
            </el-radio-button>
          </el-radio-group>
        </el-row>
        <!-- 专业 -->
        <el-row class="radioInput">
          <div>
            <span class="radiaTitle">专业类别:</span>
          </div>
          <el-radio-group v-model="currentMajor">
            <el-radio-button label="">
              <span @click="clear">所有</span></el-radio-button>
            <el-radio-button v-for="item in majorList" :key="item.code" :label="item.code" style="margin-bottom:10px">
              {{ item.name }}
            </el-radio-button>
          </el-radio-group>
        </el-row>
        <!--    专业子类    -->
        <el-row class="radioInput filter" v-if="childrenMajors.length">
          <div>
            <span class="radiaTitle"></span>
          </div>
          <div class="items fx-row">
            <div class="no_limited">
              <el-checkbox @change="changeAll"   v-model="isAll">全部</el-checkbox>
            </div>
            <el-checkbox-group v-model="checkedList" :max="10">
              <el-checkbox  v-for="item in childrenMajors" :label="item.code" :key="item.code">{{item.name}}</el-checkbox>
            </el-checkbox-group>
          </div>
        </el-row>
      </div>
      <div class="selected">
         <span class="f14 f-666">您已选择：</span>
         <div class="tags" style="width: 100%">
           <el-tag  @close="handleClose(item)" type="success" class="mr5 mb5"  closable v-for="item in checkedListName">{{item.name}}</el-tag>
         </div>
        <el-button plain size="mini"  @click="getList">确认</el-button>
        <el-button plain size="mini"  @click="clear">清除</el-button>
      </div>
    </div>
    <div class="zhiyuan-list">
      <zhiyuan-list  :tableList="rows" @apply="apply" :cols="cols" @expand="expand"></zhiyuan-list>
    </div>
    <div :class="{'active':show,'right_cart': true}" >
      <div class="btn-wrap" @click="show = !show">
        当前志愿表
      </div>
      <transition name="content">
        <div class="content-wrap">
          <!--          <el-input class="input" v-model="input" placeholder="院校/专业搜索"></el-input>-->
          <div class="content">
            <div class="list-item" v-for="(college,collegeIndex) in this.formatZhiyuan">
              <div class="head-college f16">
                <el-tag type="success" size="mini" class="mr12">{{ collegeIndex + 1 }}</el-tag>
                {{ `${college.university.name}(${college.recruitPlan.collegeCode })` }}
                <i class="el-icon-delete delete-icon"></i>
              </div>
              <div class="majors f12">
                <div class="major mt10" v-for="(major,majorIndex) in college.majors">
                  <span class="mr12 ml10">{{majorIndex + 1}}</span>
                  {{major.marjorName}}
                  <i  class="el-icon-delete delete-icon" @click="deleteMajor(major)"></i>
                </div>
              </div>
            </div>
          </div>
          <div class="btn">
            <el-button style="width: 100%;height: 30px"  type="primary" @click="save">保存志愿表</el-button>
          </div>
        </div>
      </transition>
    </div>
  </div>
</template>
<script>
import FilterForm from '@/views/career/components/FilterForm';
import { Debounce, Throttle } from '@/utils/common.js'
import ZhiyuanList from '@/views/career/zhiyuan/components/zhiyuan-list';
import { allMajor,getRecommendVoluntary,getVoluntaryMarjors,getVoluntaryHeaders,saveZhiyuan } from '@/api/webApi/professlib'
export default {
  props: {
    formSubject: {
      type: Object,
      default: {}
    },
    batch: {
      type: Object,
      default: {}
    }
  },
  components:{
    FilterForm,
    ZhiyuanList
  },
  data() {
    return {
      indeterminate:false,
      checkedList:[],
      filter_form:{
        location:'',
        natureTypeCN:'',
        type:'',
        features:'',
        pickType:'',
      },
      currentMajor:'',
      majorList:[],
      show: false,
      localFilters: {
        picks: [
          { label: '冲刺型', value: '0' },
          { label: '稳妥型', value: '1' },
          { label: '保守型', value: '2' }
        ]
      },
      pageForm: {
        pageSize: 10,
        pageNum:1
      },
      total: 0,
      rows: [],
      cols: [],
      selectedList:[],
      loading:false
    }
  },
  created() {
    this.$nextTick(_ => {
      this.getAllMajor()
      this.getList()
      this.getCols()
    })
  },
  mounted() {
    let dom = document.querySelector(".el-table__body-wrapper");
    console.log(dom)
    dom.addEventListener("scroll", (v) => {
      const scrollDistance = dom.scrollHeight - dom.scrollTop - dom.clientHeight;
      console.log('scrollDistance',scrollDistance)
      // 判断是否到底，可以加载下一页
      if (scrollDistance <= 10) {
        this.load()
      }
    });
  },
  watch:{
    filter_form:{
      deep:true,
      handler(){
        this.getList()
      }
    },
    selectedList:{
      deep:true,
      handler(selectedList){
        const index= selectedList.findIndex(item => { return item.majors.filter(major =>{ return  major.selected }).length <= 0 })
        if(index != -1) {
          this.selectedList.splice(index,1)
        }
      }
    }
  },
  computed: {
    // 所有二级
    majorAllChildren() {
      let arr = []
      this.majorList.map(item => {
        arr = [...arr,...item.children]
      })
      return arr
    },
    checkedListName() {
      return this.majorAllChildren.filter(item => {
        return this.checkedList.findIndex(code => code == item.code) != -1
      }) || []
    },
    childrenMajors() {
      if(!this.currentMajor) return []
      return this.majorList.find(item => {
        return item.code == this.currentMajor
      }).children || []
    },
    formatZhiyuan() {
      if(!this.selectedList.length) return []
      return this.selectedList.map(item => {
        return {
          university: item.university,
          majors:item.majors.filter(major =>{ return  major.selected }),
          recruitPlan: item.recruitPlan
        }
      }).filter(item => {
        return  item.majors.length > 0
      })
    },
    isAll:{
      get(){
        // 当前children 全选
        let count = 0
        const childrenMajors = this.childrenMajors
        this.checkedList.forEach(item => {
          if(childrenMajors.findIndex(major => {return major.code == item}) != -1){
            count++
          }
        })
        console.log('选中数',count)
        return count == childrenMajors.length
      },
      set(){

      }
    },
  },
  methods: {
    load() {
      if (Math.ceil(this.total / this.pageForm.pageSize) > this.pageForm.pageNum) {
        // 标识正在请求

        // 加载下一页方法
        if(!this.loading){
          //当前页数小于总页数就请求
          this.pageForm.pageNum++; //当前页数自增
          this.getList('push')
        }
      }else {
        this.$message.warning("已经见底了 ～");
      }
    },
    save(){
      const wishes = this.selectedList.map(item =>{
        return {
          universityId:item.university.id,
          collegeCode: item.recruitPlan.collegeCode,
          code:item.university.code,
          name:item.university.name,
          marjors:item.majors.filter(major => {return major.selected}).map(major=> {
            return {
              id: major.id,
              code: major.marjorBelongs,
              name: major.marjorName,
            }
          })
        }
      })
      const data = {
        batch: this.batch.batch,
        detail:{
          batch:{
            batch:this.batch.batch,
            name:this.batch.name,
            recommand: true,
            scores:[],
            wishes:wishes,
          },
          mode:`${this.formSubject.firstSubject},${this.formSubject.lastSubject}`,
          score:this.batch.score1
        },
        id: 0,
        name: ''
      }
      saveZhiyuan(data).then(res =>{
        this.$router.push({ name:'VolunteerList' })
      })
    },
    apply(item,index) {
      //  有无院校  ？
      const codeFlag = this.selectedList.find(item => item.recruitPlan.collegeCode == this.rows[index].recruitPlan.collegeCode)
      console.log(!codeFlag)
      if(!codeFlag){
        this.selectedList.push(this.rows[index])
      }
      item.selected = !item.selected
    },
    deleteMajor(major){
      major.selected = false
    },
    expand(item) {
      console.log(item)
      if(item.isExpand) {
        // 取消
        return
      }else {
        item.isExpand = true
        this.getVoluntaryMarjors(item)
      }
    },
    getCols() {
      getVoluntaryHeaders({
        mode:`${this.formSubject.firstSubject},${this.formSubject.lastSubject}`,
        year: this.batch.year
      }).then(res => {
          this.cols = res.data
      })
    },
    getList(type) {
      this.loading = true
      const data = {
        batchName: this.batch.name,
        batch: this.batch.batch,
        majors: this.checkedList,
        mode: `${this.formSubject.firstSubject},${this.formSubject.lastSubject}`,
        // mode1: string,
        pickType:  this.filter_form.pickType,
        // "rank": 0,
        score: this.formSubject.score,
        university: {
          // "code": "string",
          features: this.filter_form.features,
          level: this.filter_form.level,
          location: this.filter_form.location,
          type: this.filter_form.type,
          natureTypeCN: this.filter_form.natureTypeCN,
          // "status": 0,
          // "type": "string"
        },
      }
      getRecommendVoluntary({ ...data }, { ...this.pageForm }).then(res =>{
        console.log(res)
        this.total = res.total
        let rows = {}
        rows = res.rows.map(item => {
          item.isExpand = false
          item.majors = []
          return item
        })
        // 回显
        if(this.selectedList.length) {
          rows = rows.map(row => {
           const flagIndex =  this.selectedList.findIndex(selected => {
              return selected.recruitPlan.collegeCode == row.recruitPlan.collegeCode
            })
            if(flagIndex == -1) {
              return row
            }else {
              return this.selectedList[flagIndex]
            }
          })
        }
        if(type == 'push') {
          this.rows.push(...rows)
          return
        }
        this.rows = rows
      }).finally(_ => {
        this.loading = false
      })
    },
    getVoluntaryMarjors(item) {
      getVoluntaryMarjors(
        {
          batchName: this.batch.name,
          collegeCode: item.recruitPlan.collegeCode,
          mode: this.formSubject.firstSubject,
          universityId: item.recruitPlan.universityId,
          year: item.recruitPlan.year,}
      ).then(res => {
        item.majors = res.data.map(item => {
          item.selected = false
          return item
        })
        console.log(res)
      })
    },
    handleClose(item) {
      const index = this.checkedList.findIndex(code => code == item.code)
      this.checkedList.splice(index,1)
    },
    clear() {
      if(!this.checkedList.length) return
      this.checkedList = []
      this.getList()
    },
    changeAll(val){
      const checkedList =  this.checkedList

      if(val) {
        // 添加
        this.childrenMajors.forEach(item => {
          if(this.checkedList.length >= 10) {
            this.$message.warning('最多选择10个专业')
            throw Error('最多选择10个专业')
          }
          if(this.checkedList.findIndex(code => code == item.code) == -1 ){
            this.checkedList.push(item.code)
          }
        })
      }else {
        // 移除
        this.childrenMajors.forEach(item => {
          for (let i = 0; i < checkedList.length; i++) {
            if(item.code == checkedList[i]){
              this.checkedList.remove(item.code)
            }
          }
        })
      }

      console.log(val)
    },
    handleCheckAllChange(val) {
      this.isIndeterminate = false;
    },
    getAllMajor(){
      allMajor({
        level:2,
        batch:this.batch.batch
      }).then(res => {
        this.majorList = res.data
        console.log(res)
      })
    },
  }
}
</script>

<style scoped lang="scss">
.more span {
  margin-right: 10px;
}
.selected{
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px;
  margin-bottom: 20px;
  background: #42b98340;
  span{
    flex-shrink: 0;
  }
}
.filters {
  padding: 10px 0px;
  border: 1px solid #eee;
}

.delete-icon{
  float: right;
  cursor: pointer;
}
.filter_name {
  box-sizing: border-box;
  width: 70px;
  font-size: 14px;
  line-height: 20px;
  flex: none;
  padding: 6px 0 6px 0;
  margin-right: 10px;
}

.zhiyuan-filter .filters .filter .items .no_limited {
  margin-right: 10px;
}

.zhiyuan-filter .filters .filter .items .no_limited ::v-deep .el-checkbox__input {
  display: none;
}

.filters .filter {
  padding: 10px 0;
  display: flex;
  border-bottom: 1px solid #eee;
}

.filters .filter:last-child {
  border-bottom: 0;
}

.zhiyuan-filter .filters .filter ::v-deep .el-checkbox, .zhiyuan-filter .filters .filter ::v-deep .el-radio {
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  height: 32px;
  padding: 8px 8px;
  margin: 0;
}

em {
  font-weight: 400;
  font-style: normal;
}

::v-deep .el-input--medium .el-input__inner {
  height: 30px;
  line-height: 30px;
}

::v-deep .el-input {
  width: 260px;
}

.radioInput ::v-deep {
  background-color: #ffffff;font-size: 14px;padding:5px;
  .el-radio {
    .el-radio__input {
      display: none;
    }
  }
}

.radioInput ::v-deep {
  display: flex;

  .el-radio-button .el-radio-button__inner {
    border-radius: 4px !important;
    border: none;
    padding: 5px 10px !important;
    font-weight: 400;
    font-family: PingFangSC-Regular, PingFang SC;
  }

  .el-radio-button__orig-radio:checked + .el-radio-button__inner {
    box-shadow: none;
  }

  .radiaTitle {
    display: inline-block;
    width: 80px;
    font-size: 14px;
    text-align: right;
    margin-top: 2px;
    margin-right: 10px;
  }
}
.right_cart{
  position: fixed;
  top: 50%;
  right: -320px;
  transform: translate(0%,-50%);
  transition: all 1s ease;
}
.active{
  right: 0;
}
.right_cart{
  display: flex;
  z-index: 9999;
}
.right_cart .btn-wrap{
  cursor: pointer;
  align-self: baseline;
  border-radius: 5px 0 0 5px;
  color: white;
  background: #42b983;
  width: 30px;
  text-align: center;
  font-size: 16px;
  padding: 7px;
}
.content-wrap{
  padding: 10px 0;
  background: #fff;
  width: 320px;
  height: 400px;
  display: flex;
  flex-direction: column;

  border: 1px solid #f2f2f2;
}
.content{
  height: 100%;
  overflow-y: auto;
  padding: 0 20px
}


.content-wrap .input{
  padding: 0 15px;
}

.content-wrap .btn{
  width: 100% ;
  padding: 0 15px;
}
.list-item{
  margin-bottom: 10px;
  border-bottom: 1px solid #e6e6e6;
  padding-bottom: 20px;
}

.mask{
  z-index: 2009;
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  overflow: auto;
  opacity: 0.5;
  margin: 0;
}
</style>
