// index.js
// const { envList } = require('../../envList.js');
const app = getApp()
Page({
  data: {
    isShowBot: true,
    isShowShop: true,
    baseUrl: app.remoteConfig.baseUrl,
    baseCloudUrl: app.remoteConfig.baseCloudUrl,
    baseLoginCloudPath: 'userModel/register',
    botBtnTitle: "图片生成",
    shopBtnTitle: '虚拟资产',
    detailInfo: '关于：code笔记',
    title: "yma16博客",
    userImageUrl: "https://yongma16.xyz/staticFile/common/img/aiTop.jpg",
    loginTitle: "点击授权",
    joinTitle: '进入',
    nextPage: "/pages/home/home",
    userPrefix: '昵称:',
    userName: '月牙天冲',
    designPlaceholder: '自定义名称',
    userInfo: {},
    hasUserInfo: false,
    isloading: true,
    isOldVersion: false,
    isShowBottom: true,
    loginErrorTitle: '',
    loginErrorContent: ''
  },
  getUserInfoBtn: function (info) {
    wx.showLoading({
      title: '授权中',
    });
    console.log('userinfo', info)
    if (info && info.detail) {
      const rowData = info.detail.rawData ? JSON.parse(info.detail.rawData) : {
        nickName: '未授权用户',
        avatarUrl: ''
      }
      this.setData({
        userImageUrl: rowData.avatarUrl,
        userName: rowData.nickName,
        userInfo: rowData
      })
      wx.setStorageSync('currentUserInfo', rowData)
      console.log('rowData', rowData)
    }
    wx.hideLoading();
  },
  bindKeyInput(e) {
    const {
      value
    } = e.detail
    console.log('val', value)
    this.setData({
      userName: value
    })
  },
  clickBotBtn() {
    wx.navigateTo({
      url: '/pages/aiBot/aiBot'
    })
  },
  //  进入虚拟资产
  clickShopBtn() {
    console.log('跳转')
    // const thisBack = this
    wx.navigateTo({
      url: '/pages/shop/shop',
      // events: {
      //   // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
      //   acceptDataFromOpenedPage: function (data) {
      //     console.log('acceptDataFromOpenedPage data', data)
      //   },
      //   someEvent: function (data) {
      //     console.log('someEvent data', data)
      //   }
      // },
      // success: function (res) {
      //   console.log('res jump', res)
      //   // 通过 eventChannel 向被打开页面传送数据
      //   res.eventChannel.emit('setHomePageData', {
      //     userInfo: thisBack.data.userInfo,
      //     isShowBottom: thisBack.data.isShowBottom
      //   })
      // }
    })
  },
  // 头像选择
  onChooseAvatar(e) {
    console.log('e', e)
    const {
      avatarUrl
    } = e.detail
    this.setData({
      userImageUrl: avatarUrl,
    })
  },

  getOpenid(resolve, reject) {
    wx.showLoading({
      title: '微信登录中',
    })
    const baseUrl = this.data.baseUrl
    wx.login({
      success(res) {
        if (res.code) {
          //发起网络请求
          const path = '/common-api/wxProgramLogin/'
          wx.request({
            url: baseUrl + path,
            method: 'GET',
            data: {
              code: res.code
            },
            success: (res => {
              console.log('res', res)
              console.log('res.data', res.data.data)
              wx.setStorageSync('currentOpenid', res && res.data ? res.data.data : null)
              resolve && resolve()
              wx.hideLoading()
            }),
            fail: r => {
              console.log('cloud r', r)
              wx.hideLoading()
              reject && reject()
            }
          })
        } else {
          console.log('登录失败！' + res.errMsg)
          wx.hideLoading()
          reject && reject()
        }
      },
      fail: r => {
        console.log('r', r)
        wx.hideLoading()
        reject && reject()
        // wx.hideLoading()
      }
    })

  },
  // 登录
  loginSpringCloud() {
    const openId = wx.getStorageSync('currentOpenid')
    const wxOpenId = openId && openId.openid
    const headers = {
      'Content-Type': 'application/json;charset=UTF-8'
    }
    const params = {
      wx_openid: wxOpenId,
      wx_name: this.data.userName,
      wx_img: this.data.userImageUrl
    }
    const baseCloudUrl = this.data.baseCloudUrl
    const baseLoginCloudPath = 'wechat/register'
    console.log('注册', params)
    wx.request({
      url: baseCloudUrl + baseLoginCloudPath,
      headers: headers,
      data: params,
      method: 'POST',
      success: (res => {
        console.log('springcloud res login', res)
      }),
      fail: r => {
        console.log('cloud login error', r)
      }
    })
  },

  // 进入
  joinProfile(info) {
    const thisBack = this
    console.log('userinfo', info)
    this.getOpenid(() => {
      console.log('spring登录')
      thisBack.loginSpringCloud()
      this.setData({
        userImageUrl: thisBack.data.userImageUrl,
        userName: thisBack.data.userName,
      })
      const userInfo = {
        nickName: thisBack.data.userName,
        avatarUrl: thisBack.data.userImageUrl
      }
      thisBack.setData({
        userInfo: userInfo,
        hasUserInfo: true
      })
      wx.setStorageSync('currentUserInfo', userInfo)
      thisBack.jumpTohome()
    }, () => {
      wx.setStorageSync('currentUserInfo', null)
      return wx.showModal({
        cancelColor: 'cancelColor',
        title: thisBack.data.loginErrorTitle || '登录失败',
        content: thisBack.data.loginErrorContent || '请检查网络或联系微信cse-yma16'
      })
      // thisBack.jumpTohome()
    })

    // wx.hideLoading();
    // 跳转到home
    // this.jumpTohome()
  },
  getUserProfile(e) {
    // 推荐使用 wx.getUserProfile 获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
    // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log('信息', res)
        wx.setStorageSync('currentUserInfo', res.userInfo)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
        // 跳转到home
        this.jumpTohome()
      }
    })
  },
  // 跳转到home
  jumpTohome: function () {
    const thisBack = this
    wx.navigateTo({
      url: thisBack.data.nextPage,
      events: {
        // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
        acceptDataFromOpenedPage: function (data) {
          console.log('acceptDataFromOpenedPage data', data)
        },
        someEvent: function (data) {
          console.log('someEvent data', data)
        }
      },
      success: function (res) {
        console.log('res jump', res)
        // 通过 eventChannel 向被打开页面传送数据
        res.eventChannel.emit('setHomePageData', {
          userInfo: thisBack.data.userInfo,
          isShowBottom: thisBack.data.isShowBottom
        })
      }
    })
  },
  onLoad: function (options) {
    console.log('index page')
    console.log('option', options)
    const authorPageConfig = app.wxProgramConfig.authorPageConfig
    console.log('authorPageConfig', authorPageConfig)
    this.setData({
      detailInfo: authorPageConfig.detailInfo,
      title: authorPageConfig.title,
      userImageUrl: authorPageConfig.userImageUrl,
      loginTitle: authorPageConfig.loginTitle,
      nextPage: authorPageConfig.nextPage,
      userPrefix: authorPageConfig.userPrefix,
      userName: authorPageConfig.userName,
      designPlaceholder: authorPageConfig.designPlaceholder,
      isOldVersion: authorPageConfig.isOldVersion,
      joinTitle: authorPageConfig.joinTitle,
      shopBtnTitle: authorPageConfig.shopBtnTitle,
      isShowBottom: authorPageConfig.isShowBottom,
      isShowBot: authorPageConfig.isShowBot,
      isShowShop: authorPageConfig.isShowShop,
      loginErrorTitle: authorPageConfig.loginErrorTitle,
      loginErrorContent: authorPageConfig.loginErrorContent
    })
    // this.jumpTohome()
    // 页面创建时执行
  },
  onShow: function () {
    // 页面出现在前台时执行
  },
  onReady: function () {
    // 页面首次渲染完毕时执行
  },
  onHide: function () {
    // 页面从前台变为后台时执行
  },
  onUnload: function () {
    // 页面销毁时执行
  },
  onPullDownRefresh: function () {
    // 触发下拉刷新时执行
  },
  onReachBottom: function () {
    // 页面触底时执行
  },
  onShareAppMessage: function () {
    // 页面被用户分享时执行
  },
  onPageScroll: function () {
    // 页面滚动时执行
  },
  onResize: function () {
    // 页面尺寸变化时执行
  }
});