import httpRequestApi from '../../../utils/APIClient';
import {
  formatDate
} from '../../../utils/util';
import {
  getOpenidSessionKey
} from '../../../utils/httpUtil';
const app = getApp()
Page({
  data: {
    fullScreenBtn: false,
    playBtn: true,
    gesture: true,
    centerBtn: true,
    controls: true,
    videoLoad: false,
    autoPlay: true,
    videoUrl: '',
    poster: '',
    works: [],
    total: '',
    title: '',
    id: '',
    iconImg: '',
    pageNo: 1,
    totalNo: 0,
    collectFlag: false,
    goBackHome: false,
    lazyVideoUrl: '',
    isIOS: app.globalData.isIOS,
    modalType: "text",
    hide: true,

    modalText: [{
        text: '您还不是本课程的会员',
        type: 'bigOrange'
      },
      {
        text: '您可以开团,拼团成功获得使用权',
        type: 'normal'
      }
    ],
    modalBtnText: '去开团',
    isModalShow: false,
    productId: 0,
    videoPlayTime: 0
  },
  jurisdiction: function() {
    //隐藏弹框
    this.setData({
      hide: !this.data.hide
    })
    //登录页信息
    this.goToReading()
  },
  onLoad: function (option) {
    console.log(option);
    if (option.scene || option.shareCard) {
      this.setData({
        goBackHome: true
      })
    }
    this.setData({
      // title: option.title,
      id: option.id
    })

    this.uid = wx.getStorageSync('uid');;


    httpRequestApi.getClassDetail(this.uid, option.id).success(res => {
      console.log(res);
      const classId = this.data.id;
      httpRequestApi.userIntoPage('pages/main/class/class', '官方课程页面').success((res) => {

      })
      this.setData({
        title: res.data.data.lesson.title,
        videoUrl: res.data.data.lesson.playUrl,
        iconImg: res.data.data.lesson.iconImg,
        productId: res.data.data.product.id
      })
      wx.setNavigationBarTitle({
        title: res.data.data.lesson.title //页面标题为路由参数
      })

      this.getReadInfo(1, 10);
      this.checkLike();
      // this.innerAudioContext = wx.createInnerAudioContext();
      // this.innerAudioContext.onPause((res) => {
      //   // 播放音频失败的回调
      //   console.log('音频暂停')
      // });
      // this.innerAudioContext.onPlay(res => {
      //   console.log('class页面视频播放了')
      // })
    })
  },
  // video组件在获得url时迅速退出页面会导致小程序闪退,官方还没修复(11/28),处理办法:懒加载思路,在用户点击时再获取videoUrl
  // setVideoUrl: function(){
  //   console.log('视频地址>>>>>>>>',this.data.lazyVideoUrl)
  //   this.setData({
  //     videoUrl: this.data.lazyVideoUrl,
  //   })
  // },
  videoPlayHandler: function () {
    this.setData({
      videoLoad: true
    }, () => {
      this.videoClassCtx = wx.createVideoContext('classVideo', this);
      this.videoClassCtx.play();
    })
  },
  // 检查是否收藏
  checkLike: function () {
    httpRequestApi.classIsLike(this.uid, {
      targetCode: this.data.id
    }).success(res => {
      this.setData({
        collectFlag: res.data.data
      })
    })
  },
  goToReading: function () {
    
    getOpenidSessionKey((res) => {
      httpRequestApi.getUserAuth().success(res => {
        if (res.data.success) {
          const that = this;
          wx.authorize({
            scope: 'scope.record',
            success () {
                // 用户已经同意小程序使用录音功能,后续调用 wx.startRecord 接口不会弹窗询问
                console.log('成功')
                wx.navigateTo({
                  url: `../../main/reading/reading?id=${that.data.id}`
                })
            },
            fail () {
                wx.showModal({
                    title: '录音前请打开麦克风权限',
                    content: '点击右上角浮点...,选择:设置-麦克风,点击/打开。',
                    confirmText: '我知道了',
                    showCancel: false,
                    success(res) {
                        console.log('用户点击确定')
                    }
                })
            }
          })
        } else {
          console.log('chulaiba')
          if(this.data.isIOS){
            wx.navigateTo({
              url: `../../vipPage/wechat/wechat`
            })
          }else{
            this.setData({
              modalType: 'androidVIP',
              isModalShow: true
          })
          }
          
        }
      })
    }, (error) => {
        this.setData({
            hide: !this.data.hide
        })
        if (this.videoClassCtx) {
          this.videoClassCtx.stop();
        }
        return;
    });


  },
  modalConfirmHandler: function () {
    this.setData({
      isModalShow: false
    })
    if(this.data.isIOS){
      // wx.navigateTo({
      //   url: `../../vipPage/vipCode/vipCode`
      // })
      wx.navigateTo({
        url: `../../vipPage/wechat/wechat`
      })
    }else{
      wx.navigateTo({
        url: `../../vipPage/vip/vip`
      })
    }
   
  },
  modalCloseHandler: function () {
    this.setData({
      isModalShow: false
    })
  },
  openShare: function (e) {
    // this.setData({
    //     shareFlag: !this.data.shareFlag
    // })
    this.shareDialog = this.selectComponent("#share-dialog");
    const data = {
      avatar: this.data.authorAvatar,
      author: this.data.author,
      iconImg: this.data.iconImg,
      title: this.data.title,
      path: `pages/social/works/works?id=${this.data.id}&title=${this.data.title}`
      // tip: this.data.tip,
    }
    this.shareDialog.share(data);
  },
  onShareAppMessage: function (res) {
    console.log(this.data.productId)
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: '老师同学都在玩的配音show,你还在等什么?',
      path: `pages/main/class/class?id=${this.data.id}&title=${this.data.title}&shareCard=true`,
      imageUrl: `https://efunbox.lingjiao.cn/reader/resource/share/lesson_${this.data.productId}.jpg`
    }
  },
  goToWorks: function (e) {
    console.log(this.data.works)
    // this.videoClassCtx = wx.createVideoContext('myVideo', this);
    if (this.videoClassCtx) {
      this.videoClassCtx.stop();
    }
    console.log(e);
    let readId = e.currentTarget.dataset.id;
    let title = this.data.title;
    wx.navigateTo({
      url: `../../social/works/works?id=${readId}&title=${title}`
    })
  },
  collect: function (e) {
    // let uid =  wx.getStorageSync('uid');
    let data = {
      targetCode: this.data.id,
      // title: this.data.title,
      // iconImg: this.data.iconImg
    }
    httpRequestApi.collectClass(this.uid, data).success(res => {
      this.setData({
        collectFlag: !this.data.collectFlag
      })
    })
  },
  getReadInfo: function (pageNo, pageSize) {
    // const uid =  wx.getStorageSync('uid');
    const data = {
      lessonId: this.data.id,
      pageNo: this.data.pageNo,
      pageSize: 10
    };
    httpRequestApi.getClassRead(this.uid, data).success(res => {
      const readInfo = res.data.data.list;
      const readTemp = [];
      readInfo.forEach(item => {
        const temp = {};
        temp.nickName = item.user.wechatName;
        temp.time = formatDate(item.userRead.gmtCreated, 3);
        temp.avatar = item.user.avatar;
        temp.likes = item.userRead.playAmount ? item.userRead.playAmount : 0;
        temp.uid = item.userRead.uid;
        temp.id = item.userRead.id;
        this.data.works.push(temp);
      });
      this.setData({
        totalNo: res.data.data.totalNo,
        total: res.data.data.totalSize,
        works: this.data.works
      })
    });
  },
  // 下拉加载
  onReachBottom: function (e) {
    console.log(this.data.totalNo);
    this.setData({
      pageNo: this.data.pageNo + 1
    })
    if (this.data.pageNo <= this.data.totalNo) {
      this.getReadInfo();
    }
  },
  // 视频时间变动
  videoTimeChange: function (e) {
    this.videoPlayTime = e.detail.currentTime;
  },
  onHide: function () {
    let videoClassCtx = wx.createVideoContext('classVideo', this);
    videoClassCtx.stop();
  },
  onUnload: function () {
    if (this.videoPlayTime) {
      const data = {
        "title": this.data.title,
        "lessonId": this.data.id,
        "productId": this.data.productId,
        "playStopTime": this.videoPlayTime || 0,
        "type": 'EXAMPLE',
      }

      httpRequestApi.playLogReport(data).success(res => {
        console.log(res)
      })
    }


  }
})