import {
  createStoreBindings
} from 'mobx-miniprogram-bindings'
import {
  store
} from '~/store/index'
let innerAudioContext
Page({

  /**
   * 页面的初始数据
   */
  data: {
    vState: false,
    vStart: '00:00',
    vEnd: '00:00',
    vProgress: 0,
    dState: false,
    dStart: '00:00',
    dEnd: '00:00',
    dProgress: 0,
    currentType: '',
    victory: {},
    defeated: {},
    equal: false
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options);
    this.storeBindings = createStoreBindings(this, {
      store,
      fields: {
        userInfo: 'userInfo',
        readDetail: 'readDetail',
        pkData: 'pkData'
      },
    })
    this.storeBindings.updateStoreBindings()
    this.compareScore()
    this.innerAudioContext = wx.createInnerAudioContext()
  },
  compareScore() {
    let pkData = this.data.pkData
    let score = pkData.score
    let myResult = {
      audioPath: this.data.readDetail.tempFilePath,
      nickName: this.data.userInfo.nickName || this.data.userInfo.uid,
      avatar: this.data.userInfo.avatar,
      score: this.data.readDetail.myOverall || 97
    }
    this.setData({
      equal: score == myResult.score,
      victory: myResult.score > score ? myResult : pkData,
      defeated: myResult.score <= score ? myResult : pkData,
    })
  },
  playAudio({
    currentTarget
  }) {
    let type = currentTarget.dataset.type
    // 重置音频对象
    if (type != this.data.currentType) {
      this.innerAudioContext.stop();
    }
    // 处理音频播放
    if (type == 'victory' && !this.data.vState) {
      if (this.data.currentType != 'victory') {
        this.innerAudioContext.src = this.data.victory.audioPath
      }
      this.setData({
        vState: true,
        dState: false
      })
    } else if (type == 'victory' && this.data.vState) {
      this.innerAudioContext.pause();
      return this.setData({
        vState: false
      })
    } else if (type == 'defeated' && !this.data.dState) {
      if (this.data.currentType != 'defeated') {
        this.innerAudioContext.src = this.data.defeated.audioPath;
      }
      this.setData({
        dState: true,
        vState: false
      })
    } else if (type == 'defeated' && this.data.dState) {
      this.innerAudioContext.pause();
      return this.setData({
        dState: false
      })
    }
    this.setData({
      currentType: type
    })
    // this.innerAudioContext.onCanplay(() => {
    this.innerAudioContext.play();
    // })
    this.innerAudioContext.onTimeUpdate(() => {
      this.setDuration(this.innerAudioContext.currentTime)
    })
  },
  // 设置时间文案
  setDuration(s) {
    let t = '';
    s = Math.floor(s);
    if (s > -1) {
      let min = Math.floor(s / 60) % 60;
      let sec = s % 60;
      if (min < 10) {
        t += "0";
      }
      t += min + ":";
      if (sec < 10) {
        t += "0";
      }
      t += sec;
    }
    let label = this.data.currentType == 'victory' ? 'vStart' : 'dStart'
    let progressV = this.data.currentType == 'victory' ? 'vProgress' : 'dProgress'
    this.setData({
      [label]: t,
      [progressV]: Math.round((this.innerAudioContext.currentTime / this.innerAudioContext.duration) * 100)
    })
  },
  result() {
    wx.redirectTo({
      url: `/pages/reading/index?videoId=${this.data.pkData.exampleId}&readingType=pk&reset=true`,
    })
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.innerAudioContext.destroy()
  },
  creatShare() {
    return new Promise((resolve, reject) => {
      let context = wx.createSelectorQuery();
      context
        .select('#share')
        .fields({
          node: true,
          size: true
        }).exec((res) => {
          const canvas = res[0].node;
          const ctx = canvas.getContext('2d');
          const dpr = wx.getSystemInfoSync().pixelRatio;
          canvas.width = res[0].width * dpr;
          canvas.height = res[0].height * dpr;
          ctx.scale(dpr, dpr);
          ctx.font = '16px PingFang';
          let bgImg = canvas.createImage();
          bgImg.src = this.data.equal ? 'https://reader-wx.ai160.com/images/reader/v3/equal.png' : 'https://reader-wx.ai160.com/images/reader/v3/victory.png'
          bgImg.onload = () => {
            ctx.drawImage(bgImg, 0, 0, 375, 300);
            ctx.textAlign = "center";
            var lnamex = this.data.equal ? 100 : 100,
              lnamey = this.data.equal ? 125 : 115;
            ctx.fillText(this.data.victory.nickName, lnamex, lnamey)
            var rnamex = this.data.equal ? 280 : 280,
              rnamey = this.data.equal ? 125 : 140;
            ctx.fillText(this.data.defeated.nickName, rnamex, rnamey)
            ctx.font = '19px PingFang';
            var lnumx = this.data.equal ? 100 : 100,
              lnumy = this.data.equal ? 150 : 140;
            ctx.fillText(this.data.victory.score + '分', lnumx, lnumy)
            var rnumx = this.data.equal ? 280 : 280,
              rnumy = this.data.equal ? 150 : 165;
            ctx.fillText(this.data.defeated.score + '分', rnumx, rnumy)
            ctx.font = '13px PingFang';
            var ltimex = this.data.equal ? 136 : 136,
              ltimey = this.data.equal ? 252.5 : 239.5;
            ctx.fillText(this.data.vEnd, ltimex, ltimey)
            var rtimex = this.data.equal ? 320 : 320,
              rtimey = this.data.equal ? 253 : 267;
            ctx.fillText(this.data.dEnd, rtimex, rtimey)
            // 圆形位置 大小
            var size = 55;
            var lx = this.data.equal ? 71 : 72,
              ly = this.data.equal ? 45 : 38;
            var rx = this.data.equal ? 252 : 247,
              ry = this.data.equal ? 45 : 60;
            ctx.save(); // 保存
            ctx.arc(size / 2 + lx, size / 2 + ly, size / 2, 0, Math.PI * 2, false);
            ctx.arc(size / 2 + rx, size / 2 + ry, size / 2, 0, Math.PI * 2, false);
            ctx.clip();
            let leftImg = canvas.createImage();
            leftImg.src = this.data.victory.avatar
            leftImg.onerror = () => {
              loadRightImg()
            }
            leftImg.onload = () => {
              ctx.drawImage(leftImg, lx, ly, size, size)
              loadRightImg()
            }

            let loadRightImg = () => {
              let rightImg = canvas.createImage();
              rightImg.src = this.data.defeated.avatar
              rightImg.onload = () => {
                ctx.drawImage(rightImg, rx, ry, size, size)
                setTimeout(() => {
                  wx.canvasToTempFilePath({
                    canvas: canvas,
                    success(res) {
                      resolve({
                        title: '请欣赏我的课文朗读作品,点赞+评论。',
                        path: `/pages/pkResult/index?uid=${wx.getStorageSync('uid')}`,
                        imageUrl: res.tempFilePath
                      })
                    },
                    fail(res) {
                      reject()
                    }
                  }, this)
                }, 500)
              }
              rightImg.onerror = () => {
                setTimeout(() => {
                  wx.canvasToTempFilePath({
                    canvas: canvas,
                    success(res) {
                      resolve({
                        title: '请欣赏我的课文朗读作品,点赞+评论。',
                        path: `/pages/pkResult/index?uid=${wx.getStorageSync('uid')}`,
                        imageUrl: res.tempFilePath
                      })
                    },
                    fail(res) {
                      reject()
                    }
                  }, this)
                }, 500)
              }
            }
          }
        })
    })
  },
  onShareAppMessage({
    from,
    target
  }) {
    if (from == 'button') {
      const promise = new Promise(resolve => {
        this.creatShare().then(res => {
          resolve(res)
        })
      })
      return {
        title: '课文朗读,从未如此有趣。',
        path: `/pages/index/index?uid=${wx.getStorageSync('uid')}`,
        imageUrl: 'http://reader-wx.ai160.com/images/reader/v3/shareContent.png',
        promise
      }
    } else {
      return {
        title: '课文朗读,从未如此有趣。',
        path: `/pages/index/index?uid=${wx.getStorageSync('uid')}`,
        imageUrl: 'http://reader-wx.ai160.com/images/reader/v3/shareContent.png'
      }
    }
  },
})