<template>
  <div>
    <div class="addchild_group" v-if="step==1">
      <img class="bg" src="@/assets/home/bg2.png" alt="">
      <p class="title">添加学生</p>
      <p class="des">完善相关信息可帮助获得最佳使用体验 </p>
      <div class="phone_content">
        <div class="item">
          <p class="phone_title">手机号</p>
          <div class="flex">
            <input class="code phone" type="tel" maxlength="11" v-model="phone" placeholder="请输入您的手机号">
            <span class="getcode" @click="getCode">{{codeText}}</span>
          </div>
        </div>
        <div class="item">
          <p class="phone_title">验证码</p>
          <input class="code" type="text" v-model="code" placeholder="请输入验证码">
        </div>
        <button class="submit" @click="checkPhoneAndCode">下一步（1/2）</button>
      </div>
    </div>
    <div class="addchild_group" v-if="step==2">
      <img class="bg" src="@/assets/home/bg2.png" alt="">
      <p class="title">已查询到{{claimChildList.length}}位学生信息</p>
      <p class="des">请仔细确认学生信息后再认领</p>
      <div class="child_content">
        <div class="child_box">
          <div class="child_item" v-for="(item,index) in claimChildList" :key="index">
            <p><span>姓名</span>{{item.travelerName}}</p>
            <p><span>阶段</span>{{item.travelerType==1?'小学':item.travelerType==1?'初中':'高中'}}</p>
            <p><span>所在地区</span>{{item.province+item.city+item.area}}</p>
            <p><span>学校</span>{{item.schoolName}}</p>
            <p><span>入学年份</span>{{item.enrollYear}}</p>
            <van-checkbox class="checkbox" v-model="item.checked" shape="square"></van-checkbox>
          </div>
        </div>
        <button class="submit" @click="claimChild">认领</button>
      </div>
    </div>
    <div class="addchild_group" v-if="step==3">
      <img class="bg" src="@/assets/home/bg2.png" alt="">
      <p class="title">添加学生信息</p>
      <p class="des">如验证号码非学校预留号码，请按步骤自行添加完善学生信息。</p>
      <div class="content">
        <div class="name">学生信息</div>
        <div class="item">
          <input type="text" placeholder="请输入学生姓名" v-model="studentName">
        </div>
        <div class="item" @click="showUserTypeSelect=true" style="width:48%;display:inline-flex;margin-right:4%;">
          <p :class="!userType?'nodata':''">{{userType?userType:'当前阶段'}}</p>
          <img src="@/assets/more.png" alt="">
        </div>
        <div class="item" @click="handleYear" style="width:48%;display:inline-flex;">
          <p :class="!year||yearDisable?'nodata':''">{{year?year:'入学年份'}}</p>
          <img src="@/assets/more.png" alt="">
        </div>
        <div class="item" @click="showAreaSelect=true">
          <p :class="!area?'nodata':''">{{area?area:'请选择地区'}}</p>
          <img src="@/assets/more.png" alt="">
        </div>
        <div class="item">
          <input type="text" placeholder="请选择学校" readonly v-model="school">
          <button type="info" class="btn" @click="chooseSchool">选择学校</button>
        </div>
        <button class="submit" @click="submit">完成</button>
      </div>
    </div>
    <van-popup v-model="showUserTypeSelect" round position="bottom" get-container="body" :safe-area-inset-bottom="true">
      <van-picker title="当前阶段" show-toolbar :columns="userTypeArr" value-key="label" @cancel="showUserTypeSelect = false" @confirm="selectUserTypeOver" />
    </van-popup>
    <van-popup v-model="showYearSelect" round position="bottom" get-container="body" :safe-area-inset-bottom="true">
      <van-picker title="入学年份" show-toolbar :columns="yearArr" value-key="label" @cancel="showYearSelect = false" @confirm="selectYearOver" />
    </van-popup>
    <van-popup v-model="showAreaSelect" round position="bottom" get-container="body" :safe-area-inset-bottom="true">
      <van-area title="地区" :area-list="areaList" @cancel="showAreaSelect = false" @confirm="selectAreaOver" />
    </van-popup>

    <van-popup v-model="chooseSchoolisShow" round get-container="body" :safe-area-inset-bottom="true">
      <div v-if="chooseSchoolisShow">
        <chooseSchool v-model="chooseSchoolisShow" @schoolData='schoolData'></chooseSchool>
      </div>
    </van-popup>
  </div>
</template>

<script>

import chooseSchool from '@/views/PublicService/component/chooseSchool'
var codeInterval;
export default {
  components: { chooseSchool },
  data () {
    return {
      step: 1,
      publicName: '',
      phone: '',
      codeText: '获取验证码',//获取验证码按钮文字
      code: '',//验证码
      studentName: '',
      showDialog: true,

      claimChildList: [],

      year: '',//入学年份
      yearDisable: false,
      showYearSelect: false,
      yearArr: [],

      userType: '',
      userTypeVal: '',//所处阶段1-小学 2-初中 3-高中
      showUserTypeSelect: false,
      userTypeArr: [{
        label: '小学',
        value: 1
      }, {
        label: '初中',
        value: 2
      }, {
        label: '高中',
        value: 3
      }],

      area: '',
      areaCode: '',
      showAreaSelect: false,
      areaList: [],

      searchSchool: '',
      school: '',
      schoolId: '',

      appId: '',
      chooseSchoolisShow: false
    }
  },

  mounted () {
    let publicName = sessionStorage.getItem('publicName')
    this.publicName = publicName
    let userInfo = sessionStorage.getItem('userInfo')
    this.userInfo = userInfo ? JSON.parse(userInfo) : userInfo;
    this.initYearArr()
    this.GetSysAreaList()
  },
  methods: {
    // 获取验证码
    getCode () {
      if (this.codeText != '获取验证码') return;
      if (!this.phone) {
        this.$toast('请输入手机号')
        return;
      }
      if (!this.checkPhone(this.phone)) {
        this.$toast('请输入正确的手机号')
        return;
      }
      this.$toast.loading({
        message: '加载中',
        duration: 0,
        forbidClick: true
      })
      this.http.getMsg({
        phone: this.phone
      }).then((res) => {
        this.$toast.clear()
        if (res.success) {
          let i = 60;
          codeInterval = setInterval(() => {
            if (i == 0) {
              this.codeText = `获取验证码`;
              clearInterval(codeInterval);
              return;
            }
            this.codeText = `重试（${i}）`;
            i--
          }, 1000)
        } else {
          this.$toast.fail(res.message)
        }
      })
    },
    // 获取手机号白名单信息
    checkPhoneAndCode () {
      if (!this.phone) {
        this.$toast('请输入手机号')
        return;
      }
      if (!this.checkPhone(this.phone)) {
        this.$toast('请输入正确的手机号')
        return;
      }
      if (!this.code) {
        this.$toast('请输入验证码')
        return;
      }
      this.$toast.loading({
        message: '加载中',
        duration: 0,
        forbidClick: true
      })
      const userInfo = JSON.parse(sessionStorage.getItem('userInfo'))
      let openId = sessionStorage.getItem('openId' + this.publicName) || 'oHHbojtmLCNmOKwYBett8dXxhMlg';

      this.yxAxios.post(`${this.proxyUrl}/prod/user/info/checkPhoneAndCode`, {
        "code": this.code,
        "openId": openId,
        "phone": this.phone,
        "unionId": userInfo.unionId
      }).then((res) => {
        this.$toast.clear()
        if (res.data.code == 200) {
          if (res.data.data.length == 0) {
            // 白名单无用户
            this.step = 3;
          } else {
            // 白名单有用户
            let claimChildList = res.data.data
            for (let i in claimChildList) {
              claimChildList[i].checked = false
            }
            this.claimChildList = claimChildList
            this.step = 2;
          }
        } else {
          this.$toast.fail(res.data?.message)
        }
      })
    },


    // 认领孩子
    claimChild () {
      const claimChildList = this.claimChildList;
      let claimChildId = ''
      for (let i in claimChildList) {
        if (claimChildList[i].checked) {
          if (claimChildId == '') {
            claimChildId = claimChildList[i].travelerNum
          } else {
            claimChildId = claimChildId + ',' + claimChildList[i].travelerNum
          }
        }
      }
      this.$toast.loading({
        message: '加载中...',
        duration: 0,
        forbidClick: true
      })
      this.mgop({
        api: 'mgop.sz.hswsy.claimChildren', // 必须
        host: 'https://mapi.zjzwfw.gov.cn/',
        dataType: 'JSON',
        type: 'POST',
        appKey: 'fuxgnukl+2001895516+edccpx', // 必须
        headers: {
          //   'isTestUrl': '1'
        },
        data: {
          "loginMobile": this.phone,
          "subUserNums": claimChildId
        },
        onSuccess: res => {
          this.$toast.clear()
          if (res.data.code == 200) {
            this.$toast.success('认领成功')
            this.$emit('complete')
          } else {
            this.$toast.fail(res.data?.message)
          }
        },
        onFail: err => {
          console.log('err', err)
        }
      });
    },


    // 初始化入学年份选项
    initYearArr () {
      // 页面创建时执行
      let year = new Date().getFullYear(),
        Month = new Date().getMonth() + 1,
        yearArr = [];
      if (Month > 8) {
        // 如果月份大于8,那么当年的学年的高考年份要+1,如果月份小于7,那么当前的年份就是今年高考的年份
        year = year
      }
      for (let index = year; index > year - 6; index--) {
        yearArr.push({ value: index, label: index })
      }
      this.yearArr = yearArr
    },
    selectYearOver (value) {
      this.year = value.label;
      this.showYearSelect = false;
    },
    handleYear () {
      if (!this.yearDisable) {
        this.showYearSelect = true;
      }
    },
    selectUserTypeOver (value) {
      this.userType = value.label;
      this.userTypeVal = value.value;
      this.showUserTypeSelect = false;
    },
    // 获取地区列表
    GetSysAreaList () {
      this.mgop({
        api: 'mgop.sz.hswsy.GetSysAreaList', // 必须
        host: 'https://mapi.zjzwfw.gov.cn/',
        dataType: 'JSON',
        type: 'GET',
        appKey: 'fuxgnukl+2001895516+edccpx', // 必须
        headers: {
          //   'isTestUrl': '1'
        },
        data: {
          "areaCode": 33
        },
        onSuccess: res => {
          console.log('获取地区列表', res)
          if (res.data.success) {
            let data = res.data.data;
            let obj = {
              province_list: {
                330000: '浙江省'
              },
              city_list: {},
              county_list: {}
            };
            if (data) {
              data.forEach((n, i) => {
                obj.city_list[n.area_code + '00'] = n.area_name;
                if (n.areaList.length > 0) {
                  n.areaList.forEach((k, j) => {
                    obj.county_list[k.area_code] = k.area_name;
                  })
                }
              });
              this.areaList = obj;
            }
          } else {
            this.$toast.fail(res.message)
          }
        },
        onFail: err => {
          console.log('err', err)
        }
      });
    },
    selectAreaOver (value) {
      let data = value;
      var city = data[1].code;
      city = city.substring(0, city.length - 2);
      // console.log(city)
      this.area = data[0].name + ',' + data[1].name + ',' + data[2].name;
      this.areaCode = [data[0].code, city, data[2].code];
      this.quCode = data[2].code;
      this.school = '',
        this.schoolId = '',
        this.showAreaSelect = false
    },

    submit () {
      if (!this.studentName) {
        this.$toast('请输入姓名');
      }
      else if (!this.userType) {
        this.$toast('请选择阶段');
      }
      else if (!this.year) {
        this.$toast('请选择入学年份');
      }
      else if (!this.area) {
        this.$toast('请选择地区');
      }
      else if (!this.school) {
        this.$toast('请选择学校');
      } else {
        let postData = {
          contactsName: this.studentName,
          contactsMobile: this.phone,
          contactsType: 1,
          province: this.area.split(',')[0],//省份
          city: this.area.split(',')[1],//城市
          area: this.area.split(',')[2],//地区
          schoolName: this.school,//学校名称
          enrollYear: this.year,//入学年份
          travelerType: this.userTypeVal,//1-小学 2-初中 3-高中

        }
        this.$toast.loading({
          message: '加载中',
          duration: 0,
          forbidClick: true
        })
        this.mgop({
          api: 'mgop.sz.hswsy.addStudent', // 必须
          host: 'https://mapi.zjzwfw.gov.cn/',
          dataType: 'JSON',
          type: 'GET',
          appKey: 'fuxgnukl+2001895516+edccpx', // 必须
          headers: {
            //   'isTestUrl': '1'
          },
          data: postData,
          onSuccess: res => {
            console.log('添加学生：', res)
            this.$toast.clear()
            if (res.data.code == 200) {
              this.$toast.success('添加学生成功')
              this.$emit('complete')
            } else {
              this.$toast.fail(res.data?.message)
            }
          },
          onFail: err => {
            console.log('err', err)
          }
        });
      }
    },
    //选择学校
    chooseSchool () {
      // this.$router.push({name: 'chooseSchool'})
      this.chooseSchoolisShow = true
    },
    schoolData (val) {
      this.school = val.text;
      this.schoolId = val.id;
    },
    checkPhone (phone) {
      if ((/^1[3456789]\d{9}$/.test(phone))) {
        return true
      } else {
        return false
      }
    },
  },
  destroyed () {
    clearInterval(codeInterval);
  },
}
</script>
<style lang="scss" scoped>
.addchild_group {
  width: 638px;
  height: 836px;
  background: #ffffff;
  border-radius: 24px;
  position: relative;
  .bg {
    width: 100%;
    position: absolute;
    top: 0;
    left: 0;
  }
  .title {
    position: relative;
    width: 100%;
    padding-top: 70px;
    padding-bottom: 8px;
    text-align: center;
    font-size: 34px;
    font-weight: bold;
    color: #0857ff;
  }
  .des {
    position: relative;
    width: 100%;
    box-sizing: border-box;
    padding: 0 15%;
    text-align: center;
    font-size: 24px;
    color: #6596ff;
  }
  .content {
    width: 100%;
    box-sizing: border-box;
    padding: 0 40px;
    position: absolute;
    top: 236px;
    left: 0;
    .name {
      width: 558px;
      height: 50px;
      font-size: 28px;
      color: #000;
      padding-left: 20px;
      box-sizing: border-box;
    }
    .item {
      width: 558px;
      height: 72px;
      border-radius: 36px;
      background: #f7f7f7;
      box-sizing: border-box;
      font-size: 28px;
      padding: 0 32px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 28px;
      p {
        color: #333333;
        &.nodata {
          color: #999999;
        }
      }
      img {
        width: 40px;
      }
      input {
        width: 100%;
        background: transparent;
        border: 0;
        color: #333333;
        padding: 0;
        &::-webkit-input-placeholder {
          color: #999999;
        }
      }
      .btn {
        width: 240px;
        height: 55px;
        float: right;
        font-size: 28px;
        background: linear-gradient(135deg, #cdf8cf 0%, #8af36f 100%);
        box-shadow: 0px 4px 8px 0px rgba(189, 189, 189, 0.5),
          0px 8px 12px 0px rgba(89, 199, 171, 0.5);
        border-radius: 34px;
        border: transparent;
        color: #333333;
      }
    }
    .school_select {
      font-size: 28px;
      padding: 0 32px;
      margin-bottom: 28px;
    }
    .submit {
      width: 294px;
      height: 72px;
      border: 0;
      background: linear-gradient(135deg, #99c2ff 0%, #1f59ff 100%);
      box-shadow: 0px 4px 8px 0px rgba(189, 189, 189, 0.5),
        0px 8px 12px 0px rgba(87, 137, 255, 0.5);
      border-radius: 34px;
      font-size: 34px;
      color: #ffffff;
      margin: 0 auto;
      display: block;
    }
  }
  .child_content {
    position: relative;
    margin-top: 40px;
    .child_box {
      height: 500px;
      overflow: auto;
      padding-left: 100px;
      .child_item {
        position: relative;
        margin-bottom: 50px;
        p {
          font-size: 28px;
          padding: 8px 0;
          span {
            display: inline-block;
            width: 140px;
            margin-right: 28px;
            color: #999;
          }
        }
        .checkbox {
          position: absolute;
          top: 115px;
          right: 20px;
        }
      }
    }
    .submit {
      width: 438px;
      height: 78px;
      background: #3385ff;
      border-radius: 37px;
      border-radius: 39px;
      border: 0;
      font-size: 34px;
      color: #ffffff;
      margin: 0 auto;
      display: block;
    }
  }
  .phone_content {
    width: 100%;
    position: absolute;
    top: 180px;
    left: 0;
    box-sizing: border-box;
    padding: 40px;
    .item {
      border-bottom: 1px solid #e2e2e2;
      margin-bottom: 30px;
    }
    .phone_title {
      font-size: 34px;
      font-weight: bold;
      margin-bottom: 28px;
    }
    .flex {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 22px;
    }
    .code {
      border: 0;
      background: transparent;
      font-size: 28px;
      margin-bottom: 32px;
      width: 100%;
    }
    .phone {
      width: 50%;
      margin: 0;
    }
    .getcode {
      color: #5789ff;
      font-size: 28px;
      padding: 10px;
    }
    .submit {
      width: 438px;
      height: 78px;
      background: #3385ff;
      border-radius: 37px;
      border-radius: 39px;
      border: 0;
      font-size: 34px;
      color: #ffffff;
      margin: 0 auto;
      margin-top: 120px;
      display: block;
    }
  }
}
::v-deep .van-search {
  background: transparent;
  padding: 0;
  width: 100%;
}
::v-deep .van-search__content {
  padding: 0;
}
.schoolBoxF {
  width: 100vw;
  height: 100vh;
  position: absolute;
  top: 0;
  left: 0;
  background-color: #fff;
}
</style>
