
import { customRequest } from './utils/request.js'

App({
  globalData: {
    userInfo: null,
    // ip: 'http://bl7.matripe.com.cn:8001',
    ip: "https://daotian.matripe.com.cn",
    // ip: "https://test.renminshitang.com.cn/daotian/api_dev",
    // ip: 'http://localhost:8001',
    sessionId: "",
    appId: wx.getAccountInfoSync().miniProgram.appId,
    headers2: {
      "content-type": "multipart/form-data",
      Authorization: "",
      Cookie: "",
      appId: wx.getAccountInfoSync().miniProgram.appId,
      "g-open-env": 'MP_MINI',
      // 请求来源标识 1.小程序 2.app 3.网页
      appClassify: 1,
      // appName: encodeURIComponent('伯才')
    },
    headers1: {
      "content-type": "application/json",
      Authorization: "",
      Cookie: "",
      appId: wx.getAccountInfoSync().miniProgram.appId,
      "g-open-env": 'MP_MINI',
      appClassify: 1,
      // appName: encodeURIComponent('伯才')
    },
    headers: {
      "content-type": "application/x-www-form-urlencoded",
      Authorization: "",
      Cookie: "",
      appId: wx.getAccountInfoSync().miniProgram.appId,
      "g-open-env": 'MP_MINI',
      appClassify: 1,
      // appName: encodeURIComponent('伯才')
    },
    userLoginTokenInfo: {
      tel: "", //用户电话
      token: "", //用户token
    },
    isLogin: false, //是否登录
    loginUserInfo: {
      id: "",
      userName: "",
      tel: "",
      imgSrc: "",
    },
    lng: "",
    lat: "",
    autoLoginTag: 0, //是否是自动登录，0否、1是
    isScanQRCodes: 0, //是否是扫码进来的，0否、1是
    hasUserInfo: 1, //是否有用户授权信息
    agencyStatus: 0, //是否是代理
    openId: "",
    unionid: "",
    isCommission: 0, //是否计算佣金，0否、1是
    user: {}, //用户信息
    serviceInfo: {}, // 客服电话
    version: null,
    loginKey: "",
  },
  // "permission": {
  //   "scope.userLocation": {
  //     "desc": "你的位置信息将用于小程序位置接口的效果展示"
  //   }
  // },
  onLaunch () {
    let that = this;
    wx.hideShareMenu();
    console.log('appId', this.globalData.appId);
    Array.prototype.logResult = function (data) {
      console.log("Array");
      return data;
    };
    const updateManager = wx.getUpdateManager();
    updateManager.onCheckForUpdate(function (res) {
      console.log("onCheckForUpdate====", res);
      // 请求完新版本信息的回调
      if (res.hasUpdate) {
        console.log("res.hasUpdate====");
        updateManager.onUpdateReady(function () {
          wx.showModal({
            title: "更新提示",
            content: "新版本已经准备好，是否重启应用？",
            confirmColor: "#1890ff",
            success: function (res) {
              console.log("success====", res);
              // res: {errMsg: "showModal: ok", cancel: false, confirm: true}
              if (res.confirm) {
                // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                updateManager.applyUpdate();
              }
            },
          });
        });
        updateManager.onUpdateFailed(function () {
          // 新的版本下载失败
          wx.showModal({
            title: "已经有新版本了哟~",
            content: "新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~",
            confirmColor: "#1890ff",
          });
        });
      }
    });
    // 获取小程序版本
    const miniProgram = wx.getAccountInfoSync();
    console.log(miniProgram);
    this.globalData.version = miniProgram.miniProgram.version || "1.0.100";
    that.getServiceInfo().then(() => {
      console.log("getServiceInfo");
    });

    // 展示本地存储能力
    const { statusBarHeight, platform } = wx.getSystemInfoSync();

    const { top, height } = wx.getMenuButtonBoundingClientRect();
    console.log(statusBarHeight);
    console.log(wx.getMenuButtonBoundingClientRect());
    console.log(top, height);
    // 状态栏高度
    wx.setStorageSync("statusBarHeight", statusBarHeight);
    // 胶囊按钮高度 一般是32 如果获取不到就使用32
    wx.setStorageSync("menuButtonHeight", height ? height : 32);
    // 胶囊按钮信息
    wx.setStorageSync("menuButtonInfo", wx.getMenuButtonBoundingClientRect());

    // 判断胶囊按钮信息是否成功获取
    if (top && top !== 0 && height && height !== 0) {
      const navigationBarHeight = (top - statusBarHeight) * 2 + height;
      // 导航栏高度
      wx.setStorageSync("navigationBarHeight", navigationBarHeight);
    } else {
      wx.setStorageSync("navigationBarHeight", platform === "android" ? 48 : 40);
    }
    const logs = wx.getStorageSync("logs") || [];
    logs.unshift(Date.now());
    wx.setStorageSync("logs", logs);

    this.getLoginUserTokenInfo().then(() => {
      that.getTemplateList()

    });
    // 登录
    wx.login({
      success: (res) => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        // this.appLoginByTel()
      },
    });
    // 引入云开发
    // wx.cloud.init({
    // 	env: "cloud1-2gnvowo5e7ab00ec",
    // });
  },
  /**
  * 获取商家配置信息
  */
  getConfigInfo () {
    let that = this;
    customRequest("/yishoudan/agency/config/get", { header: 'headers' }).then((res) => {
      that.globalData.configInfo = res.data.data.config
      // setData({
      //   configInfo: res.data.data.config,
      // });
      wx.setStorageSync('configInfo', res.data.data.config)
    })
    // wx.request({
    //   url: that.globalData.ip + "/yishoudan/agency/config/get", // 分类列表获取接口
    //   header: that.globalData.headers,
    //   method: "GET",
    //   success: function (res) {
    //     console.log(res);
    //     if (res.data.status == 200) {

    //     }
    //   },
    // });
  },
  isEmptyCheck: function (str) {
    if (str == null || str == "" || str == "null" || str == "undefined" || typeof str == "undefined") {
      return true;
    }
    return false;
  },
  isNotEmptyCheck: function (str) {
    return !this.isEmptyCheck(str);
  },
  logout: function () {
    var that = this;
    return new Promise(function (reslove, reject) {
      try {
        wx.removeStorageSync("loginUserTokenInfo");
        wx.removeStorageSync("loginUser");
        wx.removeStorageSync("LOGINUSER_ID");
        that.globalData.autoLoginTag = 0;
        that.globalData.sessionId = "";
        that.globalData.loginUserInfo = {};
        that.globalData.userLoginTokenInfo = {};
        that.globalData.headers.Cookie = "";
        that.globalData.headers2.Cookie = "";
        // that.globalData.header.Authorization = "";
        that.globalData.headers.Authorization = "";
        that.globalData.headers1.Authorization = "";
        that.globalData.headers2.Authorization = "";
        that.globalData.isLogin = false;
        that.globalData.hasUserInfo = 0;
        reslove();
      } catch (e) {
        console.log("退出登录失败");
        console.log(e);
        reject();
      }
    });
  },
  load: function (text) {
    wx.showLoading({
      title: text,
      mask: true,
    });
  },
  hideLoad: function () {
    wx.hideLoading();
  },
  showTips: function (_that, msg) {
    /*_that.setData({
    popErrorMsg: msg,
    pop: 1,
  });
  setTimeout(() => {
    _that.setData({
      popErrorMsg: '',
      pop: 0,
    });
    return;
  }, 2000)*/

    wx.showToast({
      icon: "none",
      title: msg,
      duration: 3000,
    });
  },
  setLoginUserTokenInfo: function (tel, token) {
    var that = this;
    return new Promise(function (resolve, reject) {
      try {
        that.globalData.userLoginTokenInfo.tel = tel;
        that.globalData.userLoginTokenInfo.token = token;
        // debugger
        wx.setStorageSync("loginUserTokenInfo", that.globalData.userLoginTokenInfo);
        that.appLoginByTel(resolve, reject);
      } catch (e) {
        console.log("设置登录信息错误");
        console.log(e);
        reject();
      }
    });
  },
  /**
  * 微信快速登录调用
  */
  appLoginByTel: function (resolve, reject) {
    var that = this;

    var channelContactId = "";
    try {
      var value = wx.getStorageSync("fromQrCodeChannelContactId");
      if (value) {
        console.log("fromQrCodeChannelContactId：======", value);
        channelContactId = value;
      }
    } catch (e) {
      console.log("获取缓存设置的参数错误：", e);
    }

    var agencyUserId = "";
    try {
      var value = wx.getStorageSync("storageSyncAgencyUserId");
      if (value) {
        console.log("storageSyncAgencyUserId======", value);
        agencyUserId = value;
      }
    } catch (e) {
      console.log("获取缓存设置的参数错误：", e);
    }
    console.log('that.globalData', that.globalData);
    customRequest("/appLoginByTelYiShouDan", {
      method: 'post', header: 'headers', data: {
        tel: that.globalData.userLoginTokenInfo.tel,
        autoLoginTag: that.globalData.autoLoginTag,
        isScanQRCodes: that.globalData.isScanQRCodes,
        channelContactId: channelContactId,
        agencyUserId: agencyUserId,
        openId: that.globalData.openId,
        unionid: that.globalData.unionid,
        loginKey: that.globalData.loginKey,
      },
    }).then((res) => {
      console.log('appLoginByTelYiShouDan res', res);
      if (res.data.status == 200) {
        that.globalData.user = res.data.data.user;
        // that.globalData.user.idauth = 0;
        that.globalData.sessionId = res.data.data.sessionId;
        // that.globalData.headers.Cookie = "JSESSIONID=" + res.data.data.sessionId;
        // that.globalData.headers2.Cookie = "JSESSIONID=" + res.data.data.sessionId;
        that.globalData.headers.Authorization = "Bearer " + res.data.data.token;
        that.globalData.headers2.Authorization = "Bearer " + res.data.data.token;

        that.globalData.isLogin = true;
        that.globalData.read = res.data.data.read;
        that.globalData.userLoginTokenInfo.tel = res.data.data.tel;
        that.globalData.userLoginTokenInfo.token = res.data.data.token;

        that.globalData.hasUserInfo = res.data.data.imgSrc != "" && res.data.data.imgSrc != null && res.data.data.imgSrc != undefined && res.data.data.nickName != "" && res.data.data.nickName != null && res.data.data.nickName != undefined ? 1 : 0
        that.globalData.loginUserInfo = res.data.data
        if (that.globalData.loginUserInfo.admin == true) {
          that.globalData.loginUserInfo.user.agencyRole = 2
        } else {
          that.globalData.loginUserInfo.user.agencyRole = 3

        }
        wx.setStorageSync("loginUserTokenInfo", that.globalData.userLoginTokenInfo);
        wx.setStorageSync("loginUser", that.globalData.loginUserInfo);
        wx.setStorageSync("LOGINUSER_ID", that.globalData.loginUserInfo.user.agencyId);
        console.log("readySet");
        wx.showToast({
          title: "登录成功",
          icon: "success",
          duration: 2000,
        });

        that.getServiceInfo().then(() => {
          console.log("getServiceInfo");
        });
        console.log("appLoginByTel" + "+++++++++++++++++++++++++++++++++++++++++++");

        resolve();
      } else {
        wx.showToast({
          icon: "none",
          title: res.data.msg,
          duration: 2000,
        });
        reject();
      }
      if (that.userLoginCallback) {
        that.userLoginCallback(res);
      }
      console.log("login====result=======1");
      console.log(that.globalData);
      console.log("login====result=======2");
    })
    // wx.request({
    //   url: that.globalData.ip + "/appLoginByTelYiShouDan",
    //   data: {
    //     tel: that.globalData.userLoginTokenInfo.tel,
    //     autoLoginTag: that.globalData.autoLoginTag,
    //     isScanQRCodes: that.globalData.isScanQRCodes,
    //     channelContactId: channelContactId,
    //     agencyUserId: agencyUserId,
    //     openId: that.globalData.openId,
    //     unionid: that.globalData.unionid,
    //     loginKey: that.globalData.loginKey,
    //   },
    //   header: {
    //     "content-type": "application/json",
    //   },
    //   success: function (res) {
    //     console.log(res);


    //   },
    // });
  },
  /**
   * 获取伯才客服信息
   *
   *
   */
  getServiceInfo () {
    let that = this;
    console.log("fromLogin");
    return new Promise((resolve, reject) => {
      customRequest("/costumer/manager", { header: 'headers' }).then((res) => {
        that.globalData.serviceInfo = res.data.data;
        console.log(that.globalData.serviceInfo);
        if (that.globalData.serviceInfo.workPhone) {
          let tel = that.globalData.serviceInfo.workPhone.trim();
          let num1 = tel.slice(0, 3);
          let num2 = tel.slice(3, 7);
          let num3 = tel.slice(7, 11);
          that.globalData.serviceInfo.tel = num1 + "-" + num2 + "-" + num3;
          console.log(that.globalData.serviceInfo.tel);
        }
        resolve(true);
      })
      // wx.request({
      //   url: that.globalData.ip + "/costumer/manager",
      //   header: that.globalData.headers,
      //   success (res) {
      //     console.log(res);
      //     if (res.data.status == 200) {

      //     }
      //   },
      // });
    });
  },
  /**
  * 获取模板图片
  *
  *
  */
  getTemplateList () {
    let that = this;
    customRequest("/daotian/image/list", { method: 'GET', header: 'headers' }).then((res) => {
      that.globalData.templateList = res.data.data.images;

    })
    // wx.request({
    //   url: that.globalData.ip + "/daotian/image/list",
    //   success (res) {
    //     console.log(res);
    //     if (res.data.status == 200) {
    //     }
    //   },
    // });
  },
  getLoginUserTokenInfo: function () {
    var that = this;
    // debugger;
    return new Promise((resloveOutter, rejectOutter) => {
      try {
        var value = wx.getStorageSync("loginUserTokenInfo");
        console.log(value);
        if (value) {
          that.globalData.userLoginTokenInfo = value;
          // console.log(that.isNotEmptyCheck(that.globalData.userLoginTokenInfo.token));
          if (that.isNotEmptyCheck(that.globalData.userLoginTokenInfo.token)) {
            let token = that.globalData.userLoginTokenInfo.token;
            that.globalData.headers.Authorization = "Bearer " + token;
            that.globalData.headers1.Authorization = "Bearer " + token;
            that.globalData.headers2.Authorization = "Bearer " + token;
            console.log(that.globalData.headers);
            customRequest("/checkToken", { method: 'GET', header: 'headers', data: { loginKey: that.globalData.loginKey } }).then((res) => {
              if (res.data.status == 200) {
                if (wx.getStorageSync("messageClick" + res.data.data.id)) {
                  console.log("messageClick" + res.data.data.id);
                } else {
                  wx.setStorageSync("messageClick" + res.data.data.id, false);
                }
                that.globalData.isLogin = true;
                that.globalData.test = "b";
                that.globalData.user = res.data.data.user;
                // that.globalData.user.idauth = 0;

                that.globalData.loginUserInfo = res.data.data;
                if (that.globalData.loginUserInfo.admin == true) {
                  that.globalData.loginUserInfo.user.agencyRole = 2
                } else {
                  that.globalData.loginUserInfo.user.agencyRole = 3

                }
                console.log(that.globalData.loginUserInfo);
                that.getServiceInfo().then(() => {
                  console.log("getServiceInfo");
                });
                wx.setStorageSync("loginUser", that.globalData.loginUserInfo);
                wx.setStorageSync("LOGINUSER_ID", that.globalData.loginUserInfo.user.agencyId);
                if (that.userLoginCallback) {
                  that.userLoginCallback(res);
                }
                let loginKeyTmp = that.globalData.loginKey;
                that.getConfigInfo()

                resloveOutter(loginKeyTmp);
              } else {
                //已过期
                that.globalData.autoLoginTag = 1;
                // that.appLoginByTel();
                // that.globalData.isLogin = false;
                return new Promise(function (resolve, reject) {
                  try {
                    that.appLoginByTel(resolve, reject);
                  } catch (e) {
                    console.log("设置登录信息错误");
                    console.log(e);
                    reject();
                  }
                });
                rejectOutter();
              }
            })
            // wx.request({
            //   url: that.globalData.ip + "/checkToken",
            //   method: "GET",
            //   header: that.globalData.headers,
            //   data: { loginKey: that.globalData.loginKey },
            //   success: function (res) {
            //     console.log(res);


            //   },
            // });
            // console.log(that.globalData.isLogin);
          } else if (that.isNotEmptyCheck(that.globalData.userLoginTokenInfo.tel)) {
            that.globalData.autoLoginTag = 1;
            // that.appLoginByTel();

            return new Promise(function (resolve, reject) {
              try {
                that.appLoginByTel(resolve, reject);
              } catch (e) {
                console.log("设置登录信息错误");
                console.log(e);
                reject();
              }
            });
            rejectOutter();
          }
        } else {
          console.log("nologinInfo");
          if (that.userLoginCallback) {
            that.userLoginCallback();
          }
          rejectOutter();
        }
      } catch (e) { }
    });
  },
  onTabItemTap (e) {
    console.log(123);
    console.log(e);
    let that = this;
    if (!that.globalData.isLogin) {
      //   wx.showModal({
      //     title: '提示',
      //     content: '账号尚未登录，请先登录账号',
      //     success: res => {
      //       if (res.confirm) {
      wx.navigateTo({
        url: "/pages/login/login",
      });
      //       } else if (res.cancel) {
      //         wx.reLaunch({
      //           url: '/pages/main/homePage'
      //         })
      //       }
      //     }
      //   })
    }
  },
  dialog: function (title, content, btxt) {
    wx.showModal({
      title: title,
      content: content,
      showCancel: false,
      confirmColor: "#027AFF",
      confirmText: btxt,
      success: function (res) {
        if (res.confirm) {
          console.log("用户点击确定");
        } else if (res.cancel) {
          console.log("用户点击取消");
        }
      },
    });
  },
  vibrateShort () {
    wx.vibrateShort({
      type: "heavy",
      success: function (e) {
        console.log(e);
      },
    });
  },
  sharePageImage (path = "/pages/firstBill/index", image = "https://matripe-cms.oss-cn-beijing.aliyuncs.com/1shoudan/fenxiang2025.png", title = " ") {
    let params = {
      path: path,
      // imageUrl: this.store().localBaseImg + 'share.png', // image ? image : 
      imageUrl: image,
      title: title
    };
    console.log('分享数据:', params)
    return params;
  },
  copyFun (data, callBack) {
    wx.setClipboardData({
      data,
      success (res) {
        if (callBack) {
          callBack();
        } else {
          console.log(123123123);
          wx.showToast({
            title: "内容已复制",
            icon: "none",
            duration: 1500,
          });
        }
      },
    });
  }
});
