var t = getApp(),
  a = t.request,
  o = t.globalData.setting,
  os = o,
  i = require("../../../utils/util.js"),
  ut = i,
  s = require("../../../utils/common.js"),
  w = require("../../../utils/wxParse/wxParse.js"),
  t_pay = require("../../../utils/pay2.js");
var regeneratorRuntime = require('../../../utils/runtime.js');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    currentId: 0,
    url: o.imghost,
    screenWidth: 0,
    screenheight: 0,
    canvasHidden: true,
    shareImgPath: null,
    is_plusCard: "", //卡的列表
    imagePath: "",
    is_pulscardname: "", //plus会员的名字
    is_card: 0, //用于判断是否是续费页和购买页面 0不是PLUS会员
    content: "", //等级卡规则
    is_card_rule: "", //等级卡规则判断用
    is_show: 0, //页面要加载完才能显示
    open_yq: 0, //显示打开邀请码的弹窗
    by_index: null, //购买卡的下班

    isyaoqingma: 0, //是否显示邀请码
    is_salesman: 0, //是否显示营业员
    is_must_staff_yqma: 0, //是否必填

    inp_recommon: null, //输入的邀请码
    inp_serviceman: null, //输入的营业员
    is_fengxiang: 0, //是不是分享过来的
    def_recommon: null, //分享人的手机号
    def_serviceman: null, //分享人的营业员
    fir_leader: 0, //分享人的ID	
    staffNo_arr: [], //多个营业员
    focus:false, 
    is_select: false, //是否选择营业员过
    is_buy_card_id:"",//是否是链接直接过来购买的卡号id

    is_fir_open:0, //防止多次打开
    check_py_val:0

  },
  swiperChange: function (e) {
    var currentId = e.detail.current;
    this.setData({
      currentId: currentId
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    //定义第一次进入
    this.data.fir_in=1;

    var that = this,th = that;
    var store_id = getApp().globalData.setting.stoid;
    //获取用户设备信息，屏幕宽度
    wx.getSystemInfo({
      success: res => {
        that.setData({
          screenWidth: res.screenWidth
        })
      }
    })


    //二维码的带入,  生成海报 和 后台plus邀请码
    var fir_leader = options.scene;
    if (fir_leader){

      that.setData({
        fir_leader: fir_leader
      })

      //--  user_id代过来免登录 --
      getApp().globalData.first_leader = fir_leader;
      //调用接口判断是不是会员
      getApp().request.promiseGet("/api/weshop/shoppingGuide/get/" + os.stoid + "/" + fir_leader, {}).then(res => {
        if (res.data.code == 0) {
          getApp().globalData.guide_id = res.data.data.id;
          getApp().globalData.guide_pick_id= res.data.data.pickup_id
        }
      })
    }

    //判断是否是链接直接扫码购买
     let is_buy_card_id = options.is_buy_card_id
     if(is_buy_card_id){
       that.setData({
         is_buy_card_id
       })
     }


    //-----------商家配置信息----- 等级卡规则，是否又开邀请码，营业员------------
    getApp().request.get("/api/weshop/storeconfig/get/" + store_id, {
      success: function (res) {
        var is_cardrule = res.data.data.cardrules;
        var switch_list = res.data.data.switch_list;
        var swi_arr = JSON.parse(switch_list);

        w.wxParse("content", "html", ut.format_content(is_cardrule), that, 6);
        that.setData({
          is_card_rule: is_cardrule,
          isyaoqingma: parseInt(swi_arr.isyaoqingma),
          is_salesman: parseInt(swi_arr.is_staffno),
          is_must_staff_yqma: parseInt(swi_arr.is_must_staff_yqma),
          plus_bg_color: swi_arr.plus_bg_color,
        });
      }
    });

    //--先判断会员状态--
    var user_info = getApp().globalData.userInfo;
    if (user_info == null || user_info.mobile == undefined || user_info.mobile == "" || user_info.mobile == null) {
      wx.navigateTo({
        url: '/packageE/pages/togoin/togoin?first_leader=' + fir_leader,
      })
      return false;
    }

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var user_info = getApp().globalData.userInfo;
    if (!user_info) return false;

    var th = this,that = th;

    //判断是不是第一次进入
    if(this.data.fir_in){
       this.data.fir_in=0;
    }else{
        //富友插件支付
        ut.fy_back('',0);
        t_pay.set_fir();
        //-- 通联的第三方支付的返回优化 --
        ut.is_pay_ok(th.data.ok_order_sn,"func","func",function (){

            if(!th.data.ok_order_sn) return false;
            var ck_url="/api/weshop/recharge/get/"+os.stoid+"/"+th.data.ok_order_sn;
            getApp().request.promiseGet(ck_url,{}).then(res=>{

               if(res.data.code==0 && res.data.data){
                    var item=res.data.data;
                    if(item.pay_status==1){
                      //支付支付，返回首页
                      th.success()

                    }else{
                        //支付支付，返回首页
                        getApp().my_warnning('支付失败', 0, th);
                        th.setData({
                          is_select:0,
                          focus:true,
                        })
                    }
               }
            })
          }, //成功的回调
               function (){
                 th.success();
          },//失败的回调
           function (){
             th.setData({
               is_select:0,
               focus:true,
             })

        });
    }

    this.setData({
       is_select:0,
       focus:true,
    })

    var  app_d = getApp().globalData;
    var store_id = os.stoid;
    var fir_leader = this.data.fir_leader;

    if (fir_leader != null && fir_leader != undefined && fir_leader != "") {
      var r_url = "/api/weshop/plus/vip/mem/list?storeId=" + store_id + "&userId=" + fir_leader
      getApp().request.get(r_url, {
        success: function (res) {
          var is_ok = 1;
          if (res.data.code == -1) {
            getApp().my_warnning("未找到分享会员", 0, that);
            is_ok = 0;
            that.back_user();
          }
          var user_information = res.data.data[0];
          if (user_information['GradeCardID'] == null || user_information['GradeCardID'] == "" || user_information['GradeCardID'] == undefined) {
            getApp().my_warnning("分享会员不是plus会员", 0, that);
            is_ok = 0;
            that.back_user();
          }
          //--获取当前的时间--
          var now = ut.gettimestamp();
          if (user_information['ExpiryDate']) {
            var str = user_information['ExpiryDate'].replace(/-/g, '/');
            var end = new Date(str);
            end = Date.parse(end) / 1000;
            if (end < now) {
              getApp().my_warnning("分享plus会员已经过期", 0, that);
              is_ok = 0;
              that.back_user();
            }
          } else {
            getApp().my_warnning("分享plus会员已经过期", 0, that);
            is_ok = 0;
            that.back_user();
          }
          if (is_ok == 1) {
            //--保存或者更新会员信息--
            that.setData({
              def_recommon: user_information.MobileTel,
              def_serviceman: user_information.StaffNo,
              is_fengxiang: 1
            })
            th.save_th_plus_user();
          }
        }
      });
    } else {
      th.get_user_plus();
    }

    getApp().request.get("/api/weshop/users/get/" + os.stoid + "/" + app_d.user_id, {
      success: function (e) {
          var userInfo = e.data.data;
          if (userInfo && userInfo['card_field']) {
              var u_url = "/packageE/pages/user/cardinfo/cardinfo";
              wx.reLaunch({
                url: u_url
              })
          }else{
            th.getPlusCardType();
          }
      },
    });


  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var goods_list = this.selectComponent("#goods_list"); //组件的id
    goods_list.get_list();
  },

  //---  获取卡类列表 ---
  getPlusCardType: function (e) {
    var storid = o.stoid;
    var th = this;
    getApp().request.promiseGet("/api/weshop/plus/vip/mem/bership/list?" + "storeId=" + storid, {}).then(res => {
      var plusCard = res.data.data;
      var arr = [1219, 2089, 3031];
      var new_arr = new Array();
      var parr = [];
      for (var i = 0; i < plusCard.length; i++) {
        //plusCard[i].free=arr[i];
        if (plusCard[i].IsStopBuy) {
          continue;
        }
        if (plusCard[i].CardImg == "") plusCard[i].CardImg = th.data.url + "/miniapp/images/plus/bg" + (i + 1) + ".jpg?v=1";
        var item = {
          "fee": plusCard[i].CardFee,
          'index': i
        }
        new_arr.push(item);
        parr.push(plusCard[i]);
      }

      //看是不是还有卡项是可以购买的
      if (new_arr && new_arr.length > 0) {
        //根據距離遠近排序，越近在前面，升序
        new_arr.sort(function (a, b) {
          if (a.fee < b.fee) {
            return -1;
          } else if (a.fee == b.fee) {
            return 0;
          } else {
            return 1;
          }
        });

        //里面和外面要显示统一
        switch (new_arr.length) {
          case 1:
            arr = [3031];
            break;
          case 2:
            arr = [2089, 3031];
            break;
          case 3:
            arr = [1219, 2089, 3031];
            break;
        }

        //---给数组添加立省多少钱---
        for (i = 0; i < parr.length; i++) {
          //判断是否停用
          for (var j = 0; j < new_arr.length; j++) {
            if (i == new_arr[j].index) {
              parr[i].free = arr[j];
              break;
            }
          }
        }
        th.setData({
          is_plusCard: parr,
          is_show: 1
        })
        if(th.data.is_buy_card_id && !th.data.is_fir_open){
          let i = parr.findIndex(item=>item.CardId==th.data.is_buy_card_id)
          if(i>-1){
            // th.setData({
            //   by_index:i
            // })
            // th.buy_card()
            let e={
              currentTarget:{
                dataset:{ind:i}
              }
            }

            setTimeout(function (){
              th.data.is_fir_open=1;  //保证不多次打开
              th.Opening(e)
            },1000)


          }
        }
      } else {
        th.setData({
          is_show: 1
        });
        wx.showToast({
          title: "暂无可购买的等级卡项",
          icon: 'none',
          duration: 4000
        })

      }
      setTimeout(function () {
        var goods_list = th.selectComponent("#goods_list"); //组件的id
        goods_list.init();
        goods_list.get_list();
      }, 1000)

    })
  },

  //--开通会员---接受前端index，弹起窗口---
  Opening: function (e) {
    var th = this;
    th.data.by_index = e.currentTarget.dataset.ind;

    if (th.data.is_fengxiang) {
      th.buy_card();
    } else {
      //--如果后台都没有勾邀请码，营业员，立即购买--
      if (!th.data.isyaoqingma && !th.data.is_salesman) {
        th.buy_card();
        return false;
      }
      th.setData({
        open_yq: 1
      })
    }
  },

  //选择营业员
  select_serviceman(e) {
    let StaffNo = e.currentTarget.dataset.staffno;
    let {req_data,req} = this.data;
    if (StaffNo && StaffNo !== "") {
      req_data.staffNo = StaffNo;
      req.serviceman = StaffNo;
    };
    this.setData({
      is_select: 1,
      staffNo_arr:[],
    })
    this.check_serviceman(req_data,req)
  },
  //--绑定邀请码的输入--
  b_input: function (e) {
    var value = e.detail.value.trim();
    // let { isyaoqingma, is_salesman }=this.data;
    var name = e.currentTarget.dataset.name;
    // if((name=="isyaoqingma" && isyaoqingma) || (name=="is_salesman" && is_salesman) ){
    //   if(!value){
    //     wx.showToast({
    //       title: '不能为空',
    //     })
    //     return false;
    //   }
    // }
    var ob = {};
    ob[name] = value;
    this.setData(ob);
  },
  //--立即购买卡--
  buy_card: async function () {
    console.log(11111);
    var th = this;
    var is_card = 0;
    //--商家是不是有等级卡功能，开通的人数是不是够用，开通是时间是不是到期--
    await getApp().request.promiseGet("/api/weshop/plus/plus/card/register", {
      data: {
        storeId: os.stoid
      }
    }).then(res => {
      if (res.data.code == 0) is_card = 1;
    })
    if (is_card == 0) {
      getApp().my_warnning("请联系商家升级plus功能", 0, th);
      return false;
    }

    var item = th.data.is_plusCard[th.data.by_index];
    var req = {};
    req.cardId = item.CardId;
    req.rechargeType = 3;
    //如果不是你导购，也不是等级会员分享
    if (th.data.is_fengxiang == 1) {
      if (th.data.def_recommon) req.recommon = th.data.def_recommon
      if (th.data.def_serviceman) req.serviceman = th.data.def_serviceman
    } else {

      //有显示弹出框，才要求要显示用户协议
      if(!this.data.check_py_val  && (th.data.isyaoqingma || th.data.is_salesman) ){
        ut.m_toast('请先同意PLUS会员用户协议')
        return false;
      }

      //---后台要求要输入邀请码---
      if (th.data.isyaoqingma) {
        if (!th.data.inp_recommon && th.data.is_must_staff_yqma) {
          getApp().my_warnning("请输入邀请码", 0, th);
          return false;
        }

        //--邀请人不能是自己的手机号--
        if (th.data.inp_recommon == getApp().globalData.userInfo.mobile) {
          getApp().my_warnning("邀请人不能填自已", 0, th);
          return false;
        }
        if(th.data.inp_recommon) req.recommon = th.data.inp_recommon
      }
      //--后台要求要输入营业员--
      if (th.data.is_salesman) {
        if (!th.data.inp_serviceman && th.data.is_must_staff_yqma) {
          getApp().my_warnning("请输入营业员", 0, th);
          th.setData({
            focus:true
          })
          return false;
        }
        if(th.data.inp_serviceman) req.serviceman = th.data.inp_serviceman
      }
    }
    req.storeId = os.stoid;
    req.userId = getApp().globalData.user_id;



    //--如果有邀请码，和营业员的情况下--
    if (req.recommon || req.serviceman) {

      var req_data = {
        storeId: os.stoid,
        userId: req.userId
      };
      if (req.recommon) req_data.inviteCode = req.recommon;
      if (req.serviceman) req_data.staffNo = req.serviceman;
      th.setData({
        req_data,
        req,
      })
      th.check_serviceman(req_data,req)
      // getApp().request.get("/api/weshop/plus/vip/mem/referee/code/check", {
      //   data: req_data,
      //   success: function (res) {
      //     if (res.data.code == 0) {
      //       if(res.data.data.length > 1 && !th.data.is_select){
      //         th.setData({
      //           staffNo_arr:res.data.data
      //         })
      //       }else{
      //         t_pay.pay(req, th.success, function () {
      //           getApp().my_warnning("支付失败", 0, th);
      //           th.setData({
      //             is_select:0,
      //           })
      //         });
      //       }
      //     } else {
      //       getApp().my_warnning(res.data.msg, 0, th);
      //       th.setData({
      //         is_select:0,
      //       })
      //     }
      //   }
      // })
    } else {
      t_pay.set_pay_url('/api/weshop/plus/create/plus/order');
      t_pay.pay(req, th.success, function (msg) {

        if( typeof msg === 'object' && msg !== null &&  msg.code==-2){
            wx.showModal({
              title: msg.msg,
              showCancel: !1,
              complete: function () {
                getApp().goto('/packageE/pages/user/cardinfo/cardinfo');
              }
            });
        }else{
            if(!msg) msg='支付失败';
            getApp().my_warnning(msg, 0, th);
        }

        th.setData({
          is_select:0,
          focus:true,
        })
      },th);
    } 
  },
  //返回会员页面
  OpeningClose: function () {
    this.setData({
      open_yq: 0,
      inp_serviceman:""
    });
  },
  dialog_close() {
    this.setData({
      staffNo_arr: [],
    });
  },
  check_serviceman(data,req) {
    let th = this;
    getApp().request.get("/api/weshop/plus/vip/mem/referee/code/check", {
      data,
      isShowLoading:true,
      success: function (res) {
        if (res.data.code == 0) {
          if (res.data.data.length > 1 && !th.data.is_select) {
            th.setData({
              staffNo_arr: res.data.data
            })
          }else{
            t_pay.set_pay_url('/api/weshop/plus/create/plus/order');
            t_pay.pay(req, th.success, function (msg) {
              if(!msg) msg="支付失败";
              getApp().my_warnning(msg, 0, th);
              th.setData({
                is_select:0,
                focus:true,
              })
            },th);
          }
        } else {
          getApp().my_warnning(res.data.msg, 0, th);
          th.setData({
            is_select:0,
            focus:true,
          })
        }
      }
    })
  },
  //返回会员中心
  back_user: function () {
    setTimeout(function () {
      wx.reLaunch({
        url: "/pages/user/index/index"
      });
    }, 1000)
  },

  //--支付成功，跳转到等级卡续费页面--
  success: function () {
    //调一次就不再调用了  
    if (getApp().globalData.is_card_back){
      th.setData({
        is_select:0,
        focus:true,
      })
      return false;

    }
    if (getApp().globalData.plus_buy_back) {
      //值在这里换
      getApp().globalData.is_card_back = 1;
      getApp().globalData.plus_buy_back = 0;
      //返回购物车购买
      wx.navigateBack({
        delta: 1,
      });
      return false;
    } else {
      var u_url = "/packageE/pages/user/cardinfo/cardinfo";
      wx.reLaunch({
        url: u_url
      })
    }
  },



  get_user_plus: async function () {
    var user_id = getApp().globalData.user_id;
    var fuser = null;
    var user_information = null;
    var store_id = os.stoid;
    var that = this;
    //--获取登记卡邀请信息--
    await getApp().request.promiseGet("/api/weshop/usersPlus/get/" + os.stoid + "/" + user_id, {
      1: 1
    }).then(res => {
      if (res.data.code == 0) {
        fuser = res.data.data;
      }
    })
    if (!fuser) return false;
    var r_url = "/api/weshop/plus/vip/mem/list?storeId=" + store_id + "&userId=" + fuser.plus_user_id;
    //--获取等级卡信息--
    await getApp().request.promiseGet(r_url, {
      1: 1
    }).then(res => {
      if (res.data.code == 0) {
        user_information = res.data.data[0];
      }
    })
    if (user_information) {
      var now = ut.gettimestamp();
      var is_ok = 1;
      if (user_information['ExpiryDate']) {
        var str = user_information['ExpiryDate'].replace(/-/g, '/');
        var end = new Date(str);
        end = Date.parse(end) / 1000;
        if (end < now) {
          is_ok = 0;
        }
      } else {
        is_ok = 0;
      }

      if (is_ok == 1) {
        var fir_leader = fuser.plus_user_id
        that.setData({
          def_recommon: user_information.MobileTel,
          def_serviceman: user_information.StaffNo,
          is_fengxiang: 1,
          fir_leader: fir_leader
        })
        //--先判断会员状态--
        var user_info = getApp().globalData.userInfo;
        if (user_info == null || user_info.mobile == undefined || user_info.mobile == "" || user_info.mobile == null) {
          wx.navigateTo({
            url: '/packageE/pages/togoin/togoin?first_leader=' + fir_leader,
          })
          return false;
        }
      }
    }
  },

  save_th_plus_user: async function () {
    var f_user_id = this.data.fir_leader;
    if (f_user_id) {
      var user_id = getApp().globalData.user_id;
      var user_plus = null;
      var now = ut.gettimestamp();
      //--获取登记卡邀请信息--
      await getApp().request.promiseGet("/api/weshop/usersPlus/get/" + os.stoid + "/" + user_id, {
        1: 1
      }).then(res => {
        if (res.data.code == 0) {
          user_plus = res.data.data;
        }
      })

      //--如果有值，要更新--
      if (!user_plus) {
        getApp().request.post("/api/weshop/usersPlus/save", {
          data: {
            store_id: os.stoid,
            user_id: user_id,
            plus_user_id: f_user_id,
            addtime: now
          },
          success: function (res) {}
        })
      } else {
        getApp().request.put("/api/weshop/usersPlus/update", {
          data: {
            store_id: os.stoid,
            user_id: user_id,
            plus_user_id: f_user_id,
            edittime: now
          },
          success: function (res) {}
        })
      }
    }
  },

  //用户协议的同意的优化
  handleCheckboxChange:function (){
    console.log('this.data.checkboxValue ==> ' , this.data.checkboxValue);
    this.setData({
      // 点击之后进行取反
      check_py_val : !this.data.check_py_val
    })
  },

  //显示协议的内容
  show_more_xy:function (){
      getApp().goto("/packageG/pages/plus_agreement/plus_agreement");
  }


})