// pages/shared/shared.js
const api = require('../../config/api.js');
const util = require('../../utils/util.js');
const atob = require('../../utils/atob')
import remote from '../../config.js'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    shared_img: '',
    recommend_text: '',
    editShowStatus: false,
    loadHot: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {

    let {
      // companyName,
      roomId,
      many,
      vrLink,
      id,
      type
    } = options
    //测试用
    // companyName = '1111'
    // id = 1046450
    // vrLink = 'L3BhZ2VzL3dlYnZpZXcvaW5kZXg'
    //测试用
    vrLink = atob(vrLink)
    // this.vrLink = vrLink + `?id=${id}&type=${type}`
    // 1046450,32,1,4370970,1
    // [id_type_join_roomId_many]
    this.vrLink = vrLink + `?id=${id}&type=${type}&join=true&roomId=${roomId}&many=${many}`;
    console.log(this.vrLink)
    // this.companyName = companyName



    let data = await this.getBrandDetail(id, type)
    this.sceneUrl = data.sceneUrl
    this.shareCodeImg = data.shareWxQrCode
    this.sceneName = data.sceneName

    let params = {
      scene: `${id}_${type}_1_${roomId}_1`,
      page: vrLink.substr(1, vrLink.length - 1) //截掉page前的 /
    }

    // this.getMIniCode =remote.requestHost+'/statics/tmp/images/1634032649766.png'
    try {
      let codeData = await this.generateMicroAppCode(params)
      if (codeData) {

        this.getMIniCode = remote.requestHost + codeData
        console.log('****')
        console.log(this.getMIniCode)
      } else {
        this.getMIniCode = null
        wx.showToast({
          title: '小程序码生成失败',
        })
      }
    } catch (err) {
      this.getMIniCode = null
      // this.getMIniCode =remote.requestHost+'/statics/tmp/images/1634032649766.png'
    }

    this.setData({
      shared_img: data.appListPicUrl || 'https://plaza.4dkankan.com/statics/img/pic_bg@2x.png',
      layoutHeight: wx.getSystemInfoSync().windowHeight - 170
    })

    const query = wx.createSelectorQuery()
    query.select('.canvas').boundingClientRect().exec(res => {
      this.canvas_width = res[0].width
      this.canvas_height = res[0].height
      this.drawImage()
    })
  },

  getCompanyDetail() {
    // CompanyApi.getCompanyDetail(this.companyId).then(res => {
    //   console.log(res, 'company')
    //   this.setData({
    //     company: res.data
    //   })
    // })
  },
  showEdit() {
    this.setData({
      editShowStatus: true
    })
  },
  hideEdit() {
    this.setData({
      editShowStatus: false
    })
  },
  bindinput(e) {
    const {
      value
    } = e.detail
    value.substr(0, 25)
    this.setData({
      recommend_text: value
    })
  },
  onShareAppMessage() {
    console.log(this.vrLink)
    return {
      path: this.vrLink,
      imageUrl: this.data.shared_img
    }
  },
  copyLink() {
    wx.setClipboardData({
      data: decodeURIComponent(this.sceneUrl),
      success(res) {
        wx.showToast({
          title: '复制成功',
        })
      }
    })
  },

  getBrandDetail: async function (id, type, cb) {
    let res = await util.request(api.BrandDetail, {
      id: id,
      type: type
    })
    return res.data.brand
  },
  generateMicroAppCode: async function (data) {
    let res = await util.request(api.generateMicroAppCode, data, 'POST', 'application/json')
    if (res.errno == 0) {
      return res.data
    } else if (res.errno == 1) {
      return false
    }

  },
  savePhoto() {
    wx.saveImageToPhotosAlbum({
      filePath: this.data.img_url,
      success(res) {
        wx.showModal({
          title: '图片保存成功',
          content: '图片成功保存到相册了，去发圈噻~',
          showCancel: false,
          confirmText: '好哒',
          confirmColor: '#72B9C3',
          success: (res) => {
            if (res.confirm) {}
          }
        })
      }
    })
  },
  async drawImage(recommend_text) {
    this.context = wx.createCanvasContext('content')
    this.context.lineJoin = 'miter'
    this.context.font = 'bold 15px sans-serif'
    this.context.setFillStyle('#fff')
    this.context.fillRect(0, 0, this.canvas_width, this.canvas_height)
    const dpr = wx.getSystemInfoSync().pixelRatio
    let cover = await this.downloadFile(this.data.shared_img)
    // if (this.shareCodeImg) {
    //   var shareCode = await this.downloadFile(this.shareCodeImg)
    // } else {
    //   var shareCode = null
    // }
    var shareCode = null
    if (this.getMIniCode) {
      try {
        shareCode = await this.downloadFile(this.getMIniCode)

      } catch (err) {
        shareCode = null

      }
    }

    const img_width = this.canvas_width * 0.8644,
      img_height = this.canvas_width * 0.8644
    const left = (this.canvas_width - img_width) / 2
    // 画圆弧矩形
    this.strokeRoundRect((this.canvas_width - img_width) / 2, (this.canvas_width - img_width) / 2, img_width, img_height, 4)
    this.context.clip()
    this.context.drawImage(cover, 0, 0, img_width, img_height)
    this.context.restore()
    this.context.fillStyle = '#fff'
    this.context.font = 'normal 300 11px sans-serif'
    // this.sceneName = 
    // let title ='MOOST·理想服饰MOOST·理想服饰MOOST'
    if (this.sceneName && this.sceneName.length > 15) {
      this.sceneName = this.sceneName.substring(0, 15) + '...'
    } else if (!this.sceneName) {
      this.sceneName = ''
    }
    console.log(this.sceneName)
    if (this.sceneName != '') {
      this.titleWidth = this.context.measureText(this.sceneName).width + 53 + 20
    } else {
      this.titleWidth = 20
    }

    this.roundRectColor(this.context, left + 10, 243, this.titleWidth, 22, 6, 'rgba(0, 0, 0, 0.6)')
    this.context.fillStyle = '#fff'
    this.context.font = 'normal 300 11px sans-serif'
    this.context.fillText(this.sceneName, left + 10 + 53 + 10, 243 + 15)

    this.roundRectColor(this.context, left + 10, 243, 53, 22, 6, '#ED5D18')
    this.context.fillStyle = "#fff";
    this.context.beginPath();
    this.context.arc(left + 10 + 6, 243 + 11, 3, Math.PI * 2, 0, true);
    this.context.closePath();
    this.context.fill();
    this.context.fillStyle = '#fff'
    this.context.font = 'normal 300 11px sans-serif'
    this.context.fillText('直播中', left + 10 + 12, 243 + 15)




    // this.context.fillStyle = '#131D34'
    // this.context.font = 'normal bold 15px sans-serif'
    // this.context.fillText(this.companyName, left, img_width + left + this.canvas_height * 15 / 460 + 21)
    // this.context.restore()
    // this.context.font = 'normal 300 13px sans-serif'
    // this.context.fillStyle = '#79868F'
    // let recommend_text1, recommend_text2
    // if (recommend_text) {
    //   recommend_text1 = recommend_text.slice(0, 11)
    //   recommend_text2 = recommend_text.slice(11)
    // }
    // this.context.fillText(recommend_text1 || '我的个性推荐语', left, img_width + left + this.canvas_height * 15 / 460 + 18 + 21)
    // if (recommend_text2) {
    //   this.context.font = 'normal 300 13px sans-serif'
    //   this.context.fillStyle = '#79868F'
    //   this.context.fillText(recommend_text2 || '我的个性推荐语', left, img_width + left + this.canvas_height * 15 / 460 + 18 + 21 + 21)
    // }
    this.context.font = 'bold 300 12px sans-serif'
    this.context.fillStyle = '#000'
    shareCode && this.context.drawImage(shareCode, left, img_height + 40, 60, 60)
    this.context.fillText('为爱筑家', left + 80, img_height + 50)
    this.context.fillText('满足您对家的一切美好想象', left + 80, img_height + 70)
    this.context.font = 'normal 300 12px sans-serif'
    this.context.fillStyle = '#000'
    this.context.fillText('长按识别二维码', left + 80, img_height + 95)
    this.context.fillStyle = '#ED5D18'
    this.context.fillText('进入直播间', left + 170, img_height + 95)

    this.context.draw(false, () => {
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: this.canvas_width,
        height: this.canvas_height,
        canvasId: 'content',
        success: (res) => {
          this.setData({
            img_url: res.tempFilePath
          })

          setTimeout(() => {
            this.setData({
              loadHot: true
            })
          }, 100)
        }
      })
    })
    this.context.fill()
    this.context.restore()

  },
  submitRecommend() {
    this.drawImage(this.data.recommend_text)
    this.hideEdit()
  },
  strokeRoundRect(x, y, width, height, radius, /*optional*/ lineWidth, /*optional*/ strokeColor) {
    //圆的直径必然要小于矩形的宽高          
    if (2 * radius > width || 2 * radius > height) {
      return false;
    }

    this.context.save();
    this.context.translate(x, y);
    //绘制圆角矩形的各个边  
    this.drawRoundRectPath(width, height, radius);
    this.context.lineWidth = 0; //若是给定了值就用给定的值否则给予默认值2  
    this.context.strokeStyle = strokeColor || "#fff";
    this.context.stroke();

  },
  drawRoundRectPath(width, height, radius) {
    this.context.beginPath(0);
    //从右下角顺时针绘制，弧度从0到1/2PI  
    this.context.arc(width - radius, height - radius, radius, 0, Math.PI / 2);

    //矩形下边线  
    this.context.lineTo(radius, height);

    //左下角圆弧，弧度从1/2PI到PI  
    this.context.arc(radius, height - radius, radius, Math.PI / 2, Math.PI);

    //矩形左边线  
    this.context.lineTo(0, radius);

    //左上角圆弧，弧度从PI到3/2PI  
    this.context.arc(radius, radius, radius, Math.PI, Math.PI * 3 / 2);

    //上边线  
    this.context.lineTo(width - radius, 0);

    //右上角圆弧  
    this.context.arc(width - radius, radius, radius, Math.PI * 3 / 2, Math.PI * 2);

    //右边线  
    this.context.lineTo(width, height - radius);
    this.context.closePath();
  },
  downloadFile(url) {
    return new Promise(resolve => {
      wx.downloadFile({
        url: url,
        success(res) {
          resolve(res.tempFilePath)
        },
        async fail(res) {
          console.log('下载失败，再触发下载一次', res)
          wx.downloadFile({
            url: url,
            success(res) {
              resolve(res.tempFilePath)
            },
            fail() {
              console.log('二次下载失败', res)
              resolve('')
            }
          })

        }
      })
    })
  },

  /**
   * 绘制圆角矩形
   * @param {*} x 起始点x坐标
   * @param {*} y 起始点y坐标
   * @param {*} w 矩形宽
   * @param {*} h 矩形高
   * @param {*} r 圆角半径
   * @param {*} context 画板上下文
   */

  roundRectColor(context, x, y, w, h, r, color) { //绘制圆角矩形（纯色填充）
    context.save();
    // context.setFillStyle("#ED5D18"); 
    // context.setStrokeStyle('#ED5D18')
    context.setFillStyle(color);
    context.setStrokeStyle(color)
    context.setLineJoin('round'); //交点设置成圆角
    context.setLineWidth(r);
    context.strokeRect(x + r / 2, y + r / 2, w - r, h - r);
    context.fillRect(x + r, y + r, w - r * 2, h - r * 2);
    // context.stroke();
    // context.closePath();
  }


})