import {
  getPkResult
} from '~/api/works'
import {
  setDuration
} from '~/utils/util'
import {
  userEvent
} from '~/api/global'
let innerAudioContext
Page({
  /**
   * 页面的初始数据
   */
  data: {
    pkId: '',
    pkRecord: {},
    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,
    // 是否是分享进来的
    isPlayback: false
  },
  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    let {
      pkRecord,
      pkRecordVOS
    } = await getPkResult(options.id)
    this.setData({
      pkId: options.id,
      pkRecord,
      isplayback: options.playback || false
    })
    this.compareScore(pkRecordVOS)
    this.innerAudioContext = wx.createInnerAudioContext()
    await userEvent({
      action: 'WXPKSCORE',
    })
  },
  compareScore(resultData) {
    let first = resultData[0]
    let second = resultData[1]
    let victory = first.userRead.score > second.userRead.score ? first : second
    let defeated = second.userRead.score < first.userRead.score ? second : first
    this.setData({
      equal: first.userRead.score == second.userRead.score,
      victory: first.userRead.score > second.userRead.score ? first : second,
      defeated,
      vEnd: setDuration(victory.userRead.duration),
      dEnd: setDuration(defeated.userRead.duration),
    })
  },
  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.userRead.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.userRead.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(() => {
      let label = this.data.currentType == 'victory' ? 'vStart' : 'dStart'
      let progressV = this.data.currentType == 'victory' ? 'vProgress' : 'dProgress'
      this.setData({
        [label]: setDuration(this.innerAudioContext.currentTime),
        [progressV]: Math.round((this.innerAudioContext.currentTime / this.innerAudioContext.duration) * 100)
      })
    })
  },
  result({
    currentTarget
  }) {
    if (currentTarget.dataset.type == 'reading') {
      wx.redirectTo({
        url: `/pages/reading/index?videoId=${this.data.victory.userRead.exampleId}&readingType=pk`,
      })
    } else if (currentTarget.dataset.type == 'index') {
      wx.switchTab({
        url: '/pages/index/index',
      })
    } else {
      wx.redirectTo({
        url: `/pages/pkPage/index?videoId=${this.data.pkRecord.challengerUserReadId}&isShare=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;
            var vName = this.data.victory.user.nickName || this.data.victory.user.eid
            if (vName.length > 4) {
              vName = vName.slice(0, 4) + '...'
            }
            ctx.fillText(vName, lnamex, lnamey)
            var rnamex = this.data.equal ? 280 : 280,
              rnamey = this.data.equal ? 125 : 140;
            var dName = this.data.defeated.user.nickName || this.data.defeated.user.eid
            if (dName.length > 4) {
              dName = dName.slice(0, 4) + '...'
            }
            ctx.fillText(dName, rnamex, rnamey)
            ctx.font = '19px PingFang';
            var lnumx = this.data.equal ? 100 : 100,
              lnumy = this.data.equal ? 150 : 140;
            ctx.fillText(this.data.victory.userRead.score + '分', lnumx, lnumy)
            var rnumx = this.data.equal ? 280 : 280,
              rnumy = this.data.equal ? 150 : 165;
            ctx.fillText(this.data.defeated.userRead.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.user.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.user.avatar
              rightImg.onload = () => {
                ctx.drawImage(rightImg, rx, ry, size, size)
                setTimeout(() => {
                  wx.canvasToTempFilePath({
                    canvas: canvas,
                    success: (res) => {
                      let userName = this.data.pkRecord.userReadId == this.data.victory.userRead.id ? this.data.victory.user.nickName || this.data.victory.user.eid : this.data.defeated.user.nickName || this.data.defeated.user.eid
                      if (userName.length > 4) {
                        userName = userName.slice(0, 4) + '...'
                      }
                      resolve({
                        title: `我挑战了${userName}的作品,这场比拼真精彩!点击加入战局!`,
                        path: `/pages/pkResult/index?id=${this.data.pkId}&uid=${wx.getStorageSync('uid')}&playback=true`,
                        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/375-300-1.jpg',
        promise
      }
    } else {
      return {
        title: '自从用了它,家里朗朗书声,美妙极了!你家孩子也快来试试!',
        path: `/pages/index/index?uid=${wx.getStorageSync('uid')}`,
        imageUrl: 'http://reader-wx.ai160.com/images/reader/v3/375-300-1.jpg'
      }
    }
  },
})