// webLogin.js
// 获取应用实例

import {
  globalData
} from "../../wm-cloud-db_index/utils/db_api/globalData";
import {
  reqDbLogin
} from "../../wm-cloud-db_index/utils/db_api/index";






const app = getApp();

Page({
  data: {
    shareInfo: {},
    isShowBtn: false,
  },
  onLoad(options) {
    this.initWebView(options)
  },
  async initWebView(options) {
    const isNeedLogin = options.isNeedLogin;
    let redirectUrl = decodeURIComponent(options.redirect);

    console.warn("options.redirect:", redirectUrl)

    if (isNeedLogin) {

      await new Promise((r) => {
        wx.login({
          success: res => {
            console.warn("code:", res.code)
            reqDbLogin({
              code: res.code,
              redirect: redirectUrl,
              wid: globalData.wid
            }).then((res) => {
              if (res.success) {
                globalData.loginToken = res.data.loginToken
                // wx.setStorageSync('db_loginToken', res.data.loginToken)
                redirectUrl = res.data.redirectUrl
                r(1)
              }
            }).catch(() => {
              r(1)
            })
          }
        })
      })

    }


    if (redirectUrl) {
      this.setData({
        path: redirectUrl,
      })
    }


  },

  getMessage(e) {
    const {
      data
    } = e.detail;
    console.log(data, "data")
    if (data) {
      this.setData({
        share: data[data.length - 1]
      })
    }
  },

  onShareAppMessage: function (options) { //分享
    const {
      share
    } = this.data;
    console.warn(share.link, "share.link--------", JSON.stringify(options))
    // const shareurl = '/pages/webview/index?redirect=' + encodeURIComponent(share.link);
    if (share) {
      const shareurl = share.link

      return {
        title: share.title,
        path: shareurl,
        imageUrl: share.imgUrl,
        success: function (res) {
          console.log(res, '成功')
          console.info(res + '成功');
          // wx.showToast({
          //   title: '分享成功',
          //   icon: 'none'
          // })
          // 转发成功
        },
        fail: function (res) {
          console.log(res + '失败');
          // 转发失败
        },
        complete: function (res) {
          // 不管成功失败都会执行
          console.log(res, '成功或失败');
        }
      }
    } else {
      return {
        title: "",
        path: "/packages/wm-cloud-db_index/db_index/index",
        imageUrl: "https://yun.duiba.com.cn/aurora/assets/bcce6f784bb575d94e9fec4e5ee98f2e7fa1cd85.png",
        success: function (res) {
          console.log(res, '成功')
          console.info(res + '成功');
          // wx.showToast({
          //   title: '分享成功',
          //   icon: 'none'
          // })
          // 转发成功
        },
        fail: function (res) {
          console.log(res + '失败');
          // 转发失败
        },
        complete: function (res) {
          // 不管成功失败都会执行
          console.log(res, '成功或失败');
        }
      }
    }

  },


})