var app = getApp();
const navigationBarHeight = (getApp().statusBarHeight + 44) + 'px'
const extConfig = wx.getExtConfigSync ? wx.getExtConfigSync() : {}
let businessSwitch = extConfig.attr.businessSwitch
let mch_id = extConfig.attr.mchId
let ifStoreApp = extConfig.attr.ifStoreApp;
const Http = require("../utils/HttpBasics");
const imgurl = require("../utils/imgurl");
var config = require("../config/config.js");
const bgColor = require("../utils/bgColor.js")
Page({
  /**
   * 页面的初始数据
   */
  data: {
    mch_id: mch_id,
    businessSwitch: businessSwitch,
    goUrl: "",
    templateId: [],
    aboutShow: false,
    showPrivacy: false,
    navigationBarHeight,
    ifStoreApp: ifStoreApp,
    aboutUs: imgurl.aboutUs.url,
    rqCode: imgurl.barcode.url,
    banneColor: bgColor.colorFirst.user2.banneColor,
    levelBg: bgColor.colorFirst.user.levelBg,
    view: bgColor.colorFirst.user2.view,
    fenxiang: imgurl.fenxiang1.url,
    redirectUrl: imgurl.redirect.url,
    editUrl: imgurl.edit.url,
    activeUrl: imgurl.active.url,
    dingUrl: imgurl.ding.url,
    duihuan: imgurl.duihuan.url,
    shoppingAtlas: imgurl.shoppingAtlas.url,
    quansUrl: imgurl.quans.url,
    wmintegral: imgurl.wmintegral.url,
    cardiconUrl: imgurl.cardicon.url,
    myactivitygift: imgurl.myactivitygift.url,
    myactivity: imgurl.myactivity.url,
    cheUrl: imgurl.che.url,
    giftUrl: imgurl.gift.url,
    wmbarginicon: imgurl.wmbarginicon.url,
    wmspellgroup: imgurl.wmspellgroup.url,
    canIUse: wx.canIUse('official-account'),
    mineFlag: "",
    flag: 'hidden',
    score: '0',
    credit: '0',
    userId: "",
    memberName: "",
    memberLogo: "",
    curPhone: '',
    name: "",
    birthdate: "",
    sex: "",
    showEdit: false,
    ismember: false,
    canvasHidden: false,
    maskHidden: true,
    imagePath: '',
    appVersion: "",
    placeholder: '',
    userAvatarUrl: "",
    userName: "",
    ifSetUserInfo: false
  },
  suerService() {
    console.log("打开客服")
    wx.openCustomerServiceChat({
      extInfo: { url: 'https://work.weixin.qq.com/kfid/kfc7f4a755cbb51fa99' },
      corpId: 'wwdc116b631d3ea35f',
      success(res) { },
      fail(res) {
        console.log(res);
      }
    })

  },
  checkUserStatus() {
    let that = this;
    Http.get({
      url: config.api.checkPhoneStatus,
      data: {}
    }).then(res => {
      wx.navigateTo({
        url: '/pages/edit/edit',
      })
    }).catch(err => {
      wx.navigateTo({
        url: `/pages/getphoneInfo/index?mineFlag=mine`,
      })
    })
  },
  gotoPhoneInfo() {
    /**
     * 将值传到用户手机号授权的页面
     *
     */
    wx.navigateTo({
      url: `/pages/getphoneInfo/index?path=main`
    });
  },
  //是否授权手机号
  ifPhoneInfo() {
    const that = this
    Http.get({
      url: config.api.checkPhoneStatus,
      data: {}
    }).then(res => {
      console.log(res, 'res');
      that.setData({
        ifSetUserInfo: true
      })
      // 手机号未授权
      const ifSetUserInfo = wx.getStorageSync('ifSetUserInfo')
      if (ifSetUserInfo == 1) {
        if (!that.data.ifSetUserInfo) return
        wx.showModal({
          title: '完善个人信息',
          content: '请继续完成个人信息哦',
          showCancel: true,
          cancelText: "以后再说",
          cancelColor: '',
          confirmText: "去完善",
          confirmColor: '#FD832D',
          complete: (res) => {
            if (res.cancel) {
              console.log('cancel');
            }
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages3/setUserInfo/index',
              })
            }
            // 已完成手机号授权
            wx.setStorageSync('ifSetUserInfo', 2)
          }
        })
      }
      return
    }).catch(err => {
      console.log(err, 'err');
      that.setData({
        ifSetUserInfo: false
      })
      const ifSetUserInfo = wx.getStorageSync('ifSetUserInfo')
      if (ifSetUserInfo != 2) {
        wx.setStorageSync('ifSetUserInfo', 1) //手机号未授权
      }

      // wx.navigateTo({
      //   url: `/pages/getphoneInfo/index?mineFlag=mine`,
      // })
    })
  },

  goToInfo() {
    wx.navigateTo({
      url: '/pages3/setUserInfo/index',
    })
  },

  /* 判断是否授权*/
  userAuthorization() {
    Http.get({
      url: config.api.checkUserStatus,
      data: {
        token: app.globalData.token
      }
    }).then(res => {
      this.ifPhoneInfo()
    }).catch(err => {
      app.globalData.type = 'uc'
      wx.navigateTo({
        url: `/pages/getuserinfo/index`,
      })
    })
  },



  /**
   * 跳转到成长值的页面
   */
  gotograde: function () {
    if (this.data.ifSetUserInfo) {
      wx.navigateTo({
        url: '/pages/czdetail/czdetail',
      })
    } else {
      wx.navigateTo({
        url: `/pages/getphoneInfo/index?mineFlag=mine`,
      })
    }
  },


  goToOrder() {
    if (this.data.ifSetUserInfo) {
      wx.navigateTo({
        url: '/pages/order/index/index?id=all',
      })
    } else {
      wx.navigateTo({
        url: `/pages/getphoneInfo/index?mineFlag=mine`,
      })
    }
  },

  goToCouponorder() {
    if (this.data.ifSetUserInfo) {
      wx.navigateTo({
        url: '/pages/couponorder/index/index',
      })
    } else {
      wx.navigateTo({
        url: `/pages/getphoneInfo/index?mineFlag=mine`,
      })
    }
  },

  goToCardorder() {
    if (this.data.ifSetUserInfo) {
      wx.navigateTo({
        url: '/pages/cardorder/index/index',
      })
    } else {
      wx.navigateTo({
        url: `/pages/getphoneInfo/index?mineFlag=mine`,
      })
    }
  },

  goToIntegralmall() {
    if (this.data.ifSetUserInfo) {
      wx.navigateTo({
        url: '/pages/integralmall/index',
      })
    } else {
      wx.navigateTo({
        url: '/pages/integralmall/index',
      })
      // wx.navigateTo({
      //   url: `/pages/getphoneInfo/index?mineFlag=mine`,
      // })
    }
  },

  goToBargain() {
    if (this.data.ifSetUserInfo) {
      wx.navigateTo({
        url: '/pages/bargain/bargain?from=myhtml',
      })
    } else {
      wx.navigateTo({
        url: `/pages/getphoneInfo/index?mineFlag=mine`,
      })
    }
  },

  goToSpellGroup() {
    if (this.data.ifSetUserInfo) {
      wx.navigateTo({
        url: '/pages/spellGroup/spellGroup?from=myhtml',
      })
    } else {
      wx.navigateTo({
        url: `/pages/getphoneInfo/index?mineFlag=mine`,
      })
    }
  },

  goToMyactivity() {
    if (this.data.ifSetUserInfo) {
      wx.navigateTo({
        url: '/pages/user/myactivity/index',
      })
    } else {
      wx.navigateTo({
        url: `/pages/getphoneInfo/index?mineFlag=mine`,
      })
    }
  },

  goToSetUserInfo() {
    if (this.data.ifSetUserInfo) {
      wx.navigateTo({
        url: '/pages3/setUserInfo/index',
      })
    } else {
      wx.navigateTo({
        url: `/pages/getphoneInfo/index?mineFlag=mine`,
      })
    }
  },

  goToSpecialcourtesy() {
    if (this.data.ifSetUserInfo) {
      wx.navigateTo({
        url: '/pages/specialcourtesy/specialcourtesy',
      })
    } else {
      wx.navigateTo({
        url: `/pages/getphoneInfo/index?mineFlag=mine`,
      })
    }
  },

  goToExchangeCard() {
    wx.navigateTo({
      url: '/pages3/exchangeCard/exchangeCard',
    })
    // if (this.data.ifSetUserInfo) {
    //   wx.navigateTo({
    //     url: '/pages3/exchangeCard/exchangeCard',
    //   })
    // } else {
    //   wx.navigateTo({
    //     url: `/pages/getphoneInfo/index?mineFlag=mine`,
    //   })
    // }
  },

  goToQuestionnaire() {
    if (this.data.ifSetUserInfo) {
      wx.navigateTo({
        url: '/pages/questionnaire/questionnaireLsit/questionnaireLsit',
      })
    } else {
      wx.navigateTo({
        url: '/pages/questionnaire/questionnaireLsit/questionnaireLsit',
      })
      // wx.navigateTo({
      //   url: `/pages/getphoneInfo/index?mineFlag=mine`,
      // })
    }
  },

  goToComplaint() {
    if (this.data.ifSetUserInfo) {
      wx.navigateTo({
        url: '/pages3/complaint/complaint',
      })
    } else {
      wx.navigateTo({
        url: '/pages3/complaint/complaint',
      })
      // wx.navigateTo({
      //   url: `/pages/getphoneInfo/index?mineFlag=mine`,
      // })
    }
  },

  goToBusinessSwitch() {
    if (this.data.ifSetUserInfo) {
      wx.navigateTo({
        url: this.data.goUrl,
      })
    } else {
      wx.navigateTo({
        url: `/pages/getphoneInfo/index?mineFlag=mine`,
      })
    }
  },

  share() {
    if (this.data.ifSetUserInfo) {
      wx.navigateTo({
        url: '/pages/shareFriend/shareFriend',
      })
    } else {
      wx.navigateTo({
        url: `/pages/getphoneInfo/index?mineFlag=mine`,
      })
    }
  },
  /**
   * 跳转到商场信息的页面
   */
  gomallInfo: function () {
    wx.navigateTo({
      url: '/pages/mallInfo/mallInfo',
    })
  },
  showVersion: function () {
    /**
     * 长按显示版本号
     */
    let that = this;
    if (that.data.flag == 'hidden') {
      that.setData({
        flag: 'show'
      });
    }
  },
  gotoedit: function () {
    // this.checkUserStatus();
    console.log('goSetAvatar');
    wx.navigateTo({
      url: '/pages3/setUserInfo/index'
    })
  },
  onLoad(options) {
    // this.getLocation();
    this.updateScene();
    // this.getRoomId();
    // this.getRoomList();
    console.log(wx.getExtConfigSync())
    this.getPrivacySetting()
  },

  clickPrivacy(e) {

  },

  closePrivacy() {
    this.setData({
      showPrivacy: false
    })
  },

  getPrivacySetting() {
    const canIUsePrivacy = wx.canIUse('getPrivacySetting')
    console.log(canIUsePrivacy, 'canIUse getPrivacySetting')
    if (canIUsePrivacy) {
      wx.getPrivacySetting({
        success: res => {
          console.log(res, 'getPrivacySetting') // 返回结果为: res = { needAuthorization: true/false, privacyContractName: '《xxx隐私保护指引》' }
          if (res.needAuthorization) {
            // 需要弹出隐私协议
            this.setData({
              showPrivacy: false
            })
          } else {
            // this.setData({
            //   showPrivacy: true
            // })
            // 用户已经同意过隐私协议，所以不需要再弹出隐私协议，也能调用已声明过的隐私接口
            // wx.getUserProfile()
            // wx.chooseMedia()
            // wx.getClipboardData()
            // wx.startRecord()
            // this.setData({
            //   showPrivacy: true
            // })
          }
        },
        fail: () => { },
        complete: () => { }
      })
    }
  },

  handleAgreePrivacyAuthorization() {
    console.log('Privacy Agreed!');
    this.setData({
      showPrivacy: true
    })
    // 用户同意隐私协议事件回调
    // 用户点击了同意，之后所有已声明过的隐私接口和组件都可以调用了
    // wx.getUserProfile()
    // wx.chooseMedia()
    // wx.getClipboardData()
    // wx.startRecord()
  },

  handleOpenPrivacyContract() {
    // 打开隐私协议页面
    wx.openPrivacyContract({
      success: () => {
        // this.setData({
        //   showPrivacy: false
        // })
      }, // 打开成功
      fail: () => { }, // 打开失败
      complete: () => { }
    })
  },
  //获取房间列表
  getRoomList() {
    Http.get({
      url: config.api.getRoomList,
      data: {
        token: app.globalData.token,
        appId: config.weapp.AppId
      }
    }).then(res => {
      console.log(res)
    })
  },
  getRoomId() {
    let roomId = [3] // 填写具体的房间号，可通过下面【获取直播房间列表】 API 获取
    let customParams = encodeURIComponent(JSON.stringify({
      path: 'pages/index/index',
      pid: 1
    })) // 开发者在直播间页面路径上携带自定义参数（如示例中的path和pid参数），后续可以在分享卡片链接和跳转至商详页时获取，详见【获取自定义参数】、【直播间到商详页面携带参数】章节（上限600个字符，超过部分会被截断）
    console.log(customParams, 777777777)
    this.setData({
      roomId,
      customParams
    })
  },
  /**
   * 获得经纬度
   */
  // getLocation() {
  //   let that = this;
  //   wx.getLocation({
  //     type: "wgs84",
  //     success: function(res) {
  //       console.log(res)
  //       if (res && res.longitude && res.latitude) {
  //         Http.post({
  //           url: config.api.updateLBS,
  //           data: {
  //             latitude: res.latitude,
  //             longitude: res.longitude
  //           }
  //         }).then(res => {
  //           console.log(res)
  //         })
  //       }
  //     },
  //     fail: error => {
  //       console.log(error);
  //     }
  //   })
  // },
  /**
   * 用户更新scene
   */
  updateScene() {
    Http.post({
      url: config.api.updateScene,
      data: {
        scene: app.globalData.scene
      }
    }).then(res => {
      console.log(res)
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.ifPhoneInfo()

    if (businessSwitch) {
      let openId = wx.getStorageSync("openId")
      this.setData({
        goUrl: `plugin://auto-points-plugin/index?openid=${openId}&mch_id=${this.data.mch_id}`
      })
    }
    console.log(this.data.goUrl)
    let that = this;
    that.userAuthorization()
    if (typeof that.getTabBar === 'function' &&
      that.getTabBar()) {
      if (ifStoreApp == 1) {
        that.getTabBar().setData({
          selected: 1
        })
      } else if (ifStoreApp == 2) {
        that.getTabBar().setData({
          selected: 2
        })
      } else {
        that.getTabBar().setData({
          selected: 3,
        })
      }
    }

    that.setData({
      appVersion: extConfig.appVersion,
    })
    /**
     * couponNum
     * couponNum2
     */
    let num = wx.getStorageSync('couponNum');
    let num1 = wx.getStorageSync('couponNum2');
    // wx.hideTabBarRedDot({
    //   index: 3
    // });
    if (num == 'couponNum1') {
      wx.setStorage({
        key: 'couponNum',
        data: "couponNum1",
      })
      that.setData({
        couponNum: "couponNum1"
      })
    } else if (num == 'couponNum') {
      that.setData({
        couponNum: "couponNum"
      })
    };
    if (num1 == 'couponNum3') {
      wx.setStorage({
        key: 'couponNum2',
        data: "couponNum3",
      })
      that.setData({
        couponNum2: "couponNum3"
      })
    } else if (num1 == 'couponNum2') {
      that.setData({
        couponNum2: "couponNum2"
      });
    };

    Http.get({
      url: config.api.getScore,
      data: {}
    }).then(res => {
      if (res.data.address && res.data.name && res.data.sex && res.data.birthdate) {
        that.setData({
          showEdit: true
        })
      }
      let curPhone = res.data.phone ? res.data.phone : '';
      if (curPhone) {
        let curPhoneList = curPhone.split('');
        let curPhoneList01 = [];
        curPhoneList.forEach((item, index) => {
          if (index >= 3 && index <= 6) {
            item = '*';
          }
          curPhoneList01.push(item);
        })
        curPhone = curPhoneList01.join('');
      }
      that.setData({
        score: res.data.score,
        credit: res.data.credit,
        curPhone: curPhone,
        levelName: res.data.levelName,
        userId: res.data.userId,
        userAvatarUrl: res.data.avatarUrl,
        userName: res.data.nickName
      })
      if (res.data.nickName) {
        that.setData({
          ismember: true,
          memberId: res.data.id
        })
        var size = this.setCanvasSize();
        var initUrl = JSON.stringify({
          flagid: res.data.id
        });
      }
    })
      .catch(err => {
        wx.showModal({
          title: '提示',
          content: err.errMsg,
          showCancel: false
        })
      })
    //暂时注释
    // that.getrun();


    //查询关于我们
    Http.get({
      url: config.api.getMallInfo,
      data: {}
    }).then(res => {
      if (res.code == 200) {
        this.setData({
          memberName: res.data.name,
          memberLogo: res.data.imgUrlH
        })
      }
      if (res.data.businessHours !== '[]') {
        that.setData({
          aboutShow: true
        })
      } else {
        that.setData({
          aboutShow: false
        })
      }
    })
      .catch(err => { })
  },
  //适配不同屏幕大小的canvas
  setCanvasSize: function () {
    var size = {};
    try {
      var res = wx.getSystemInfoSync();
      var scale = 750 / 500;
      //不同屏幕下canvas的适配比例；设计稿是750宽
      var width = res.windowWidth / scale;
      var height = width;
      //canvas画布为正方形
      size.w = width;
      size.h = height;
    } catch (e) {
      // Do something when catch error
      console.log("获取设备信息失败" + e);
    }
    return size;
  }
});