// app.js
App({
  basePage:'pages/aiBot/aiBot',
  homePageArticleId: 32,
  lifePageArricleId: 35,
  wxProgramConfig: {
    "aiBotConfig":{
      "saveKey":"aiBot",
      "searchOpenAiText":"画一只猫",
    },
    authorPageConfig: {
      cloudEmail: "1575057249@qq.com",
      cloudPwd: "U2FsdGVkX1+jfEkF2OXTQ5iIG4mrYc5/TLOiIntyENU=",
      title: "记忆碎片",
      userImageUrl: 'https://yongma16.xyz/staticFile/common/img/aiTop.jpg',
      loginTitle: '点击授权',
      detailInfo: '关于：code笔记',
      nextPage: "/pages/home/home",
      basePage: "/pages/home/home",
      userPrefix: '昵称:',
      userName: '月牙天冲',
      designPlaceholder: '自定义名称',
      joinTitle: '微信登录',
      shopBtnTitle: '虚拟资产',
      isOldVersion: false,
      "isShowBottom": true,
      "isShowBot":true,
      "isShowShop":true,
    },
    homePageConfig: {
      headBackground: [
        { class: 'header-swiper-one', content: '数据分析', articleId: 32, img: 'https://yongma16.xyz/staticFile/common/img/data.png' },
        { class: 'header-swiper-two', content: '前端开发', articleId: 33, img: 'https://yongma16.xyz/staticFile/common/img/front.png' },
        { class: 'header-swiper-three', content: '全栈开发', articleId: 34, img: 'https://yongma16.xyz/staticFile/common/img/back.png' }],
      bottomStyleConfig: {
        tabMenuText: '记忆碎片',
        homePageText: '主页',
        blogText: '博客',
        apiText: 'openai',
        aboutText: '关于'
      },
      bottomBtn: 'target',
    },
    apiPageConfig: {
      articleId: 44,
      aiConfig: {
        avatarUrl: 'https://yongma16.xyz/staticFile/common/img/aiTop.jpg',
        bgUrl: 'https://yongma16.xyz/staticFile/common/img/aiBg.jpg'
      },
      mode: 'introduce',
      option: 'introduce,openAiUse',
      layoutConfig: {
        introduceText: 'api介绍',
        useText: '使用',
        returnText: '返回介绍',
        sendText: '发送',
        searchText: '关键词查询',
        reportText: '复制数据',
        copyText: '复制',
        pasteText: '粘贴',
        upText: "",
        downText: "",
        errorMsg: 'openai的服务器异常！',
        emptyText: '欢迎',
        storageKey: 'openAiOptionsConfig',
        permissionTitle: '很抱歉您没有权限！',
        permissionContent: '请联系微信号：cse-yma16\r\n 需要1元开通权限\r\n1元可支持100条消息！',
        wxInfoImg: 'https://yongma16.xyz/staticFile/common/img/userInfo.png',
        isShowOpenAi:true,
        limitMsgCount: 10,
        confirmText: '添加微信',
        cancelText: '返回'
      }
    },
    aboutPageConfig: {
      articleId: 35,
      title:'个人信息'
    }
  },
  loginStatus: '',
  globalData: {
    userInfo: '',
    hasUserInfo: false,
    geoJson: {},
    hotData: [],
    /**
     * @type object[{name:'',adcode:''}]
     */
    geoAdcodeMap: [],
    targetItem: {},
  },
  remoteConfig: {
    baseUrl: 'https://yongma16.xyz',
    baseCloudUrl:'https://yongma16.xyz/cloudApi/api/',
  },
  // 引入`towxml3.0`解析方法
  towxml: require('/towxml/index'),
  // 引入eval 自定义的eval
  eval_des: require('/eval-pack/define-function/define-function'),
  /**
   * 转换text
   * @param {string} text 
   */
  changeMrkdownText(text) {
    const markdownText = this.towxml(text, 'markdown', {
      theme: 'light', //主题 dark 黑色，light白色，不填默认light
      events:{
        tap:(e)=>{
          console.log('e',e)
          if(e&&e.target&&e.target.dataset.data){
            const {attrs,tag}=e.target.dataset.data
            if(tag==='img'){
              const {src}=attrs
              wx.previewImage({
                current: src, // 当前显示图片的http链接
                urls: [src] // 需要预览的图片http链接列表
              })
            }
          }
        }
      }
    });
    return markdownText
  },
    /**
   * 转换html
   * @param {string} text 
   */
  changeHtmlText(text) {
    const markdownText = this.towxml(text, 'html', {
      theme: 'light', //主题 dark 黑色，light白色，不填默认light
      events:{
        tap:(e)=>{
          console.log('e',e)
          if(e&&e.target&&e.target.dataset.data){
            const {attrs,tag}=e.target.dataset.data
            if(tag==='img'){
              const {src}=attrs
              wx.previewImage({
                current: src, // 当前显示图片的http链接
                urls: [src] // 需要预览的图片http链接列表
              })
            }
          }
        }
      }
    });
    return markdownText
  },
  getUserProfile: function (e) {
    // 推荐使用 wx.getUserProfile 获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
    // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    })
  },
  onLaunch: function (options) {
    console.log('onLaunch', options)
    // 获取配置项目
    const that = this
    wx.showLoading({
      title: '加载配置中',
    })
    wx.request({
      url: 'https://yongma16.xyz/api/dictModel/index/',
      method: 'POST',
      data: {
        kind: 'wxConfig'
      }, success: function (res) {
        console.log('res', res)
        wx.hideLoading({
          success: (loadRes) => { console.log(loadRes) },
        })
        if (res.data.data && res.data.data[0].option) {
          that.wxProgramConfig = JSON.parse(res.data.data[0].option)
          console.log('that.wxProgramConfig',that.wxProgramConfig)
          that.basePage=that.wxProgramConfig.authorPageConfig.basePage||that.basePage
          wx.navigateTo({
            url: that.basePage,
            success: function (res) {
              // 通过 eventChannel 向被打开页面传送数据
              console.log('res', res)
            }
          });
        }
        else {
          wx.navigateTo({
            url: that.basePage,
            success: function (res) {
              // 通过 eventChannel 向被打开页面传送数据
              console.log('res', res)
            }
          });
        }
      },
      fail: function (r) {
        console.log('r', r)
        wx.hideLoading({
          success: (loadRes) => { console.log(loadRes) },
        })
        wx.navigateTo({
          url: that.basePage,
          success: function (res) {
            // 通过 eventChannel 向被打开页面传送数据
            console.log('res', res)
          }
        });
      }
    })
    if (!wx.cloud) {
      console.error('请使用 2.2.3 或以上的基础库以使用云能力');
    } else {
      wx.cloud.init({
        // env 参数说明：
        //   env 参数决定接下来小程序发起的云开发调用（wx.cloud.xxx）会默认请求到哪个云环境的资源
        //   此处请填入环境 ID, 环境 ID 可打开云控制台查看
        //   如不填则使用默认环境（第一个创建的环境）
        // env: 'my-env-id',
        traceUser: true,
      });
      wx.removeStorageSync('currentUserInfo');

      const currentUserInfo = wx.getStorageSync('currentUserInfo')
      if (currentUserInfo && currentUserInfo.nickName) {
        console.log('success')
      } else {
        wx.navigateTo({
          url: this.basePage,
          success: function (res) {
            // 通过 eventChannel 向被打开页面传送数据
            console.log('res', res)
          }
        })
      }

      // 用户登录
      const that = this
      wx.login({
        success(res) {
          console.log('res login', res)
          that.globalData.loginStatus = res
        }
      })
      wx.getSetting({
        success(res) {
          console.log('res set', res)
          that.globalData.setting = res
        }
      })
    }
  },

  onShow(options) {
    // Do something when show.
    console.info('show', options)
  },
  onHide(options) {
    console.info('onHide', options)
    // Do something when hide.
  },
  onError(msg) {
    console.log('error', msg)
  }
});
