// pages/member/index_v2/index_v2.js
var app = getApp();
var getInvite = require("../../mybehaviors/getInvite/getInvite");
Page({
  behaviors: [getInvite],
  /**
   * 页面的初始数据
   */
  data: {
    U_tabcontrol: true,
    order_active: 0,
    plugin_active: 'recommend_goods',
    order_list: [],
    pluginsList: [],
    plugin_handle_list: [],
    plugins_data: [],
    service: "",
    showPopup: false,


    // 默认组件数据
    btnData: {
      "button_size": 40,
      "over_top": 500,
      "position_location": "right",
      "icon_url": ""
    },
    goodsData: {
      "preview_color": "#f5f5f5",
      "sort_style": {
        "choose_icon": "2"
      },
      "padding_top": 0,
      "padding_bottom": 0,
      "padding_left": 10,
      "padding_right": 10,
      "item_radius": 5,
      "show_shadow": false,
      "show_border": false,
      "border_color": "#BFB7B7",
      "good_tag": {
        "choose_icon": "0",
        "image": ""
      },
      "button_type": "3",
      "button_title": "立即购买",
      "button_bg_color": "#ff2c29",
      "button_color": "#ffffff",
      "content_list": [
        "1",
        "3",
        "4",
        "7"
      ],
      "show_price_text": false,
      "disable_good": "0",
      "goods_type": "list"
    },
    limitData: {
      "preview_color": "#f5f5f5",
      "sort_style": {
        "choose_icon": "2"
      },
      "padding_top": 0,
      "padding_bottom": 0,
      "padding_left": 10,
      "padding_right": 10,
      "item_radius": 5,
      "show_shadow": false,
      "show_border": false,
      "border_color": "#BFB7B7",
      "good_tag": {
        "choose_icon": "0",
        "image": ""
      },
      "button_type": "3",
      "button_title": "立即购买",
      "button_bg_color": "#ff2c29",
      "button_color": "#ffffff",
      "content_list": [
        "1",
        "3",
        "4",
        "7"
      ],
      "show_price_text": false,
      "disable_good": "0",
      "goods_type": "list"
    },
    articleData: {
      "get_style": "1",
      "get_number": 999,
      "article_style": "2",
      "article_bg": "#f5f5f5",
      "show_tab": true,
      "article_tab_bg": "#ffffff",
      "title_color": "#333",
      "title_active_color": "#ff2c29"
    },
    storeData: {
      "get_number": 999,
      "preview_color": "#f5f5f5",
      "font_size": 14,
      "font_color": "#666666",
      "border_radius": 35,
      "class_font_size": 14,
      "class_font_color": "#ffffff",
      "class_bg_color": "#adadad",
      "class_border_radius": 5,
      "location_font_size": 14,
      "location_font_color": "#666666",
      "discount_font_size": 14,
      "discount_title_color": "#ff2c29",
      "discount_font_color": "#666666",
      "discount_list": [
        "1",
        "2",
        "3",
        "4"
      ],
      "tag_font_size": 14,
      "tag_font_color": "#666666",
      "tag_bg_color": "#f3f2f2",
      "tag_border_color": "#ff8400",
      "tag_border_radius": 5,
      "show_goods": true,
      "tab_list": [],
      "tab_bg_color": "#ffffff",
      "tab_color": "#333333",
      "tab_active_color": "#ff8400"
    },
    communityData: {
      "get_style": "1",
      "get_number": 999,
      "preview_color": "#f5f5f5",
      "tab_bg": "#ffffff",
      "title_color": "#333",
      "title_active_color": "#ff2c29",
    },
    videoData: {
      "preview_color": "#f5f5f5",
      "get_style": "1",
      "get_number": 999
    },
    liveData: {
      choose_tab: "0",
      get_number: 20,
      preview_color: "#f5f5f5",
      record_id: 1,
      tab_active_color: "#ff2c29",
      tab_bg_color: "#ffffff",
      tab_color: "#333333",
    },
    groupList: [],
    groupListPage: 0,
    groupListTotalPage: 0,

    show_member_id: "",
    member_agent: "",
    // 登录弹窗
    lsgow: false,
    logintap: false,
    language: {},
    showDiy: [],
    //会员等级
    level_name: "",
    nickname: "",
    mobile: "",
    isshow: false, //判断二维码的显示
    //门店申请和供应商申请开关
    supplier_id: "",
    store_set: {
      is_cash_pay: "",
      is_open_cashier: "",
      is_write_information: "",
    },
    //课程中心
    signs: false,
    sign_name: "",
    //会员等级是否可点击
    isMemberGrade: false,
    helps: false,
    help_name: "",
    //显示提现
    // isWithdraw: false,
    //供应商申请
    haveShop: "",
    // 不否开户爱心值插件
    // isLove: false,
    // 爱心值名称
    // love_name: "",
    //是否开启关系链
    relation_switch: 0,
    //供应商申请
    supplier: "",
    //当前的会员model
    member_item: "",
    //优惠券
    coupon: {},
    //邀请码
    inviteCode: "",
    isshowInvit: "",
    //是否是推广员
    isGeneralize: "",
    //是否有推广下线资格 0-无资格；1-有资格
    // is_agent: 0,
    // 华侨币
    // coin: false,
    // coin_name: "",
    //头像
    avatar: "",
    //积分
    integral: "",
    //版权
    copyright: "",
    //版权图片
    copyrightImg: "",
    //余额
    credit: "",
    custom_value: "", //自定义值
    // custom_title: "", //自定义title
    // is_custom: false, //自定义参数
    validity_value: "", //会员等级时间限制 数据
    isELive: false, //生活缴费开关
    //冻结币
    // froze_name: "",
    // is_froze: false,
    //爱心值
    love_obj: {},
    // is_extension: false, //推广
    is_stroeWithdraw: false, //门店提现
    activeNames: [],
    template: "",
    //酒店订单显示
    // is_hotel: false,
    poster: "",
    PageNameList: {},
    footshow: false,
    isMCreated: 0,
    designerReadly: false,
    firstshow: false,
    // name_of_withdrawal: "",

    showcarrfootBol: false,
    dataIs: "block",
    iPnoneBottomBol: false,
    TemplateArray_1: [],
    TemplateArray_2: [],
    TemplateArray_3: [],

    //新装修
    page_id: "",
    components: [],
    advertising: {},
    isDecorate: false, //是否新装修
    clientWidth: "375",
    popShow: false,
    btnFlag: false,
    bottomShowBol: false,
    bottomShowBolIndex: 0,
    images: {},

    showChangeID: false,
    changidInfo: {
      uid: null,
      change_uid: null,
    },
    AuthorizedPhone: '',


    current_page: 1,
    total_page: 0,
    decorate_isLoadMore: true,
    lastIndex: "",
    // 平台协议
    PlatformAgreement: '',
    openPlatformAgreement: false,
    tapSelectAgreement: true,
    agreement_name: '平台协议',
    // end

    store_alone_temp: 0, // 门店独立参数
    // 兼容登录
    canIUseGetUserProfile: false,
    showAutoBindPhone: false, // 首次授权登录自动绑定手机号(PS：新会员！！！首次)
    canIUseGetUserProfileTap:false,
    order_active_show:true,
    //小程序没有做的入口
    notShow: ['lifeService', 'uidCode', 'codePage', 'teamSell', 'eliteAwardHome', 'admarketHome', 'Bonus', 'extendHelper', 'publish_manage', 'hireCarManage', 'TransHome', 'ReplenishmentApply', 'DeliveryTerminalApply', 'footprintMember', 'oilStation', 'signIndex', 'gduIndex'],
    // 用户信息编辑
    is_show_user_info_edit_popup: false,
    user_info: {
      'nickName': '',
      'avatarUrl': '',
      'gender': ''
    }
  },
  imageLoad: function (e) {
    var $width = e.detail.width, //获取图片真实宽度
      $height = e.detail.height;
    // ratio=$width/$height;    //图片的真实宽高比例
    // var viewWidth=375,           //设置图片显示宽度，左右留有16rpx边距
    // 		viewHeight=375/ratio;    //计算的高度值
    let image = {
      width: $width,
      height: $height
    };
    this.setData({
      images: image
    });
  },

  //获取模板id
  getTemplate_1() {
    let urlStr = app.getNetAddresss("member.member.getMiniTemplateCorrespond");
    let that = this;
    app._getNetWork({
      url: urlStr,
      data: {
        small_type: 4,
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          let array = [];
          for (let i = 0; i < res.data.length; i++) {
            array.push(res.data[i].template_id);
          }
          that.setData({
            TemplateArray_1: array,
          });
          wx.requestSubscribeMessage({
            tmplIds: that.data.TemplateArray_1,
            success(res) {
              wx.navigateTo({
                url: "/packageA/member/SupplierCenter/SupplierCenter?uid=" +
                  that.data.supplier_id,
              });
            },
            fail() {
              wx.navigateTo({
                url: "/packageA/member/SupplierCenter/SupplierCenter?uid=" +
                  that.data.supplier_id,
              });
            },
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  //获取模板id
  getTemplate_2() {
    let urlStr = app.getNetAddresss("member.member.getMiniTemplateCorrespond");
    let that = this;
    app._getNetWork({
      url: urlStr,
      data: {
        small_type: 5,
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          let array = [];
          for (let i = 0; i < res.data.length; i++) {
            array.push(res.data[i].template_id);
          }
          that.setData({
            TemplateArray_2: array,
          });
          wx.requestSubscribeMessage({
            tmplIds: that.data.TemplateArray_2,
            success(res) {
              wx.navigateTo({
                url: "/packageC/o2o/storeManage/storeManage",
              });
            },
            fail() {
              wx.navigateTo({
                url: "/packageC/o2o/storeManage/storeManage",
              });
            },
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  getTemplate_3() {
    let urlStr = app.getNetAddresss("member.member.getMiniTemplateCorrespond");
    let that = this;
    app._getNetWork({
      url: urlStr,
      data: {
        small_type: 6,
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          let array = [];
          for (let i = 0; i < res.data.length; i++) {
            array.push(res.data[i].template_id);
          }
          that.setData({
            TemplateArray_3: array,
          });
          wx.requestSubscribeMessage({
            tmplIds: that.data.TemplateArray_3,
            success(res) {
              wx.navigateTo({
                url: "/packageD/directSeeding/helperLiveList/helperLiveList",
              });
            },
            fail() {
              wx.navigateTo({
                url: "/packageD/directSeeding/helperLiveList/helperLiveList",
              });
            },
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getiPnoneBottom();
    if (options.scene) {
      let scene = decodeURIComponent(options.scene);
      if (scene) {
        var info_arr = [];
        info_arr = scene.split(",");
        for (let i = 0; i < info_arr.length; i++) {
          let chil_arr = [];
          chil_arr = info_arr[i].split("=");
          if (chil_arr[0] == "mid") {
            app._setMid(chil_arr[1]);
          }
        }
      }
    }
    if (options.mid) {
      app._setMid(options.mid);
    }
    if (this.firstlogin()) {
      this.setData({
        footshow: true,
      });
    } else {
      this._initData();
      // if (this.data.isMCreated == 0) {
      // 	this.newTemplate();
      // }
      this.getTemp();
      // this.customizeIncome();
    }

    this.setData({
      clientWidth: wx.getSystemInfoSync().windowWidth,
    });
    wx.removeStorageSync("setNewDecorateMember");
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let language = wx.getStorageSync("langIndex");
    if (language) {
      this.setData({
        language: language.en,
      });
      wx.setNavigationBarTitle({
        title: this.data.language["会员中心"],
      });
    }

  },
  PlatformAgreementOnChange(e) {
    console.log(e);
    this.setData({
      tapSelectAgreement: e.detail
    });
  },
  // 平台协议
  PlatformAgreementTap() {
    this.setData({
      openPlatformAgreement: true
    });
  },
  PlatformAgreementClose() {
    this.setData({
      openPlatformAgreement: false
    });
  },
  // end
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      order_active_show:true
    })
    wx.showShareMenu({
      withShareTicket: false,
      menus: ["shareAppMessage", "shareTimeline"],
    });
    if (this.firstlogin()) {
      this.setData({
        footshow: true,
        lsgow: true,
      });
      try {
        let showinfo = wx.getStorageSync("yz_basic_info");
        if (showinfo.home && showinfo.home.register_setting) {
          try {
            this.setData({
              PlatformAgreement: showinfo.home.register_setting.new_agreement ? showinfo.home.register_setting.new_agreement.replace(/<img/g, '<img style="width:100%;display:flex;"') : '',
              agreement_name: app._isTextEmpty(showinfo.home.register_setting.agreement_name) ? this.data.agreement_name : showinfo.home.register_setting.agreement_name,
            });
          } catch (error) {
            console.log(error);
          }

          let shopName = showinfo.home.mailInfo.name;
          if (app._isTextEmpty(showinfo.home.register_setting.title1)) {
            showinfo.home.register_setting.title1 = `欢迎来到${shopName}`;
          }
          if (app._isTextEmpty(showinfo.home.register_setting.title2)) {
            showinfo.home.register_setting.title2 = "登录尽享各种优惠权益！";
          }
          this.setData({
            showinfo: showinfo.home.register_setting,
          });
        } else {
          this.setData({
            showinfo: {
              title1: "欢迎来到",
              title2: "登录尽享各种优惠权益！"
            }
          });
        }

      } catch (err) {
        console.log(err);
      }
    } else {
      // setNewDecorateMember是否已经请求会员数据
      var value = wx.getStorageSync("setNewDecorateMember");
      if (value != 1) {
        this.getMemberData();
        wx.setStorageSync("setNewDecorateMember", "1");
      }
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.setData({
      isshow: false,
    });
  },
  getiPnoneBottom() {
    let that = this;
    try {
      var value = wx.getStorageSync("iPhoneBottom");
      if (value) {
        that.setData({
          iPnoneBottomBol: true,
        });
        // Do something with return value
      }
    } catch (e) {
      // Do something when catch error
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // #87379 清除首页装修缓存
    wx.removeStorageSync("new_decorate"); //登录之后清除首页缓存数据重新请求
    this.setData({
      order_active_show:false
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    // 下拉刷新
    console.log('onPullDownRefresh', new Date());
    this.getMemberData();
  },

  // 获取滚动条当前位置
  onPageScroll: function (e) {
    // 节流
    if (e.scrollTop > 80) {
      if (!this.data.btnFlag) {
        this.setData({
          btnFlag: true,
        });
      }
    } else {
      if (this.data.btnFlag) {
        this.setData({
          btnFlag: false,
        });
      }
    }

    if (this.data.bottomShowBol) {
      this.setData({
        bottomShowBol: false,
      });
    }

    // 下拉更多保留
    // if (e.scrollTop > 600) {
    //   if (this.data.decorate_isLoadMore) {
    //   }
    // }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.setData({
      bottomShowBol: true,
    });

    if (this.data.decorate_isLoadMore) {
      if (this.data.template === "03") {
        this.getMoreDecorate();
      } else if (this.data.template === "01") {
        this.getMorePluginData();
      }
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareTimeline() {},
  onShareAppMessage: function () {
    var value = wx.getStorageSync("yz_uid");
    var mid = "";
    if (value) {
      mid = value;
    }
    return {
      path: "/packageG/index/index?mid=" + mid,
    };
  },
  closePop() {
    this.setData({
      popShow: false,
    });
  },
  clearStorage: function () {
    wx.clearStorage({
      success: function () {},
    });
  },
  _initData() {
    this.setData({
      activeNames: [],
    });
  },
  _getMemberInfo(memberInfo) {
    this.data.supplier_id = memberInfo.member.uid;
    if (memberInfo.plugins.merchant && memberInfo.plugins.merchant.cashier) {
      this.setData({
        "store_set.is_open_cashier": 1,
      });
    }
    //邀请码
    this.setData({
      // isLove: memberInfo.member.love.status,
      // love_name: memberInfo.member.love.love_name,
      relation_switch: memberInfo.member.is_agent,
      // supplier: memberInfo.member.supplier, //供应商申请
      coupon: memberInfo.member.coupon || {},
      inviteCode: memberInfo.member.inviteCode.code ? memberInfo.member.inviteCode.code : "",
      isshowInvit: memberInfo.member.inviteCode.status ? memberInfo.member.inviteCode.status : "",
      isGeneralize: memberInfo.member.is_agent,
      member_item: memberInfo.member,
      member_order: memberInfo.order,
      avatar: memberInfo.member.avatar,
      nickname: memberInfo.member.nickname,
      integral: memberInfo.member.integral,
      copyright: memberInfo.member.copyright,
      copyrightImg: memberInfo.member.copyrightImg,
      uid: memberInfo.member.uid,
      level_name: memberInfo.member.level_name,
      credit: memberInfo.member.credit,
      integral_show: memberInfo.member.integral_show,
      mobile: memberInfo.member.mobile,
      love_obj: memberInfo.member.love_show,
    });
    for (let k in this.data.designer) {
      this.setData({
        ["designer[" + k + "].member_item"]: memberInfo.member,
        ["designer[" + k + "].member_order"]: memberInfo.order,
      });
    }
    wx.setStorage({
      key: "uid",
      data: memberInfo.member.uid,
    });
    wx.setStorage({
      key: "integral",
      data: this.data.integral.text,
    });

    // 处理插件列表
    if (memberInfo.plugins.plugins) {
      memberInfo.plugins.plugins.push({
        class: "icon-zb_all_more",
        image: "",
        mini_url: "/packageG/morePlugin/morePlugin",
        name: "morePlugin",
        title: "更多工具",
        url: "morePlugin"
      });

      let show_plugins = [];
      let plugin_handle_list = [];
      memberInfo.plugins.plugins.forEach((icon, index) => {
        if (this.data.notShow.indexOf(icon.url) < 0) {
          show_plugins.push(icon);
        }
      });

      let page = Math.ceil(show_plugins.length / 10); //==> 页数
      let num = 10; // ==> 每页多少个

      for (let i = 0; i < page; i++) {
        plugin_handle_list.push(show_plugins.slice(i * num, (i + 1) * num));
      }
      this.setData({
        plugin_handle_list: plugin_handle_list
      });
    }

    if (memberInfo.order && memberInfo.order_name) {
      // 处理订单列表
      let order_list = [];
      for (let order_key in memberInfo.order) {
        let title = memberInfo.order_name[order_key];

        if (memberInfo.order[order_key]) {
          if (order_key === "order" ||
            order_key === "hotel_order" ||
            order_key === "lease_order" ||
            order_key === "live_install_order" ||
            order_key === "live_install_work_order" ||
            order_key === "group_work_order"
          ) {
            memberInfo.order[order_key].push({
              status: -1,
              status_name: "全部订单",
              total: 0,
              class: "icon-fontclass-quanbudingdan"
            });
          } else if (order_key === "aggregation_cps_order") {
            memberInfo.order[order_key].push({
              status: 0,
              status_name: "全部订单",
              total: 0,
              class: "icon-fontclass-quanbudingdan"
            });
            memberInfo.order[order_key].push({
              status: 3,
              status_name: "卡券订单",
              total: 0,
              class: "icon-fontclass-shouhou1"
            });
          }
          order_list.push({
            name: order_key,
            title: title,
            list: memberInfo.order[order_key]
          });
        }
      }
      if (memberInfo.order_name.hasOwnProperty("ys_system")) {
        // 益生-线下订单；PS:点击直接跳转
        order_list.push({
          name: "ys_system",
          title: memberInfo.order_name["ys_system"],
          list: []
        });
      }
      this.setData({
        order_list: order_list
      });
    }

    // if (this.data.is_hotel) {
    //   this.getCustomizeHotelHead();
    // }

    if (
      this.data.love_obj.unable_love_show == 1 &&
      this.data.credit.is_show == 1 &&
      this.data.integral.is_show == 1
    ) {
      this.setData({
        fire: true,
      });
    } else {
      this.setData({
        fire: false,
      });
    }
  },
  clickOrderTab(e) {
    if (this.data.order_list[e.detail.name].name == "ys_system") {
      // 益生线下订单
      wx.navigateTo({
        url: "/packageA/member/myOrder_v2/myOrder_v2?status=0&orderType=ysSystem",
      });
    }
  },
  _getEnablePlugin(data) {
    let pluginsList = data;
    let asset_equity = [];
    let market = [];
    let merchant = [];
    let tool = [];
    // 控制显示入口
    if (data.asset_equity) {
      data.asset_equity.forEach((item, index) => {
        if (this.data.notShow.indexOf(item.url) < 0) {
          asset_equity.push(item);
        }
      });
    }

    if (data.market) {
      data.market.forEach((item, index) => {
        if (this.data.notShow.indexOf(item.url) < 0) {
          market.push(item);
        }
      });
    }

    if (data.merchant) {
      data.merchant.forEach((item, index) => {
        if (this.data.notShow.indexOf(item.url) < 0) {
          merchant.push(item);
        }
      });
    }

    if (data.tool) {
      data.tool.forEach((item, index) => {
        if (this.data.notShow.indexOf(item.url) < 0) {
          tool.push(item);
        }
      });
    }

    pluginsList.asset_equity = asset_equity;
    pluginsList.market = market;
    pluginsList.merchant = merchant;
    pluginsList.tool = tool;
    this.setData({
      pluginsList: pluginsList,
    });
    let template=this.data.template;
    if (data.ViewSet.member) {
      template = data.ViewSet.member.name ? data.ViewSet.member.name : "01";
    } else {
      template = "01";
    }

    // 从yz_basic_info获取新装修设置
    let basic_info = wx.getStorageSync("yz_basic_info");
    if (basic_info && basic_info.home.item.is_decorate === 1) {
      if (basic_info.home.item.ViewSet.member.is_default != 0) {
        template = basic_info.home.item.ViewSet.member.code.substring(6);
      } else {
        template = "01";
      }
    }

    if (this.data.designerStatus) {
      template = "03";
    }
    this.setData({template});

    if (this.data.template !== '03') {
      wx.setNavigationBarColor({
        frontColor: '#ffffff',
        backgroundColor: '#ffc11e',
        animation: {
          duration: 400,
          timingFunc: 'easeIn'
        }
      });
    }
  },

  //跳转至会员权益
  gotoMemberGrade() {
    //MemberGradeList
    if (this.data.isMemberGrade) {
      wx.navigateTo({
        url: "/packageB/member/MemberGradeList/MemberGradeList",
      });
    }
  },
  //会员权益插件是否开启
  _getMemberGrade(data) {
    this.setData({
      isMemberGrade: data.is_open == 1 ? true : false,
    });
    // this.data.isClick = (data.level_type == 2 ? true : false)
    for (let k in this.data.designer) {
      this.setData({
        ["designer[" + k + "].isMemberGrade"]: this.data.isMemberGrade,
      });
    }
  },
  //跳到爱心兑换值
  golove_index: function () {
    //love_index
    wx.navigateTo({
      url: "/packageB/member/love/Love_index/Love_index",
    });
  },
  //
  gobalance: function () {
    //balance
    if (this.data.store_alone_temp == 1) {
      wx.navigateTo({
        url: "/packageI/independenceBalance/independenceBalance?store_id="+app.globalData.STORE_ID,
      });
    }else {
      wx.navigateTo({
        url: "/packageA/member/balance/balance/balance",
      });
    }
  },
  Integral_love: function () {
    wx.navigateTo({
      url: "/packageB/member/Integral_love/Integral_love",
    });
  },
  CardIndexPage() {
    wx.navigateTo({
      url: "/packageB/member/CardIndex/CardIndex",
    });
  },
  gointegral: function () {
    //balance
    wx.navigateTo({
      url: "/packageA/member/balance/balance/balance",
    });
  },
  gointegral_v2: function () {
    //integral_v2
    wx.navigateTo({
      url: "/packageB/member/integral/integral",
    });
  },
  goextension: function () {
    //extension
    wx.reLaunch({
      url: "/packageG/pages/member/extension/extension",
    });
  },
  //跳到我的订单详情页面
  goorderlist: function (e) {
    //orderlist
    let status = e.currentTarget.dataset.status;
    wx.navigateTo({
      url: "/packageA/member/myOrder_v2/myOrder_v2?status=" + status,
    });
  },
  goaftersaleslist: function () {
    wx.navigateTo({
      url: "/packageD/member/myOrder/Aftersaleslist/Aftersaleslist",
    });
  },
  //跳到收藏页面
  gocollection(e) {
    wx.navigateTo({
      url: "/packageD/member/collection/collection",
    });
  },
  //跳转到足迹
  gofootprint(e) {
    wx.navigateTo({
      url: "/packageD/member/footprint/footprint",
    });
  },
  //跳转到评论页
  gomyEvaluation(e) {
    wx.navigateTo({
      url: "/packageD/member/myEvaluation/myEvaluation",
    });
  },
  //跳转到客户
  gomyRelationship(e) {
    //myRelationship
    wx.navigateTo({
      url: "/packageD/member/myRelationship/myRelationship",
    });
  },
  //跳转到地址
  goaddress(e) {
    wx.navigateTo({
      url: "/packageD/member/addressList/addressList",
    });
  },
  //跳转到优惠
  gocoupon(e) {
    wx.navigateTo({
      url: "/packageA/member/coupon_v2/coupon_v2",
    });
  },
  //跳转到设置
  goinfo(e) {
    wx.navigateTo({
      url: "/packageA/member/info/info",
    });
  },
  //跳转到汇聚支付
  goQucik(e) {
    wx.navigateTo({
      url: "/packageD/quickPay/quick_index/quick_index",
    });
  },
  //跳到签到页面
  gosign() {
    //sign
    wx.navigateTo({
      url: "/packageA/member/sign/sign",
    });
  },
  //跳转到收银台
  gocashier() {
    wx.navigateTo({
      url: "/packageC/cashier/cashier/cashier",
    });
  },
  //跳转到微店
  gomicroShop_home() {
    wx.navigateTo({
      url: "/packageC/microshop/microShop_home/microShop_home",
    });
    //microShop_home
  },
  //跳转到我要开店
  gomicroShop_apply() {
    //microShop_apply
    wx.navigateTo({
      url: "/packageC/microshop/microShop_apply/microShop_apply",
    });
  },
  //跳转到生活缴费
  golifeService() {
    //lifeService
  },
  //跳转到华侨币
  gooverseas_index() {
    //overseas_index
    wx.navigateTo({
      url: "/packageB/member/overseas_index/overseas_index",
    });
  },
  //跳转到门店管理
  gostoreManage() {
    this.getTemplate_2();
    //storeManage
  },
  //跳装到帮助页面
  gohelpcenter() {
    wx.navigateTo({
      url: "/packageB/member/helpcenter/helpcenter",
    });
  },
  //跳装到冻结币
  goFrozenCoin() {
    //FrozenCoin
    wx.navigateTo({
      url: "/packageB/member/FrozenCoin/FrozenCoin",
    });
  },
  //推广
  _getExtension(data) {
    this.setData({
      // is_extension: (data.switch == 1 ? true : false)
    });
  },
  //获取门店提现
  _getStroeWithdraw(data) {
    if (data) {
      this.setData({
        is_stroeWithdraw: data.is_store == 1 ? true : false,
      });
    }
  },
  //根据后台返回名字做跳转
  pluginGoto(e) {
    let item = e.currentTarget.dataset.item;
    let url = item.url;

    if (item.name == "courier") {
      wx.setStorage({
        key: "couriername",
        data: item.title,
      });
      wx.navigateTo({
        url: "/packageA/member/" + url + "/" + url,
      });
    } else if (item.url == "SupplierCenter") {
      let that = this;
      that.getTemplate_1();
    } else if (item.url == "extension") {
      this.goextension();
    } else if (item.url == "storeManage") {
      //跳转到门店管理
      this.gostoreManage();
    } else if (item.name == "supplier") {
      wx.navigateTo({
        url: "/packageA/member/" +
          url +
          "/" +
          url +
          "?uid=" +
          this.data.supplier_id,
      });
    } else if (item.url == "HotelManage") {
      wx.navigateTo({
        url: "/packageA/hotel/HotelManage/HotelManage?title=" +
          encodeURIComponent("酒店管理"),
      });
    } else if (item.url == "helperLiveList") {
      let that = this;
      that.getTemplate_3();
    } else if (item.url == "cloudIndex") {
      wx.navigateTo({
        url: "/packageE/others/cloudwarehouse/cloud_index/cloud_index",
      });
    } else if (item.url == "collageIndex") {
      wx.navigateTo({
        url: "/packageE/member/collage/collageIndex/collageIndex",
      });
    } else if (item.name == "m-erweima") {
      // 海报
      this.openQrCode(this.data.dataIs);
    } else if (item.mini_url) {
      wx.navigateTo({
        url: item.mini_url,
      });
    }
  },
  onChange(event) {
    this.setData({
      activeNames: event.detail,
    });
  },
  openQrCodebtn() {
    this.openQrCode(this.data.dataIs);
  },
  showcarrfoot(e) {
    let bol = e.detail;
    this.setData({
      showcarrfootBol: bol,
    });
  },
  showcarrfoot_ipx(e) {
    let bol = e.detail;
    this.setData({
      showcarrfootBol: bol,
    });
  },
  openQrCode(e) {
    this.setData({
      isshow: true,
    });
    // var that = this;
    // let earr;
    // try {
    //   if (e.currentTarget.dataset.is) {
    //     earr = e.currentTarget.dataset.is;
    //   } else {
    //     earr = e;
    //   }
    // } catch (err) {}
    // console.log(earr);
    // //打开二维码
    // if (!this.data.poster && earr != "none") {
    //   if (!this.data.timer) {
    //     wx.showLoading({
    //       title: "二维码生成中",
    //     });
    //     this.getPoster(earr);
    //     let time = setInterval((i) => {
    //       this.getPoster(earr);
    //     }, 3000);
    //     that.setData({
    //       timer: time,
    //     });
    //   } else {
    //     this.setData({
    //       dataIs: "none",
    //     });
    //   }
    // } else {
    //   // wx.hideTabBar({})
    //   this.setData({
    //     dataIs: "none",
    //   });
    //   clearInterval(this.data.timer);
    //   this.setData({
    //     isshow: true,
    //   });
    // }
  },
  // 隐藏二维码
  clicktapshow() {
    this.setData({
      isshow: false,
      lsgow: false,
    });
  },
  previewImage() {
    wx.showToast({
      title: "长按分享好友",
      icon: "none",
      duration: 1800,
    });
    wx.previewImage({
      urls: [this.data.poster], // 当前显示图片的链接
    });
  },
  saveImg() {
    wx.getSetting({
      success(res) {
        if (!res.authSetting["scope.writePhotosAlbum"]) {
          wx.authorize({
            scope: "scope.writePhotosAlbum",
            success() {
              console.log("授权成功");
            },
          });
        }
      },
    });
    var imgSrc = this.data.poster;
    wx.downloadFile({
      url: imgSrc,
      success: function (res) {
        //图片保存到本地
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function (data) {
            wx.showToast({
              title: "保存成功",
              icon: "none",
              duration: 2000,
            });
          },
          fail: function (err) {
            if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
              console.log("当初用户拒绝，再次发起授权");
              wx.openSetting({
                success(settingdata) {
                  if (settingdata.authSetting["scope.writePhotosAlbum"]) {
                    wx.showToast({
                      icon: "none",
                      title: "获取权限成功,再次长按保存图片",
                      duration: 1500,
                    });
                  } else {
                    wx.showToast({
                      icon: "none",
                      title: "获取权限失败,保存图片需要用户授权",
                      duration: 1500,
                    });
                  }
                },
              });
            }
          },
          complete(res) {
            console.log(res);
          },
        });
      },
    });
  },
  copybtn() {
    let inviteCode = this.data.inviteCode;
    wx.setClipboardData({
      data: inviteCode ? inviteCode : "",
      success(res) {
        wx.showToast({
          icon: "none",
          title: "复制成功",
          duration: 1000,
        });
      },
    });
  },
  gohotelOrderlist(e) {
    let status = e.currentTarget.dataset.status;
    let ordertype = e.currentTarget.dataset.ordertype;
    wx.navigateTo({
      url: "/packageA/member/myOrder_v2/myOrder_v2?status=" +
        status +
        "&orderType=" +
        ordertype,
    });
  },
  gotoAftersaleslist(e) {
    let ordertype = e.currentTarget.dataset.ordertype;

    wx.navigateTo({
      url: "/packageD/member/myOrder/Aftersaleslist/Aftersaleslist?orderType=" + ordertype,
    });
  },
  //获取酒店自定义字段
  getCustomizeHotelHead() {
    let that = this;
    let isQuestHotel = "";
    try {
      const value = wx.getStorageSync("customizeHotelHead");
      if (value) {
        isQuestHotel = value;
        // Do something with return value
      }
    } catch (e) {
      // Do something when catch error
    }
    if (!app._isTextEmpty(isQuestHotel)) {
      this.setData({
        PageNameList: JSON.parse(isQuestHotel),
      });
    } else {
      let urlStr = app.getNetAddresss(
        "plugin.hotel.frontend.hotel.get-hotel-info.get-custom-name"
      );
      app._getNetWork({
        url: urlStr,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              PageNameList: res.data,
            });
            try {
              wx.setStorageSync("customizeHotelHead", JSON.stringify(res.data));
            } catch (e) {
              console.log(e);
            }
          }
        },
        fail: function (res) {
          console.log(res);
        },
      });
    }
  },
  getNewDecorate(data) {
    this.setData({
      isDecorate: true,
      page_id: data.id,
      components: data.datas,
      decorate_isLoadMore: true,
    });

    if (data.page) {
      this.setData({
        total_page: data.page.total_page,
        current_page: data.page.current_page,
        bottomShowBolIndex: data.page.count - 1,
      });
    }

    if (data.page_info) {
      this.setData({
        advertising: data.page_info.advertising_id,
      });

      if (this.data.advertising.id && this.data.advertising.datas) {
        this.data.advertising.datas = JSON.parse(this.data.advertising.datas);
        this.setData({
          advertising: this.data.advertising,
        });
      }
    }

    let firstAdvertisement = wx.getStorageSync("firstAdvertisement");
    // 每个浏览周期只弹出一次
    if (
      this.data.advertising &&
      this.data.advertising.id &&
      !firstAdvertisement &&
      this.data.advertising.show_rule === 1
    ) {
      wx.setStorageSync("firstAdvertisement", true);
      this.setData({
        popShow: true,
      });
    }

    let popAdvertisement_expiration = wx.getStorageSync(
      "member_popAdvertisement_expiration"
    );
    let pop_newTime = parseInt(Date.parse(new Date()) / 1000);
    if (
      this.data.advertising &&
      this.data.advertising.id &&
      this.data.advertising.show_rule === 2 &&
      popAdvertisement_expiration < pop_newTime
    ) {
      let timestamp = parseInt(
        (new Date(new Date().toLocaleDateString()).getTime() +
          24 * 60 * 60 * 1000 -
          1) /
        1000
      ); //当天23:59:59
      wx.setStorageSync("member_popAdvertisement_expiration", timestamp);
      //每日小程序登录弹出
      this.setData({
        popShow: true,
      });
    }
  },
  getMoreDecorate() {
    this.setData({
      decorate_isLoadMore: false,
    });

    if (this.data.current_page < this.data.total_page) {
      this.setData({
        current_page: this.data.current_page + 1,
      });
      let urlStr = app.getNetAddresss(
        "plugin.decorate.frotend.decorate-api.get-page"
      );
      app._postNetWork({
        url: urlStr,
        data: {
          decorate_page: this.data.current_page,
          decorate_id: this.data.page_id,
        },
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            this.setData({
              decorate_isLoadMore: true,
              components: this.data.components.concat(res.data.datas),
            });
          } else {
            this.setData({
              decorate_isLoadMore: false,
              current_page: this.data.current_page - 1,
            });
            console.log(res.msg);
          }
        },
      });
    }
  },
  getStoreMember() {
    let urlStr = app.getNetAddresss(
      "plugin.store-alone-temp.frontend.member.index"
    );
    app._postNetWork({
      url: urlStr,
      data: {
        v: 2
      },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          let memberInfo = res.data;
          this.setData({
            store_alone_temp: 1,
            coupon: memberInfo.member.coupon || {},
            inviteCode: memberInfo.member.inviteCode.code ? memberInfo.member.inviteCode.code : "",
            isshowInvit: memberInfo.member.inviteCode.status ? memberInfo.member.inviteCode.status : "",
            isGeneralize: 1,
            member_item: memberInfo.member,
            member_order: memberInfo.order,
            avatar: memberInfo.member.avatar,
            nickname: memberInfo.member.nickname,
            integral: memberInfo.member.integral,
            copyright: memberInfo.member.copyright,
            copyrightImg: memberInfo.member.copyrightImg,
            uid: memberInfo.member.uid,
            level_name: memberInfo.member.level_name,
            credit: memberInfo.member.credit,
            integral_show: memberInfo.member.integral_show,
            mobile: memberInfo.member.mobile,
            love_obj: memberInfo.member.love_show,
            template: "01",
          });
          wx.stopPullDownRefresh();
          // 底部导航数据
          if (res.data.plugins_data && (!this.data.plugins_data.nav || this.data.plugins_data.nav.length <= 0)) {
            this.setData({
              plugins_data: res.data.plugins_data,
            });

            if (this.data.plugins_data.nav.length > 0) {
              this.setData({
                plugin_active: this.data.plugins_data.nav[0].code
              });

              if (this.data.plugin_active === 'recommend_goods') {
                this.setData({
                  ["goodsData.list"]: this.data.plugins_data.data
                });
              } else if (this.data.plugin_active === 'limitBuy_goods') {
                this.setData({
                  ["limitData.list"]: this.data.plugins_data.data,
                });
              } else {
                this.handlePlugin({
                  name: this.data.plugin_active
                });
              }
            }
          }

          // 处理插件列表
          if (memberInfo.plugin) {
            memberInfo.plugin.forEach((icon, index) => {
              if (this.data.notShow.indexOf(icon.url) >= 0) {
                memberInfo.plugin.splice(index, 1);
              }
            });

            let plugin_handle_list = [];
            let page = Math.ceil(memberInfo.plugin.length / 10); //==> 页数
            let num = 10; // ==> 每页多少个

            for (let i = 0; i < page; i++) {
              plugin_handle_list.push(memberInfo.plugin.slice(i * num, (i + 1) * num));
            }
            this.setData({
              'pluginsList.plugin_head': memberInfo.plugin_head,
              plugin_handle_list: plugin_handle_list
            });
          }

          // 处理订单列表
          if (memberInfo.order) {
            let order_list = [];
            for (let i = 0; i < memberInfo.order.length; i++) {
              if (memberInfo.order[i].key === "order") {
                memberInfo.order[i].order.push({
                  status: -1,
                  status_name: "全部订单",
                  total: 0,
                  class: "icon-fontclass-quanbudingdan"
                });
              }
              order_list.push({
                name: memberInfo.order[i].key,
                title: memberInfo.order[i].title,
                list: memberInfo.order[i].order
              });
            }
            this.setData({
              order_list: order_list
            });
          }

        } else {
          app.tips(res.msg);
        }
        this.setData({
          firstshow: true,
        });
      },
    });
  },
  getMemberData() {
    if (app.globalData.store_alone_temp == 1) {
      // 开启门店独立模块
      this.getStoreMember();
      return;
    }

    let that = this;
    let urlStr = app.getNetAddresss("member.member.member-data");
    app._getNetWork({
      url: urlStr,
      data: {
        v: 2,
      },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result === 1) {
          if (res.data.designer.data.page_plugins === "decorate") {
            that.getNewDecorate(res.data.designer.data);
            that.setData({
              designerStatus: res.data.designer.status,
            });
          } else {
            if (that.data.isMCreated == 0) {
              // that.data.isMCreated 是否第一次渲染
              that.newTemplate(res.data.designer);
            }
          }

          // console.log(res.data.plugins, '开启的插件');
          that._getMemberInfo(res.data);
          wx.stopPullDownRefresh();
          if (res.data.plugins_data && (!this.data.plugins_data.nav || this.data.plugins_data.nav.length <= 0)) {
            that.setData({
              plugins_data: res.data.plugins_data,
            });

            if (this.data.plugins_data.nav.length > 0) {
              this.setData({
                plugin_active: this.data.plugins_data.nav[0].code
              });

              if (this.data.plugin_active === 'recommend_goods') {
                that.setData({
                  ["goodsData.list"]: this.data.plugins_data.data
                });
              } else if (this.data.plugin_active === 'limitBuy_goods') {
                this.setData({
                  ["limitData.list"]: this.data.plugins_data.data,
                });
              } else {
                this.handlePlugin({
                  name: this.data.plugin_active
                });
              }
            }
          }

          if (res.data.service) {
            if (typeof (res.data.service) !== 'string') {
              that.setData({
                service: res.data.service
              });

              if (res.data.service.customer_open == "0") {
                that.setData({
                  service: false
                });
              }
            }
          }


          if (!app._isTextEmpty(res.data.member.yz_member)) {
            that.data.custom_value = res.data.member.yz_member.custom_value;
            that.getMemberCustom(
              that.data.custom_value,
              res.data.member.yz_member.validity,
              res.data.setting.custom
            ); //获取自定义数据
          }
          that._getEnablePlugin(res.data.plugins);
          that._getStroeWithdraw(res.data.plugins.is_open);
          that._getExtension(res.data.relation);
          that._getMemberGrade(res.data.setting.level);
          that.setData({
            show_member_id: res.data.setting.show_member_id,
            designerReadly: true,
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1500,
          });
        }
        that.setData({
          firstshow: true,
        });
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  handleContact(e){
    let _url = e.currentTarget.dataset.url;
    if(_url){
      wx.navigateTo({
        url: _url,
        fail:function(err){
          app.tips('客服路径错误');
        }
      });
    }
  },
  //获取自定义数据 validity会员等级时间限制
  getMemberCustom(value, validity, data) {
    // let that = this;
    // if (data.is_custom == "1" && !app._isTextEmpty(value)) {
    //   that.setData({
    //     custom_title: data.custom_title,
    //   });
    //   that.data.is_custom = true;
    // } else {
    //   that.data.is_custom = false;
    // }
    //处理会员等级时间限制
    if (data.is_validity && data.term == 1) {
      if (validity) {
        this.setData({
          validity_value: validity
        });
      }
    }
  },
  getPoster() {
    let that = this;
    let urlStr = app.getNetAddresss("member.poster");
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            poster: res.data.image_url,
            dataIs: "hook",
            isshow: true,
          });
          if (that.data.poster && that.data.timer) {
            wx.hideLoading({});
            clearInterval(that.data.timer);
          }
          // wx.hideTabBar({})
        } else {
          if (this.data.timer) {
            clearInterval(that.data.timer);
          }
          wx.hideLoading({});
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1500,
          });
        }
      },
      fail: function (res) {
        if (this.data.timer) {
          clearInterval(this.data.timer);
        }
        wx.hideLoading();
      },
    });
  },
  getTemp() {
    var that = this;
    try {
      var showinfo = wx.getStorageSync("yz_basic_info");
      if (!showinfo.home) {
        var urlStr = app.getNetAddresss("home-page.wxapp");
        urlStr += '&basic_info=1';
        app._getNetWork({
          showToastIn: false,
          url: urlStr,
          success: (res) => {
            var resdata = res.data;
            if (res.result == 1) {
              that.setData({
                footshow: true,
              });

              try {
                this.setData({
                  member_agent: resdata.basic_info.lang.agent && resdata.basic_info.lang.agent.agent ?
                    resdata.basic_info.lang.agent.agent : "客户",
                  PlatformAgreement: resdata.basic_info.home.register_setting.new_agreement ? resdata.basic_info.home.register_setting.new_agreement.replace(/<img/g, '<img style="width:100%;display:flex;"') : '',
                  agreement_name: app._isTextEmpty(resdata.basic_info.home.register_setting.agreement_name) ? this.data.agreement_name : resdata.basic_info.home.register_setting.agreement_name,
                });
              } catch (error) {
                console.log(error);
              }

            }
          },
          fail: (res) => {},
        });
      } else {
        that.setData({
          footshow: true,
          member_agent: showinfo.lang.agent && showinfo.lang.agent.agent ?
            showinfo.lang.agent.agent : "客户",
        });

      }
    } catch (e) {
      // Do something when catch error
    }
  },
  //自定义提现收入语言
  // customizeIncome() {
  //   try {
  //     var value = wx.getStorageSync("mailLanguage");
  //     if (value) {
  //       let mailLanguage = JSON.parse(value);
  //       // Do something with return value
  //       this.setData({
  //         name_of_withdrawal: mailLanguage.income.name_of_withdrawal,
  //       });
  //     }
  //   } catch (e) {
  //     // Do something when catch error
  //   }
  // },
  newTemplate(data) {
    let that = this;
    that.setData({
      designer: data.data,
      isDecorate: false,
    });
    that.data.designer.forEach((item, index, key) => {
      if (item.temp === "showdiyform") {
        that.showDiy.push(item);
        that.setData({
          showDiy: that.data.showDiy,
        });
      }
    });
    for (let i in that.data.designer) {
      that.setData({
        ["designer[" + i + "].temp"]: "show" + that.data.designer[i].temp,
      });
      if (
        that.data.designer[i].temp === "showlocation" ||
        that.data.designer[i].temp === "showstore"
      ) {
        that.setData({
          isLocation: true,
        });
      }
    }
    that.setData({
      designerStatus: data.status,
    });
    that.data.isMCreated = 1;
  },
  firstlogin() {
    let firstlogin = false;
    try {
      var value = wx.getStorageSync("wx_token");
      if (value) {
        // Do something with return value
        this.setData({
          loginshow: false,
        });
        firstlogin = false;
      } else {
        // console.log('没登陆')
        this.setData({
          loginshow: true,
        });
        firstlogin = true;
      }
    } catch (e) {
      // Do something when catch error
    }
    return firstlogin;
  },
  gotologin() {
    app.seyzredirect();
    wx.navigateTo({
      url: "/pages/login/login",
    });
  },
  /*************** 用户登录 START ***************************/
  getUserProfileTap() {
    let that = this;
    that.setData({
      is_show_user_info_edit_popup: true,
      lsgow: false
    });
   /* wx.getUserProfile({
      desc: '获取用户信息',
      success: function (_info) {
        that.setData({
          user_info:{
            'nickName': _info.userInfo.nickName,
            'avatarUrl': _info.userInfo.avatarUrl,
            'gender': _info.userInfo.gender
          },
          is_show_user_info_edit_popup: true
        });
        console.log('===== 获取用户信息 ======',that.user_info);
        // that.loginbtn(info);
      }
    });*/
  },
  loginbtn(_info) {
    if (this.data.logintap) return;
    this.setData({
      logintap: true
    });
    var that = this;
    console.log("=======  登录中...   ===============");
    wx.login({
      success: function (_json) {
        console.log("=========== login登录成功，获取用户info ==============",_json);
        if (_json.code) {
          // 请求登录接口
          wx.request({
            url: app.getNetAddresss("member.login.index"),
            header: {
              'Content-Type': 'application/json',
              'Accept': 'application/json',
            },
            data: {
              code: _json.code,
              info: _info,
              ver: '2'
            },
            success: function (res) {
              var _data = res.data;
              console.log("登录接口", res);
              setTimeout(() => {
                that.setData({
                  logintap: false
                });
              }, 1000);
              if (_data.result == 1) {
                // 存储key
                if (_data.msg.session) {
                  wx.setStorageSync('session', _data.msg.session);
                }
                // wx.setStorage({
                // 	key: "session",
                // 	data: _data.msg.session
                // })
                wx.setStorage({
                  key: "openid",
                  data: _data.data.openid
                });
                if (_data.msg.wx_token) {
                  wx.setStorageSync('wx_token', _data.msg.wx_token);
                }
                // wx.setStorage({
                // 	key: "wx_token",
                // 	data: _data.msg.wx_token
                // })
                if (_info) {
                  wx.setStorageSync('userInfo', _info);
                }
                //that.globalData.uid = _data.msg.uid;
                wx.setStorage({
                  key: "yz_uid",
                  data: _data.msg.uid
                });

                if( _data.data.is_first_time_bind){
                  // 首次授权登录自动绑定手机号
                  that.setData({
                    showAutoBindPhone: true
                  });
                }else{
                  that.getInvite();
                }
                wx.removeStorageSync("new_decorate"); //登录之后清除首页缓存数据重新请求
              } else {
                wx.showModal({
                  title: '提示',
                  content: _data.msg,
                  success(res) {
                    console.log(res);
                  }
                });
                // wx.showToast({
                // 	title: _data.msg,
                // 	icon: 'loading',
                // 	duration: 2000,
                // 	mask: true,
                // })
                console.log("第三方登录数据错误" + res.errMsg);
              }
            },
            fail: function (res) {
              that.setData({
                logintap: false
              });
              console.log("第三方登录失败session、wx_token获取失败" + res.errMsg);
            }
          });
        } else {
          that.setData({
            logintap: false
          });
          console.log("获取用户登录态失败！" + res.errMsg);
        }
      },
      fail: function (res) {
        console.log("登录失败，请求被拒绝！获取用户登录态失败！" + res);
      },
    });
  },

  /*old_getUserProfileTap(e) {
    let that = this;
    if(this.data.canIUseGetUserProfileTap) return; 
    this.setData({
      canIUseGetUserProfileTap:true
    });





    console.log('====== getUserProfileTap 详细信息 =======',e.detail);



    if (this.data.canIUseGetUserProfile) {
      wx.getUserProfile({
        desc: '获取用户信息',
        success: function (_info) {
          let info = {
            'nickName': _info.userInfo.nickName,
            'avatarUrl': _info.userInfo.avatarUrl,
            'gender': _info.userInfo.gender
          };
          that.loginbtn(info);
        },
        fail:function(){
          that.setData({
            canIUseGetUserProfileTap:false
          });
        }
      });
    } else {
      let _info = e.detail;
      let info = {
        'nickName': _info.userInfo.nickName,
        'avatarUrl': _info.userInfo.avatarUrl,
        'gender': _info.userInfo.gender
      };
      that.loginbtn(info);
    }

  },
  old_loginbtn(_info) {
    console.log('====== 用户信息 =======',_info);

    if (this.data.logintap) {
      // 正在请求 return
      return;
    }
    this.setData({
      logintap: true
    });
    var that = this;
    // var _session;
    // var _wx_token;
    console.log("登录中...");
    wx.login({
      success: function (_json) {
        console.log("login登录成功，获取用户info");
        if (_json.code) {
          // 请求登录接口
          wx.request({
            url: app.getNetAddresss("member.login.index"),
            header: {
              'Content-Type': 'application/json',
              'Accept': 'application/json',
            },
            data: {
              code: _json.code,
              info: _info,
              ver: '2'
            },
            success: function (res) {
              var _data = res.data;
              console.log("登录接口", res);
              setTimeout(() => {
                that.setData({
                  logintap: false
                });
              }, 1000);
              if (_data.result == 1) {
                // 存储key
                if (_data.data.user_info) wx.setStorageSync("nickname", _data.data.user_info.nickname);
                if (_data.msg.session) wx.setStorageSync('session', _data.msg.session);
                wx.setStorage({
                  key: "openid",
                  data: _data.data.openid
                });
                if (_data.msg.wx_token) wx.setStorageSync('wx_token', _data.msg.wx_token);
                if (_info) wx.setStorageSync('userInfo', _info);
                wx.setStorage({
                  key: "yz_uid",
                  data: _data.msg.uid
                });
                if( _data.data.is_first_time_bind){
                  // 首次授权登录自动绑定手机号
                  that.setData({
                    showAutoBindPhone: true
                  });
                }else{
                  that.getInvite();
                }
                wx.removeStorageSync("new_decorate"); //登录之后清除首页缓存数据重新请求
              } else {
                wx.showModal({
                  title: '提示',
                  content: _data.msg,
                  success(res) {
                    console.log(res);
                  }
                });
                // wx.showToast({
                // 	title: _data.msg,
                // 	icon: 'loading',
                // 	duration: 2000,
                // 	mask: true,
                // })
                console.log("第三方登录数据错误" + res.errMsg);
              }
            },
            fail: function (res) {
              that.setData({
                logintap: false,
                canIUseGetUserProfileTap:false
              });
              console.log("第三方登录失败session、wx_token获取失败" , res);
            }
          });
        } else {
          that.setData({
            logintap: false,
            canIUseGetUserProfileTap:false
          });
          console.log("获取用户登录态失败！" + res.errMsg);
        }
      },
      fail: function (res) {
        console.log("登录失败，请求被拒绝！获取用户登录态失败！" + res);
      },
    });
  },*/

  onChooseAvatar(e){
    const { avatarUrl } = e.detail
    let that = this;
    let urlStr = app.getNetAddresss("upload.uploadPic");
    wx.uploadFile({
      url: urlStr,
      filePath: avatarUrl,
      name: 'file',
      formData: null,
      success(resdata) {
        var res = JSON.parse(resdata.data);
        console.log(res.data.img_url);
        that.setData({
          avatar_image:res.data.img_url,
          'user_info.avatarUrl': res.data.img_url
        })
      }
    });
  },
  nicknameblur(e){
    let val = e.detail.value;
    console.log(e)
    this.setData({
      nickname: val,
      'user_info.nickName': val
    });
  },
  closeNickAvatar(){
    this.setData({
      is_show_user_info_edit_popup: false
    });
  },
  updateInfo() {
    let that = this;
    // 判断是否存在信息
    if(!that.data.user_info.avatarUrl){
      wx.showModal({
        title: "提示",
        content: '头像必须填写!',
        success(res) {},
      });
      return false;
    }
    // 用户信息存储
    that.setData({
      is_show_user_info_edit_popup: false
    },function(){
      that.loginbtn(that.data.user_info);
    });



  },
  /*************** 用户登录 END ***************************/


  //是否开启邀请页面
  getInvite() {
    let urlStr = app.getNetAddresss("member.member.isValidatePage");
    app._getNetWork({
      url: urlStr,
      data: {},
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          let data = res.data;
          try {
            this.checktoInvite(data, 'member');
          } catch (e) {
            wx.reLaunch({
              url: "/packageG/index/index",
            });
          }
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  gomember() {
    wx.reLaunch({
      url: "/packageG/member_v2/member_v2",
    });
  },
  turnTo() {
    if (this.data.advertising.is_minapp == 2) {
      if (this.data.advertising.minapp_sid) {
        if (this.data.advertising.minapp_link2) {
          try {
            wx.navigateToMiniProgram({
              appId: this.data.advertising.minapp_sid,
              path: this.data.advertising.minapp_link2,
              extraData: {},
              envVersion: "release",
              success(res) {
                // 打开成功
              },
              fail(res) {
                wx.showToast({
                  title: "小程序跳转失败",
                  icon: "none",
                  duration: 2000,
                });
              },
            });
          } catch (e) {
            wx.showToast({
              title: "小程序跳转失败",
              icon: "none",
              duration: 2000,
            });
          }
        } else {
          wx.showToast({
            title: "请设置跳转小程序后的跳转链接",
            icon: "none",
            duration: 2000,
          });
        }
      } else {
        wx.showToast({
          title: "请设置小程序所需跳转appId",
          icon: "none",
          duration: 2000,
        });
      }
    } else {
      let url = this.data.advertising.minapp_link;
      try {
        wx.navigateTo({
          url: url,
        });
      } catch (e) {
        wx.showToast({
          title: "链接设置错误",
          icon: "none",
          duration: 2000,
        });
      }
    }
  },

  toOrderList(e) {
    let item = e.currentTarget.dataset.item;
    let order_key = e.currentTarget.dataset.name;
    if ((order_key !== 'hotel_order') && item.status === 11) {
      this.goaftersaleslist();
      return;
    }
    if (order_key === 'order') {
      wx.navigateTo({
        url: "/packageA/member/myOrder_v2/myOrder_v2?status=" + (Number(item.status) + 1),
      });
    } else if (order_key === 'hotel_order') {
      if (item.status === 11) {
        wx.navigateTo({
          url: "/packageA/member/myOrder_v2/myOrder_v2?status=" + 5 + "&orderType=hotel",
        });
      } else {
        wx.navigateTo({
          url: "/packageA/member/myOrder_v2/myOrder_v2?status=" + (Number(item.status) + 1) + "&orderType=hotel",
        });
      }
    } else if (order_key === 'fight_groups_order') {
      wx.navigateTo({
        url: "/packageA/member/myOrder_v2/myOrder_v2?status=" + (Number(item.status) + 2) + "&orderType=groups",
      });
    } else if (order_key === 'snatch_regiment_order') {
      wx.navigateTo({
        url: "/packageA/member/myOrder_v2/myOrder_v2?status=" + (Number(item.status) + 1) + "&orderType=grabGroup",
      });
    } else if (order_key === 'lease_order') {
      wx.navigateTo({
        url: "/packageA/member/myOrder_v2/myOrder_v2?status=" + (Number(item.status) + 1) + "&orderType=lease_toy",
      });
    } else if (order_key === 'live_install_work_order') {
      // 上门安装师傅
      if (item.status === -1) {
        wx.navigateTo({
          url: "/packageH/installationSever/installationSeverHome/installationSeverHome?status=" + 1,
        });
      } else {
        wx.navigateTo({
          url: "/packageH/installationSever/installationSeverHome/installationSeverHome?status=" + item.status,
        });
      }
    } else if (order_key === 'live_install_order') {
      if (item.status === 3) {
        wx.navigateTo({
          url: "/packageH/installationSever/installationSeverMemberHome/installationSeverMemberHome?status=" + 5,
        });
      } else {
        wx.navigateTo({
          url: "/packageH/installationSever/installationSeverMemberHome/installationSeverMemberHome?status=" + (Number(item.status) + 1),
        });
      }
    } else if (order_key === 'aggregation_cps_order') {
      if (item.status === 3) {
        wx.navigateTo({
          url: "/packageA/member/order/cpsCoupon/cpsCoupon",
        });
      } else {
        wx.navigateTo({
          url: "/packageA/member/order/cpsOrder/cpsOrder?status=" + item.status,
        });
      }
    } else if (order_key === 'group_work_order') {
      wx.navigateTo({
        url: "/packageA/member/myOrder_v2/myOrder_v2?status=" + (Number(item.status) + 1) + "&orderType=groupWork"
      });
    }
  },
  async handlePlugin(event) {
    let plugin_active = "";
    if (event.detail) {
      plugin_active = event.detail.name;
    } else if (event.name) {
      plugin_active = event.name;
    }

    this.setData({
      plugin_active: plugin_active
    });
    this.data.decorate_isLoadMore = true;

    if (this.data.store_alone_temp == 1) {
      // 门店独立模块
      this.getPlugins("plugin.store-alone-temp.frontend.member.nav-data", {
        page: 1,
        code: this.data.plugin_active
      }, this.data.plugin_active);
      return;
    }

    // if(this.data.plugin_active==='recommend_goods') {
    // 	this.getPlugins("member.member.plugin-data",{code: this.data.plugin_active,page: 1}, this.data.plugin_active);
    // }else
    if (this.data.plugin_active === 'limitBuy_goods') {
      if (!this.data.limitData.list) {
        this.getPlugins("member.member.plugin-data", {
          code: this.data.plugin_active,
          page: 1
        }, this.data.plugin_active);
      }
    } else if (this.data.plugin_active === 'fight-groups') {
      if (this.data.groupList.length <= 0) {
        this.getPlugins("plugin.fight-groups.frontend.controllers.fight-groups.index", {
          page: 1
        }, this.data.plugin_active);
      }
    } else if (this.data.plugin_active === 'article') {
      if (!this.data.articleData.list) {
        this.getPlugins("plugin.article.api.article.get-articles", {
          category_id: 0,
          pageSize: 12,
          page: 1
        }, this.data.plugin_active);
      }
    } else if (this.data.plugin_active === 'video-share') {
      if (!this.data.videoData.list) {
        this.getPlugins("plugin.video-share.frontend.video.getList", {
          page: 1
        }, this.data.plugin_active);
      }
    } else if (this.data.plugin_active === 'micro-communities') {
      if (!this.data.communityData.list) {
        this.getPlugins("plugin.micro-communities.api.index.getStick", {
          trick_new: 1,
          page: 1
        }, this.data.plugin_active);
      }
    } else if (this.data.plugin_active === 'room') {
      if (!this.data.liveData.list) {
        this.getPlugins("plugin.room.frontend.live-list.get-all-live-list", {
          page: 1
        }, this.data.plugin_active);
      }
    }
  },

  getPlugins(url, json, plugin_active) {
    let urlStr = app.getNetAddresss(url);
    app._getNetWork({
      url: urlStr,
      data: json,
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          if (plugin_active === 'recommend_goods') {
            this.setData({
              ["goodsData.list"]: res.data.data
            });
          } else if (plugin_active === 'limitBuy_goods') {
            this.setData({
              ["limitData.list"]: res.data.data,
            });
          } else if (plugin_active === 'fight-groups') {
            this.setData({
              groupList: this.data.groupList.concat(res.data.data),
              groupListPage: res.data.current_page,
              groupListTotalPage: res.data.last_page,
            });
            this.data.decorate_isLoadMore = true;
          } else if (plugin_active === 'article') {
            this.setData({
              ['articleData.list']: res.data.articles
            });
          } else if (plugin_active === 'video-share') {
            this.setData({
              ['videoData.list']: res.data.list
            });
          } else if (plugin_active === 'micro-communities') {
            this.setData({
              ['communityData.list']: res.data
            });
          } else if (plugin_active === 'room') {
            this.setData({
              ['liveData.list']: res.data
            });
          }
        }
      }
    });
  },

  getMorePluginData() {
    this.data.decorate_isLoadMore = false;
    let plugin_active = this.data.plugin_active;
    if (plugin_active === 'recommend_goods') {
      let recommendGoods = this.selectComponent("#recommend_goods");
      recommendGoods.loadMoreMemberData();
    } else if (plugin_active === 'limitBuy_goods') {
      let limitBuyGoods = this.selectComponent("#limitBuy_goods");
      limitBuyGoods.loadMoreMemberData();
    } else if (plugin_active === 'fight-groups') {
      if (this.data.groupListPage < this.data.groupListTotalPage) {
        this.data.groupListPage += 1;
        let group_url = "plugin.fight-groups.frontend.controllers.fight-groups.index";
        if (this.data.store_alone_temp == 1) {
          // 门店独立
          group_url = "plugin.store-alone-temp.frontend.member.nav-data";
        }
        this.getPlugins(group_url, {
          page: this.data.groupListPage,
          code: this.data.plugin_active
        }, plugin_active);
      }
    } else if (plugin_active === 'article') {
      let articleBox = this.selectComponent("#article_box");
      articleBox.getMoreData();
    } else if (plugin_active === 'video-share') {
      let videoShare = this.selectComponent("#video_share");
      videoShare.loadMoreMemberData();
    } else if (plugin_active === 'micro-communities') {
      let microCommunities = this.selectComponent("#micro_communities");
      microCommunities.getMoreData();
    } else if (plugin_active === 'store-cashier') {
      let storeCashier = this.selectComponent("#store_cashier");
      storeCashier.getMoreList();
    } else if (plugin_active === 'room') {
      this.data.decorate_isLoadMore = true;
    }
  },

  setLoadMore(event) {
    this.setData({
      decorate_isLoadMore: event.detail.isLoadMore
    });
  },

  openService() {
    this.setData({
      showPopup: true
    });
  },
  closeService() {
    this.setData({
      showPopup: false
    });
  },

  // 获取授权手机号 ============= start =============
  async getPhoneNumber(e) {
    let info = e.detail;
    if(info.errMsg == 'getPhoneNumber:ok') {
      await this.getPhoneM(info);
      let keys = await this.getSessionKey(info);
      let mobile = await this.getPhone_index(info, keys);
      this.data.AuthorizedPhone = mobile;
      await this.getPrepBind(mobile);
      await this.setBindPhone();
      this.getInvite();
    }else{
      this.getInvite();
    }
  },
  getPhoneM() {
    return new Promise((resolve,reject) => {
      wx.checkSession({
        success: (res) => {
          resolve();
        },
        fail:err => {
          reject(err);
        }
      });
    });
  },
  getSessionKey() {
    let key = wx.getStorageSync('session');
    console.log(key, '缓存的session');
    let urlStr = app.getNetAddresss('member.mini-decrypt.getSessionKey');
    return new Promise((resolve,reject) => {
      app._postNetWork({
        url: urlStr,
        data: {
          session_key_id: key,
          not_validate_page: '0'
        },
        showToastIn: false,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            console.log(res, '获取session_key');
            if (res.result == 1) {
              let keys = res.data.session_key_data.session_key;
              resolve(keys);
            }
          } else {
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
            reject();
          }
        },
        fail: function (res) {
          reject(res);
        }
      });
    });
  },
  getPhone_index(info, keys) {
    wx.showLoading({
      title: '加载中',
    });
    let arr = {
      info: info,
      session_key: keys
    };
    let urlStr = app.getNetAddresss('member.mini-decrypt.index');
    return new Promise((resolve,reject) => {
      app._postNetWork({
        url: urlStr,
        showToastIn: false,
        data: {
          para_arr: arr,
          not_validate_page: '0'
        },
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            resolve(res.data.purePhoneNumber);
          } else {
            wx.hideLoading({
              success: (res) => { },
            });
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
            reject();
          }
        },
        fail: function (res) {
          reject(res);
        }
      });
    });
  },
  setBindPhone(){
    let urlStr = app.getNetAddresss('member.member.bindMobile');
    return new Promise((resolve,reject) => {
      app._postNetWork({
        url: urlStr,
        data: {
          mobile: this.data.AuthorizedPhone
        },
        success: function (resdata) {
          var res = resdata.data;
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
          resolve();
        },
        fail: function (res) {
          reject(res);
        }
      });
    });
  },
  // 获取授权手机号 ============= end =============
  closeChangeId() {
    this.setData({
      showChangeID: false
    });
  },
  //先验证是否导致会员id变更
  getPrepBind(mobile) {
    let urlStr = app.getNetAddresss("member.member.prepBind");
    return new Promise((resolve,reject) => {
      app._postNetWork({
        url: urlStr,
        showToastIn: false,
        data: {
          mobile: mobile
        },
        validateBol: 2,
        success: (resdata)=> {
          var res = resdata.data;
          if (res.result == 1) {
            if (res.data.is_show) {
              // 显示 导致会员id变更 弹窗
              this.setData({
                showChangeID: true,
                changidInfo: {
                  uid: res.data.uid,
                  change_uid: res.data.change_uid
                }
              });
            } else {
              resolve();
            }
          } else {
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
            reject(res);
          }
        },
        fail: function (res) {
          reject(res);
        }
      });
    });
  },

});