import {
  awardUrl,
  chanllageUrl,
  exchangeUrl,
  getUrlParam,
  globalData,
  rankUrl,
  shopUrl
} from "../utils/db_api/globalData";
import {
  apiAuthAvatar,
  apiDbIndexInfo,
  apiDbScan,
  apiGetActivityStatus,
  apiGetTicketStatus,
  apiUploadFile,
  apiUserRecord,
  reqDbCheckHavePower,
  reqDbLogin
} from "../utils/db_api/index";
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

Page({
  data: {
    guideIndex: -1,
    showModalType: "",
    isBindPhone: false,
    ticket: "",
    inviteNum: 0,
    inviteTicketNum: 0,
    qrcodeSign: "",
    prizeInfoVO: [],
    authAvatar: false,
    avatarUrl: defaultAvatarUrl,
    isShowAuth: false,
    nickName: "",
    activityStatus: 0,
    isPlayMusic: true,
    assistErrorMsg: ""
  },
  onLoad: async function (options) {



    const q = decodeURIComponent(options.q) // 获取到二维码原始链接内容
    const scancode_time = parseInt(options.scancode_time) // 获取用户扫码时间 UNIX 时间戳

    // console.warn("q_scancode_time", q, scancode_time)
    // console.warn("q_scancode_time", q, scancode_time)
    // console.warn("q_scancode_time", q, scancode_time)
    // console.warn("q_scancode_time", q, scancode_time)
    // console.warn("q_scancode_time", q, scancode_time)



    this.innerAudioContext = wx.createInnerAudioContext({
      useWebAudioImplement: false, // 是否使用 WebAudio 作为底层音频驱动，默认关闭。对于短音频、播放频繁的音频建议开启此选项，开启后将获得更优的性能表现。由于开启此选项后也会带来一定的内存增长，因此对于长音频建议关闭此选项
      loop: true,
    })
    this.innerAudioContext.src = 'https://yun.duiba.com.cn/aurora/assets/9cd54c2107760e0adbe826843990ab966b149e5b.mp3'


    this.innerAudioContext.play() // 播放

    // innerAudioContext.pause() // 暂停

    // innerAudioContext.stop() // 停止

    wx.showLoading({
      mask: true,
      success: (res) => {},
      fail: (res) => {},
      complete: (res) => {},
    })



    const wid = await this.getWid()

    apiUserRecord({
      wid,
      data: q + "|scancode_time=" + scancode_time
    })


    const activityStatusResp = await apiGetActivityStatus({
      wid
    })
    /**
     * 未开始:1,进行中:2,已结束:3
     */
    if (activityStatusResp.success) {
      this.setData({
        activityStatus: activityStatusResp.data
      })
    }
    console.warn("activityStatusResp", activityStatusResp.data)
    console.warn("wid", wid)
    globalData.wid = wid
    const isBindPhone = await this.getBindPhone(wid)
    if (isBindPhone) {
      /**已绑定的老用户直接拿loginToken */
      await this.login(wid)
      const resp = await apiDbIndexInfo({
        wid
      })
      if (resp.success) {
        this.setData({
          authAvatar: resp.data.authAvatar,
          inviteNum: resp.data.inviteNum,
          inviteTicketNum: resp.data.inviteTicketNum
        })
        if (resp.data.authAvatar && !options.shareCode && !options.q) {
          if (wx.getStorageSync('db_firstIn_pop') == '1') {
            //已经授权的情况下走新手引导
            if (wx.getStorageSync('db_guide') != '1') {
              /**新手引导 */
              wx.setStorageSync('db_guide', '1')
              this.setData({
                guideIndex: 0
              })
            } else {
              //看是否有人帮忙助力
              // resp.data.inviteNum > 0
              if (resp.data.inviteNum > 0 && activityStatusResp.data == 2) {
                this.setData({
                  showModalType: "assistReflct"
                })
              }else{
                this.openGameModal()
              }

            }
          }
        }
        /**首页接口存储 */
        globalData.indexInfo = resp.data
      }
    }
    // console.warn("isBindPhone", isBindPhone)
    this.setData({
      isBindPhone
    })

    // options.shareCode和options.q链路互斥不会同时
    if (options.shareCode && activityStatusResp.data == 2) {
      //助力逻辑
      this.setData({
        showModalType: 'assist',
        shareCode: options.shareCode
      })
      wx.hideLoading()
      return
    }




    if (options.q && activityStatusResp.data == 2) {
      if (isBindPhone && globalData.indexInfo.lastScanTimes <= 0) {
        wx.hideLoading()
        wx.showToast({
          title: '今日扫码次数已达上限',
          icon: 'none',
          duration: 3000
        })
        return
      }



      const db_qrcodeInfo = getUrlParam('q', decodeURIComponent(options.q))
      const params = db_qrcodeInfo.split("_")
      let ticket = params[1]
      let qrcodeSign = params[2]
      // const oldTicket = wx.getStorageSync("ticket")
      // const oldQrcodeSign = wx.getStorageSync("qrcodeSign")

      // if (!(oldTicket == ticket && oldQrcodeSign == qrcodeSign)) {
      //已经使用过则置空
      let apiGetTicketStatusResp = await apiGetTicketStatus({
        wid,
        ticket,
        qrcodeSign
      })
    
      if (apiGetTicketStatusResp.success && apiGetTicketStatusResp.data == 1) {
        wx.hideLoading()
        //已使用
        wx.showToast({
          title: '此瓶盖已被核奖～',
          icon: 'none',
          duration: 3000
        })
        if (wx.getStorageSync('db_firstIn_pop') != '1') {
          wx.setStorageSync('db_firstIn_pop', '1')
          this.setData({
            showModalType: 'firstIn'
          })
        } else {
          if (wx.getStorageSync('db_guide') != '1') {
            /**新手引导 */
            wx.setStorageSync('db_guide', '1')
            this.setData({
              guideIndex: 0,
              showModalType: ''
            })
          }
        }
        return
      }
      if (apiGetTicketStatusResp.success && apiGetTicketStatusResp.data == 0) {
        // wx.showToast({
        //   title: '',
        //   icon: 'none'
        // })
        this.setData({
          showModalType: 'clickGift',
          ticket,
          qrcodeSign
        })
      }
      // }
    } else {
      if (wx.getStorageSync('db_firstIn_pop') != '1') {
        wx.setStorageSync('db_firstIn_pop', '1')
        this.setData({
          showModalType: 'firstIn'
        })
      } else {
        if (wx.getStorageSync('db_guide') != '1') {
          /**新手引导 */
          wx.setStorageSync('db_guide', '1')
          this.setData({
            guideIndex: 0,
            showModalType: ''
          })
        }
      }
    }


    if (options.isFromH5Scan) {
      //如果来自h5的话必然是免登
      this.scan()
    }

    wx.hideLoading()

    console.warn("options:", options, wid)
    // wx.showToast({
    //   title: '' + JSON.stringify(options),
    //   icon: 'none'
    // })
  },

  async getBindPhone(wid) {
    const isBindPhone = await new Promise((r) => {
      wx.login({
        success: res => {
          if (res.code) {
            reqDbCheckHavePower({
              code: res.code,
              wid
            }).then((resp) => {
              console.warn("resp:", resp, resp.success, resp.data)
              if (resp.success) {
                r(resp.data.bindPhone)
              } else {
                r(false)
              }
            })
          }
        }
      })
    })

    return isBindPhone;
  },

  async login(wid) {
    await new Promise((r) => {
      wx.login({
        success: ress => {
          reqDbLogin({
            code: ress.code,
            wid
          }).then((respp) => {
            if (respp) {
              globalData.loginToken = encodeURIComponent(respp.data.loginToken)
              r(1)
            }
          })
        }
      })
    })
  },

  async getWid() {
    const wid = await new Promise((r) => {
      getApp().getSdk().getRetailData('user_base_info').then(data => {
        r(data.wid)
      })
    })
    console.warn("wid", wid)
    if (wid != -1) {
      return wid
    } else {
      return await this.getWid()
    }
  },
  async getAuthLogin(wid) {
    await new Promise((r) => {
      wx.login({
        success: ress => {
          reqDbLogin({
            code: ress.code,
            wid
          }).then((respp) => {
            if (respp) {
              r(respp.data)
            }
          })
        }
      })
    })
  },
  async showAward() {
    // const resp = await this.getAuthLogin(globalData.wid)
    wx.navigateTo({
      url: '/packages/wm-cloud-db_webview/db_webview/index?isNeedLogin=true&redirect=' + encodeURIComponent(awardUrl)
    })
  },
  scanFunc() {
    if (globalData.indexInfo.lastScanTimes > 0) {
      this.setData({
        showModalType: "scanTip"
      })
    } else {
      this.setData({
        showModalType: "scanLimit"
      })
    }
  },
  nextGuide(e) {
    // const {
    //   index
    // } = e.target.dataset
    // console.warn("引导:" + (index * 1 + 1))
    if (this.data.guideIndex == 2) {
      if (this.data.inviteNum > 0) {
        this.setData({
          showModalType: "assistReflct"
        })
        return
      }else{
        console.warn("进游戏引导弹窗了", )
        this.openGameModal()
      }
      console.warn("完成引导")
    }
    this.setData({
      guideIndex: this.data.guideIndex + 1
    })
  },
  showRuleModal() {
    if (this.data.activityStatus == 3) {
      wx.showToast({
        title: "抱歉，活动已结束~",
        icon: "none"
      })
      return
    }
    this.setData({
      showModalType: 'rule'
    })
  },
  onModalClose(e) {
    //暂不考虑两个弹窗
    console.warn("onModalClose,e", e.detail)

    if (e.detail.type && e.detail.type == 'openWxMoneyAward') {

      if (!this.data.authAvatar) {
        //如果没有授权
        this.setData({
          isShowAuth: true,
          showModalType: '',
          awardInfo: e.detail
        })
        return
      }

      this.setData({
        showModalType: ''
      })
      if (e.detail.projectOrderNo) {
        //直接跳转领取页
        wx.navigateTo({
          url: '/packages/wm-cloud-db_webview/db_webview/index?isNeedLogin=true&redirect=' + encodeURIComponent('https://duiba.ioutu.cn/customActivity/weimocloud/redPage?orderId=' + e.detail.projectOrderNo),
        })
      } else {
        //兜底
        wx.navigateTo({
          url: '/packages/wm-cloud-db_webview/db_webview/index?isNeedLogin=true&redirect=' + encodeURIComponent('https://duiba.ioutu.cn/aaw/projectx/takePrize?projectOrderNo=' + e.detail.recordId),
        })
      }
      //详情页
      // https://duiba.ioutu.cn/aaw/projectx/takePrize?projectOrderNo=
      //红包页
      // https://duiba.ioutu.cn/customActivity/weimocloud/redPage?orderId=

    }

    if (e.detail == 'openAward' && !this.data.authAvatar) {
      this.setData({
        isShowAuth: true,
        showModalType: ''
      })
      return
    }
    if (e.detail == 'firstIn-auth') {
      if (!this.data.authAvatar) {
        this.setData({
          isShowAuth: true,
          showModalType: ''
        })
      } else {
        if (wx.getStorageSync('db_guide') != '1') {
          /**新手引导 */
          wx.setStorageSync('db_guide', '1')
          this.setData({
            guideIndex: 0,
            showModalType: ''
          })
        } else {
          this.setData({
            showModalType: ''
          })
        }
      }
      return
    }
    //如果都授权了，关闭
    if (e.detail == 'firstIn' && this.data.isBindPhone && this.data.authAvatar && wx.getStorageSync('db_guide') != '1') {
      /**新手引导 */
      wx.setStorageSync('db_guide', '1')
      this.setData({
        guideIndex: 0,
        showModalType: ''
      })
    }

    if (e.detail == 'assistSuc' || e.detail == 'assistFail' || e.detail == 'assist') {
      if (wx.getStorageSync('db_firstIn_pop') != '1') {
        wx.setStorageSync('db_firstIn_pop', '1')
        this.setData({
          showModalType: 'firstIn'
        })
        return
      }

      if (wx.getStorageSync('db_guide') != '1') {
        /**新手引导 */
        wx.setStorageSync('db_guide', '1')
        this.setData({
          guideIndex: 0,
          showModalType: ''
        })
        return
      }

      if (this.data.inviteNum > 0) {
        this.setData({
          showModalType: "assistReflct"
        })
        return
      }
      this.setData({
        showModalType: ""
      })
    }
     //助力反馈弹窗之后再检查一遍
    if (e.detail == "assistReflct") {
      this.openGameModal()
    }
    this.setData({
      showModalType: ''
    })
  },
  openGameModal(){
    if(!!wx.getStorageSync("gameGuide")){
      return
    }
    wx.setStorageSync("gameGuide", true);
    this.setData({showModalType:"gameGuide"})
  },
  onModalPhoneClose(e) {
    console.warn("onModalPhoneClose,e", e.detail)
    this.checkAuth(e.detail)
    this.setData({
      showModalType: ''
    })
  },
  onModalCloseShowRule(e = {}) {
    this.setData({
      showModalType: 'rule'
    })
  },
  onAuthPhone(e) {
    this.checkAuth(e.detail, true)
  },
  onAuthUser() {
    this.showAuth()
  },
  onAssistResult(e) {
    const res = e.detail
    if (res.success) {
      //助力成功
      this.setData({
        showModalType: "assistSuc"
      })
    } else {
      //助力失败
      this.setData({
        showModalType: "assistFail",
        assistErrorMsg: res.message
      })
    }
  },
  /**立即扫码 */
  scanRightNow() {
    if (this.data.activityStatus == 3) {
      wx.showToast({
        title: "抱歉，活动已结束~",
        icon: "none"
      })
      return
    }
    this.setData({
      showModalType: ''
    })
    this.scan()
  },

  scan() {
    wx.scanCode({
      onlyFromCamera: true,
      success: async (res) => {
        console.warn("res", res)
        const db_qrcodeInfo = getUrlParam('q', decodeURIComponent(res.result))
        const params = db_qrcodeInfo.split("_")
        const ticket = params[1]
        const qrcodeSign = params[2]
        // const ticket = getUrlParam('ticket', res.path)
        // const qrcodeSign = getUrlParam('qrcodeSign', res.path)

        const apiGetTicketStatusResp = await apiGetTicketStatus({
          ticket,
          qrcodeSign
        })
        if (apiGetTicketStatusResp.success && apiGetTicketStatusResp.data == 1) {
          //已使用
          wx.showToast({
            title: '此瓶盖已被核奖～',
            icon: 'none'
          })
          return
        }
        if (!apiGetTicketStatusResp.success) {
          // wx.showToast({
          //   title: '',
          //   icon: 'none'
          // })
          return
        }
        console.warn("qrcode", qrcodeSign, ticket)
        this.setData({
          showModalType: 'clickGift',
          ticket,
          qrcodeSign
        })
        // wx.navigateBack()
        // wx.showToast({
        //   title: JSON.stringify(res.result),
        //   icon: 'none',
        //   duration: 3000,
        // })
      },
      fail: () => {}
      // complete: (res) => {
      //   wx.navigateBack({
      //     delta: 1
      //   });
      // }
    });
  },

  async onOpenAward() {
    this.setData({
      isBindPhone: true
    })
    let resp = await apiDbScan({
      ticket: this.data.ticket,
      qrcodeSign: this.data.qrcodeSign
    })

    //mock
    // let resp = {
    //   code: null,
    //   message: null,
    //   success: true,
    //   timeStamp: 1702902817178,
    //   data: {
    //     prizeInfoVO: [{
    //       prizeName: "任务获得门票",
    //       prizeImg: "//yun.duiba.com.cn/polaris/悦龙门门票.3e5353da026b89b1656686bd95323cf533ff9e6f.png",
    //       sendCount: 2,
    //       type: 4,
    //       url: null
    //     }, {
    //       prizeName: "第4次-5元立减金腾讯视频周卡-线上测试",
    //       prizeImg: "//yun.duiba.com.cn/polaris/5元优惠券.1ca8f08fb363d846e45ab206b9621af3ebe04a83.png",
    //       sendCount: 1,
    //       type: 1,
    //       url: "/aaw/projectx/takePrize?projectOrderNo=1431534976"
    //     }, {
    //       prizeName: "能量币",
    //       prizeImg: "//yun.duiba.com.cn/polaris/能量币.99fc40a82c66b4393f8d63fcfe20883bc149987e.png",
    //       sendCount: 50,
    //       type: 3,
    //       url: null
    //     }]
    //   }
    // }

    if (resp.success) {
      // wx.setStorageSync("ticket", this.data.ticket)
      // wx.setStorageSync("qrcodeSign", this.data.qrcodeSign)
      const homeResp = await apiDbIndexInfo({})
      if (homeResp.success) {
        this.setData({
          authAvatar: homeResp.data.authAvatar
        })
        /**首页接口存储 */
        globalData.indexInfo = homeResp.data
      }
      this.setData({
        prizeInfoVO: resp.data.prizeInfoVO,
        showModalType: 'openAward'
      })
      console.warn('123', resp)
    }
  },
  checkAuth(e, noShow = false) {
    wx.login({
      success: res => {
        if (res.code) {
          const param = {
            code: res.code,
            phoneEncryptedData: e.detail.encryptedData,
            phoneIv: e.detail.iv,
          }
          this.login_db(param, noShow)
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      }
    })
  },
  /**登陆逻辑 */
  login_db(param, noShow) {
    console.warn("param", param)
    if (this.data.isloading) return;
    this.setData({
      isloading: true
    });

    wx.showLoading();
    reqDbLogin({
      ...param,
    }).then(async (res) => {
      wx.hideLoading();
      this.setData({
        isloading: false
      });
      if (res.success) {
        globalData.loginToken = encodeURIComponent(res.data.loginToken)
        const isBindPhone = await this.getBindPhone(globalData.wid)
        this.setData({
          isBindPhone
        })
        const resp = await apiDbIndexInfo({})
        if (resp.success) {
          this.setData({
            authAvatar: resp.data.authAvatar
          })
          if (resp.data.authAvatar && !noShow) {
            //已经授权的情况下走新手引导
            if (wx.getStorageSync('db_guide') != '1') {
              /**新手引导 */
              wx.setStorageSync('db_guide', '1')
              this.setData({
                guideIndex: 0
              })
            }
          }
          /**首页接口存储 */
          globalData.indexInfo = resp.data
        }
      } else {
        console.log("获取兑吧免登失败", res);
      }
      wx.hideLoading();
    })
  },
  // onChooseAvatar(e) {
  //   console.warn("eee", e)
  //   const {
  //     avatarUrl
  //   } = e.detail;
  //   console.log(e, "头像")
  //   // this.setData({
  //   //   avatar: avatarUrl,
  //   // })

  //   wx.getFileSystemManager().readFile({
  //     filePath: e.detail.avatarUrl, //地址
  //     encoding: 'base64', //编码格式
  //     success: res => {
  //       let base64 = 'data:image/png;base64,' + res.data
  //       apiUploadFile({
  //         img64: base64,
  //       }).then((res = {}) => {
  //         console.warn(JSON.stringify(res), "resttts");
  //         this.setData({
  //           avatarUrl: res.data
  //         })
  //       })
  //     }
  //   })
  // },
  // onInputChange(e) {
  //   console.warn("nickName", e.detail.value)
  //   this.setData({
  //     nickName: e.detail.value
  //   })
  // },
  saveFunc(e) {
    console.warn("保存")
    if (!e.detail.nickName) {
      wx.showToast({
        title: '昵称不能为空～',
        icon: 'none'
      })
      return
    }
    apiAuthAvatar({
      nickname: e.detail.nickName,
      avatar: e.detail.avatarUrl
    }).then(async (res) => {
      if (res.success) {
        this.setData({
          isShowAuth: false
        })
      }

      const resp = await apiDbIndexInfo({})
      if (resp.success) {
        this.setData({
          authAvatar: resp.data.authAvatar
        })


        //助力逻辑下不走新手引导
        if (resp.data.authAvatar && this.data.showModalType != 'assist') {
          //已经授权的情况下走新手引导
          if (wx.getStorageSync('db_guide') != '1') {
            /**新手引导 */
            wx.setStorageSync('db_guide', '1')
            this.setData({
              guideIndex: 0
            })
          }
        }
        /**首页接口存储 */
        globalData.indexInfo = resp.data

        //如果是开心收下处的授权
        if (this.data.awardInfo) {
          const awardInfo = this.data.awardInfo
          if (awardInfo.projectOrderNo) {
            this.setData({
              awardInfo: null
            })
            //直接跳转领取页
            wx.navigateTo({
              url: '/packages/wm-cloud-db_webview/db_webview/index?isNeedLogin=true&redirect=' + encodeURIComponent('https://duiba.ioutu.cn/customActivity/weimocloud/redPage?orderId=' + awardInfo.projectOrderNo),
            })
          } else {
            //兜底
            wx.navigateTo({
              url: '/packages/wm-cloud-db_webview/db_webview/index?isNeedLogin=true&redirect=' + encodeURIComponent('https://duiba.ioutu.cn/aaw/projectx/takePrize?projectOrderNo=' + awardInfo.recordId),
            })
          }
        }
      }
      wx.hideLoading()
    })

  },
  cancelFunc() {
    console.warn("取消")
    this.setData({
      isShowAuth: false
    })
  },
  showAuth() {
    this.setData({
      isShowAuth: true
    })
  },
  showExchange() {
    wx.navigateTo({
      url: exchangeUrl
    })
  },
  showChallange() {
    if (this.data.activityStatus == 3) {
      wx.showToast({
        title: "抱歉，活动已结束~",
        icon: "none"
      })
      return
    }
    wx.navigateTo({
      url: '/packages/wm-cloud-db_webview/db_webview/index?isNeedLogin=true&redirect=' + encodeURIComponent(chanllageUrl),
    })
    this.setData({showModalType:""})
  },
  showShop() {
    wx.navigateTo({
      url: shopUrl
    })
    // wx.navigateTo({
    //   url: '/packages/wm-cloud-db_webview/db_webview/index?isNeedLogin=true&redirect=' + encodeURIComponent(shopUrl),
    // })
  },
  showRank() {
    if (this.data.activityStatus == 3) {
      wx.showToast({
        title: "抱歉，活动已结束~",
        icon: "none"
      })
      return
    }
    wx.navigateTo({
      url: '/packages/wm-cloud-db_webview/db_webview/index?isNeedLogin=true&redirect=' + encodeURIComponent(rankUrl),
    })
  },
  switchMusic(e) {
    const {
      index
    } = e.target.dataset
    if (index == '1') {
      //关闭音乐
      this.innerAudioContext.pause()
    } else {
      this.innerAudioContext.play()
    }
    console.warn("index", index, this.data.isPlayMusic)
    this.setData({
      isPlayMusic: index == '0'
    })
  },
  onHide() {
    this.innerAudioContext.stop()
  },
  onShow() {
    if (this.innerAudioContext && this.data.isPlayMusic) {
      this.innerAudioContext.play()
    }
  },
  onUnload() {
    this.innerAudioContext.stop()
  }
});