<template>
  <div class="sign_in">
    <div class="header">
      <van-swipe class="my-swipe" indicator-color="white" v-if="baseInfo.coverList && baseInfo.coverList.length > 0">
        <van-swipe-item v-for="n in baseInfo.coverList" :key="n.id">
          <video v-if="n.cover_url.indexOf('.mp4') > -1" id="video" :src="n.cover_url" poster="" controls="controls" windowlessvideo="true" playsinline="true" webkit-playsinline="true" x5-playsinline="true" x-webkit-airplay="allow" width="100%" height="260px" type="video/mp4"></video>
          <img v-if="n.cover_url.indexOf('.mp4') == -1" :src="n.cover_url" />
        </van-swipe-item>
      </van-swipe>
      <img v-else src="@/assets/service/defCoure.jpg" alt="" />
    </div>
    <div class="base_info">
      <p class="base_title">{{baseInfo.baseName}}</p>
      <div class="rate">
        <van-rate v-model="baseInfo.baseScore" color="#FFCC00" :size="16" readonly />
        <span>{{ baseInfo.baseScore }}</span>
      </div>
      <p class="address">
        <van-icon name="location" class="icon" />
        {{baseInfo.address}}
      </p>
      <p class="phone">
        <van-icon name="phone" class="icon" />
        {{baseInfo.phone}}
      </p>
    </div>
    <div class="select_student" @click="selectStudent">
      <p class="select_tip">请选择需要打卡的孩子</p>
      <div class="student" v-if="selectedContact.travelerName">
        <span>{{selectedContact.travelerName}}</span>
        <van-icon name="close" class="icon" />
      </div>
      <div class="student" v-else>
        <span>点击选择</span>
      </div>
    </div>
    <div class="btns" @click="getPosition">立即打卡</div>
    <van-popup v-model="failShow" round closeable :style="{ width:'80%'}">
      <div class="success">
        <img src="@/assets/tip1.png" alt="">
        <h3>打卡失败！</h3>
        <p>您当前所在的地理位置不在课程的打卡范围内！</p>
      </div>
    </van-popup>
  </div>
</template>

<script>
export default {
  data () {
    return {
      baseInfo: '',
      list: [],
      baseId: '',
      userInfo: '',
      failShow: false,
      selectedContact: '',//选择的出行人

    }
  },
  mounted () {
    var userInfo = sessionStorage.getItem('userInfo');
    if (userInfo) {
      this.userInfo = JSON.parse(userInfo);
    }
    // 选择的出行人
    let selectedContactArr = sessionStorage.getItem('selectedContactArr');
    if (selectedContactArr) {
      selectedContactArr = JSON.parse(selectedContactArr);
      this.selectedContact = selectedContactArr[0]
    }
    this.baseId = this.$route.query.qrresult;
    this.GetStudyBaseDetail(this.baseId);
  },
  methods: {
    AddSign () {

      this.$toast.loading({
        message: '请求中...',
      });
      this.yxAxios.get(`${this.yanxueUrl}/api/BaseManage/AddSign?userId=${this.selectedContact.travelerNum}&baseId=${this.baseId}`).then((res) => {
        this.$toast.success('打卡签到成功');
        console.log(res.data)
        // alert('打卡签到成功:',JSON.stringify(res))
        setTimeout(() => {
          let publicName = sessionStorage.getItem('publicName');
          this.$router.push({ name: 'Home' + publicName })
        }, 1000)
      })
    },
    GetStudyBaseDetail (baseId) {
      this.$toast.loading({
        message: '请求中...',
      });
      this.yxAxios.get(`${this.yanxueUrl}/api/StudiesWap/GetStudyBaseDetail?userId=0&cs=绍兴市&id=${baseId}`).then((res) => {
        console.log(res.data)
        if (res.data.data) {
          this.$toast.clear();
          this.baseInfo = res.data.data;
        } else {
          this.$toast.fail(res.data.message)
        }
      })
    },
    getPosition () {
      if (!this.selectedContact.travelerNum) {
        this.$toast('请选择需要打卡的孩子');
        return false;
      }
      if (this.baseInfo.signLong == 0 && this.baseInfo.signLat == 0) {  //基地没数坐标
        this.AddSign();
        return false
      }
      var basePosition = [this.baseInfo.signLong, this.baseInfo.signLat];
      AMap.convertFrom(basePosition, 'baidu', function (status, result) {
        console.log(result)
        if (result.info === 'ok') {
          basePosition = [result.locations[0].lng, result.locations[0].lat]; // Array.<LngLat>
        }
      });
      this.$toast.loading({
        message: '请求中...',
      });
      this.getNowPosition((posi) => { //获取当前位置坐标
        this.$toast.clear();
        if (posi) {
          var nowPosition = [posi.position.lng, posi.position.lat];
          var distance = AMap.GeometryUtil.distance(nowPosition, basePosition);
          console.log(parseInt(distance), nowPosition, basePosition)
          if (parseInt(distance) > 500) {
            this.failShow = true;
          } else {
            // alert('定位小于500m')
            this.AddSign();
          }
        } else {
          // alert('getNowPosition没有返回')
        }
      });
    },
    getNowPosition: function (callback) {
      let mapObj = new AMap.Map('iCenter');
      mapObj.plugin('AMap.Geolocation', function () {
        let geolocation = new AMap.Geolocation({
          enableHighAccuracy: true,//是否使用高精度定位，默认:true
          timeout: 10000,          //超过10秒后停止定位，默认：无穷大
          maximumAge: 0,           //定位结果缓存0毫秒，默认：0
          convert: true,           //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
          showButton: true,        //显示定位按钮，默认：true
          buttonPosition: 'LB',    //定位按钮停靠位置，默认：'LB'，左下角
          buttonOffset: new AMap.Pixel(0, 0),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
          showMarker: true,        //定位成功后在定位到的位置显示点标记，默认：true
          showCircle: true,        //定位成功后用圆圈表示定位精度范围，默认：true
          panToLocation: true,     //定位成功后将定位到的位置作为地图中心点，默认：true
          zoomToAccuracy: true      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
        });
        mapObj.addControl(geolocation);
        geolocation.getCurrentPosition();
        AMap.event.addListener(geolocation, 'complete', function (res) {
          // alert('返回定位信息:' + JSON.stringify(res))
          console.log('返回定位信息:', res)
          callback(res);
        });//返回定位信息
        AMap.event.addListener(geolocation, 'error', function (res) {
          // alert('返回定位出错信息:' + JSON.stringify(res))
          console.log('返回定位出错信息:', res)
          callback();
        });      //返回定位出错信息
      })

    },
    // 选择孩子
    selectStudent () {
      this.$router.push({ name: 'SelectContact', query: { limit: 1, hideParent: 1 } })
    }
  }
}
</script>

<style lang="scss" scoped>
.sign_in {
  padding-bottom: 100px;
  .header {
    img {
      width: 100%;
    }
  }
  .base_info {
    width: 702px;
    margin: 0 auto;
    padding-top: 20px;
    .base_title {
      font-size: 34px;
      font-weight: bold;
    }
    .rate {
      margin-top: 20px;
      span {
        font-size: 30px;
        color: #ffcc00;
        margin-left: 30px;
      }
    }
    .address,
    .phone {
      font-size: 24px;
      color: #999;
      margin-top: 16px;
      .icon {
        color: #000;
      }
    }
  }
  .select_student {
    width: 702px;
    margin: 0 auto;
    margin-top: 30px;
    padding-top: 30px;
    border-top: 2px solid #d8d8d8;
    .select_tip {
      font-size: 30px;
      color: #999;
    }
    .student {
      position: relative;
      width: 532px;
      line-height: 78px;
      margin: 0 auto;
      margin-top: 24px;
      background: #f5f6fa;
      border-radius: 8px;
      font-size: 28px;
      text-align: center;
      .icon {
        position: absolute;
        top: 50%;
        right: 20px;
        transform: translateY(-50%);
      }
    }
  }

  .btns {
    width: 702px;
    margin: 0 auto;
    margin-top: 100px;
    text-align: center;
    line-height: 90px;
    border-radius: 100px;
    font-size: 30px;
    background: #4092ff;
    color: #fff;
  }
  .success {
    padding: 40px 0;
    text-align: center;
    img {
      width: 30%;
    }
    h3 {
      font-size: 36px;
    }
    p {
      font-size: 30px;
      color: #999999;
    }
  }
}
</style>
