const app = getApp();
var e = getApp(),
  a = e.globalData.setting,
  os = a,
  t = e.request,
  s = require("../../../../utils/common.js"),
  d = e.globalData;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    url: a.url, //接口网址
    iurl: a.imghost, //图片前缀网址
    interest_lables: [], //兴趣标签   
    check_label: [], //用户选中的标签集合
    user_label_val: "", //奖励多少
    user_label_type: "", //奖励类型（1积分，1成长值）
    is_modify: 0, //判断是第一次填写还是修改（0填写，1修改）
    isread: 0, //是否读取
    is_check: 0, //是否重复提交
    pageType:'',//页面来源标识，1 是注册时跳转过来的 
    label_required:'',//注册时标签是否必填
  },
  //点击选择兴趣标签把值放到已选中
  click_label: function(e) {
    var th = this;
    var index = e.currentTarget.dataset.index; //选择兴趣标签的下标
    var labels = th.data.interest_lables; //兴趣标签数组
    var check_label = th.data.check_label; //已选中的数组
    var labels_cid = th.data.interest_lables[index].check; //当前标签是否选中
    var labels_check = 'interest_lables[' + index + '].check'; //用于点击标签把点击状态赋值进去 
    if (labels_cid) {
      labels_cid = 0;
      for (var i = 0; i < check_label.length; i++) {
        if (labels[index].id == check_label[i].id) {
          check_label.splice(i, 1);
        }
      }
      th.setData({
        [labels_check]: labels_cid,
        check_label: check_label
      })
    } else {
      if (check_label.length > 9) {
        getApp().my_warnning("最多可选10个哦", 0, th);
      } else {
        var check_new = {
          lable: labels[index]
        };
        labels_cid = 1;
        check_label.push(labels[index]);
      }
      th.setData({
        [labels_check]: labels_cid,
        check_label: check_label
      })
    }

  },
  //获取配置信息
  get_config: function() {
    var th = this;
    getApp().getConfig2(function(ee) {
      var sms_conf = ee.switch_list;
      sms_conf = JSON.parse(sms_conf);
      var getuser_label_type = 1;
      var getuser_label_val = 0;
      let label_required=''
      if (sms_conf.user_label_type != undefined) {
        getuser_label_type = parseInt(sms_conf.user_label_type) + 1;
      }
      if (sms_conf.user_label_val != undefined) {
        getuser_label_val = sms_conf.user_label_val;
      }
    
      if (sms_conf.label_required==1) {
        label_required=1
      }


      th.setData({
        user_label_val: getuser_label_val,
        user_label_type: getuser_label_type,
        label_required:label_required
      })
    })
  },
  //页面跳转
  goto: function(e) {
    var th = this;
    wx.navigateBack({ //返回
      delta: 1
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log('标签页面对象-------');
    console.log(options);
    let pageType = options.pageType //页面来源标识，1 是注册时跳转过来的 
    if (pageType) {
      this.setData({
        pageType
      })
      // this.pageType=pageType
    }
    var th = this;
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2]; //上一个页面
    //直接调用上一个页面的setData()方法，把数据存到上一个页面中去
    try {
      prevPage.setData({
        is_zy: 1
      })
    } catch (error) {
      
    }

    if(options.is_reg){
       this.setData({is_reg:1})
    }

    th.query_nolabels();
    th.get_config();
  },
  //获取标签集合
  query_nolabels: function() {
    var th = this;
    var url = "/api/weshop/marketing/holiday/vip/interest/label/page";
    var interest_lables = th.data.interest_lables; //兴趣标签集合
    getApp().request.promiseGet(url, {
      data: {
        storeId: a.stoid,
        pageSize: 50,
        page: 1
      }
    }).then(res => {
      if (res.data.code == 0) {
        th.setData({
          interest_lables: res.data.data.pageData,
          isread: 1
        })
        if(!th.data.pageType){
          th.query_checklabels();
        }
      } else {
        getApp().my_warnning("系统繁忙,请稍后再试", 0, th);
        th.setData({
          isread: 1
        })
        return false;
      }
    })
  },
  //查找会员选择的兴趣标签
  query_checklabels: function() {
    var th = this;
    var url = "/api/weshop/marketing/holiday/vip/interest/label/get";
    var interest_lables = th.data.interest_lables; //兴趣标签
    getApp().request.promiseGet(url, {
      data: {
        userId: d.user_id,
        storeId: a.stoid
      }
    }).then(res => {
      if (res.data.code == 0) {
        var data = res.data.data;
        var arr = [];
        var VipLabelId = []; //通过id标签找到已选择的标签
        var dateList = data.VipLabelId.split(",");
        for (var i in dateList) {
          VipLabelId = VipLabelId.concat(dateList[i]);
        }
        if (VipLabelId.length > 0) {
          for (var i = 0; i < interest_lables.length; i++) {
            for (var ii = 0; ii < VipLabelId.length; ii++) {
              if (interest_lables[i].id == VipLabelId[ii]) {
                interest_lables[i].check = 1;
                arr.push(interest_lables[i]);
              }
            }
          }
        }
        //如何有之前有选择兴趣标签的话，再进来的话就是修改
        if (data.VipLabelId != '') {
          th.setData({
            is_modify: 1
          })
        }
        th.setData({
          check_label: arr,
          interest_lables: interest_lables
        })
      } else {
        getApp().my_warnning("系统繁忙，请稍后再试", 0, th);
        return false;
      }
    })
  },
  //更新会员兴趣标签
  update_label: function() {
    var th = this;
    var is_modify = th.data.is_modify; //是否是修改
    var check_label = th.data.check_label; //用户选择
    var user_label_val = th.data.user_label_val; //选择标签奖励多少
    var remark = "领取";
    var user_label_type = th.data.user_label_type; //赠送类型
    var is_check = th.data.is_check; //是否重复提交
    var i = 0;
    var vipLabel = ""; //选择的标签名称
    var vipLabelId = ""; //选择的标签id
    var arr = [];
    for (var i = 0; i < check_label.length; i++) {
      if (i < check_label.length - 1) {
        vipLabelId += check_label[i].id + ",";
        vipLabel += check_label[i].LabelName + ",";
        arr.push(check_label[i].LabelName);
      } else {
        vipLabelId += check_label[i].id;
        vipLabel += check_label[i].LabelName;
        arr.push(check_label[i].LabelName);
      }
    }
    if (is_modify) {
      user_label_type = 0;
      remark = "修改";
      user_label_val = 0;
    }
    if (is_check==1) {
      getApp().my_warnning("请勿重复提交", 0, th);
    }
    if (is_check == 0) {
      if (th.data.pageType) {
        if(th.data.label_required){
          if (check_label.length < 1) {
            getApp().my_warnning("必须完成兴趣标签选择", 0, th);
            return
          } 
        }
        wx.showLoading({
            title: "处理中.",
            mask: true
        })
        th.setData({
          is_check: 1
        })

        if(getApp().globalData.h5_openid){
          getApp().globalData.zc_dd.openid=getApp().globalData.h5_openid;
        }

        app.request.get("/api/weshop/users/thirdLogin", {
            data: getApp().globalData.zc_dd,
            success: function (e) {
                wx.hideLoading();

                e.data.code=-5;

                if (e.data.code == 0) {
                    app.globalData.user_id = e.data.data.user_id;
                } 
                else if(e.data.code==-3){
                  th.setData({loading: 0,is_check:0});
                  wx.showModal({
                    title: e.data.msg,
                    success: function (e) {
                      if(e.confirm){
                          getApp().globalData.zc_dd.isreplacemobile=1;
                         
                          th.update_label();
                      }
                    }
                  });
                  return false;
                } 
           
                else {
                    th.setData({loading: 0,is_check:0});
                    return app.my_warnning("授权登入失败！" + e.data.msg,0,th);
                }

                getApp().globalData.login_back = 1;
                wx.setStorageSync("userinfo", e.data.data);
                wx.setStorageSync("isAuth", !0), app.globalData.userInfo = e.data.data, app.globalData.userInfo.head_pic = s.getFullUrl(app.globalData.userInfo.head_pic);
                if (th.data.label_required && check_label.length>0) {                
                  getApp().request.put("/api/weshop/marketing/holiday/vip/interest/label/update", {
                    data: {
                      "storeId": a.stoid,
                      "userId":e.data.data.user_id,
                      "vipLabel": vipLabel,
                      "vipLabelId": vipLabelId,
                      "type": user_label_type,
                      "remark": remark,
                      "value": user_label_val,
                      "fromType": "REWARD"
                    },
                    success: function(res) {
                      if (res.data.code == 0) {
                        getApp().my_warnning("领取成功", 1, th);
                        setTimeout(function() {
                          // var pages = getCurrentPages();
                          // var prevPage = pages[pages.length - 2];
                          // prevPage.setData({
                          //   check_label: arr
                          // })
                          // th.goto();
                          // wx.reLaunch({
                          //   url: '/pages/user/index/index',
                          // })
                          //-- 看情况,是跳转等级卡，还是跳转到新人有礼 --
                          getApp().go_to_page(th.data.is_reg,function (){
                            wx.navigateBack({ delta: 1 })
                          })

                        }, 2000);
                      }

                    
                      else {
                        getApp().my_warnning("系统繁忙,请稍后再试", 0, th);
                        th.setData({
                          is_check: 0
                        })
                      }
                    }
                  })
                }else{
                  getApp().go_to_page(th.data.is_reg,function (){
                    // wx.navigateBack({ delta: 1 })
                    wx.reLaunch({
                      url: '/pages/user/index/index',
                    })
                  })

                }

            },
            failStatus: function (t) {
                wx.hideLoading();
                th.setData({loading: 0,is_check:0});
                return app.my_warnning("授权登入失败,请稍后再试!", 0, that);
            },
            fail: function (t) {
                wx.hideLoading();
                th.setData({loading: 0,is_check:0});
                return i.clearAuth(), i.alertLoginErrorAndGoHome(), !1;
            }
        });
      }else{
        if (check_label.length < 1) {
          getApp().my_warnning("完成兴趣标签才能" + remark + "哦~", 0, th);
          th.setData({
            is_check: 0
          })
        } else {
            th.setData({
              is_check: 1
            })
         
          var url = "/api/weshop/marketing/holiday/vip/interest/label/update"; //更新标签接口地址
          var nav_url = "/packageG/pages/user/userinfo/userinfo"; //领取成功之后跳转页面

          var my_confirm = th.selectComponent("#my_confirm"); //组件的id
          remark = "兴趣标签赠送";
            if (is_modify) {
    
              my_confirm.open_cancel(0);
              getApp().request.put(url, {
                data: {
                  "storeId": a.stoid,
                  "userId": d.user_id,
                  "vipLabel": vipLabel,
                  "vipLabelId": vipLabelId,
                  "type": user_label_type,
                  "remark": remark,
                  "value": user_label_val,
                  "fromType": "REWARD"
                },
                success: function(res) {
                  if (res.data.code == 0) {
                    getApp().my_warnning("修改成功", 1, th);
                    setTimeout(function() {
                      var pages = getCurrentPages();
                      var prevPage = pages[pages.length - 2]; //上一个页面
                      //直接调用上一个页面的setData()方法，把数据存到上一个页面中去
                      prevPage.setData({
                        check_label: arr
                      })
                      th.goto();
                    }, 2000);
                  } else {
                    getApp().my_warnning("系统繁忙,请稍后再试", 0, th);
                    th.setData({
                      is_check: 0
                    })
                  }
                }
              })
    
            } else {
    
              getApp().request.put(url, {
                data: {
                  "storeId": a.stoid,
                  "userId": d.user_id,
                  "vipLabel": vipLabel,
                  "vipLabelId": vipLabelId,
                  "type": user_label_type,
                  "remark": remark,
                  "value": user_label_val,
                  "fromType": "REWARD"
                },
                success: function(res) {
                  if (res.data.code == 0) {
                    getApp().my_warnning("领取成功", 1, th);
                    setTimeout(function() {
                      var pages = getCurrentPages();
                      var prevPage = pages[pages.length - 2]; //上一个页面
                      //直接调用上一个页面的setData()方法，把数据存到上一个页面中去
                      prevPage.setData({
                        check_label: arr
                      })
                      th.goto();
                    }, 2000);
                  } else {
                    getApp().my_warnning("系统繁忙,请稍后再试", 0, th);
                    th.setData({
                      is_check: 0
                    })
                  }
                }
              })
            }
          
        }
      }
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  //会员点击了跳过，就要注册
  goto_user(e){
    var th=this;
    if(this.data.is_check) return false;
    wx.showLoading({
      title: "处理中.",
      mask: true
    })

    this.setData({ is_check: 1 })

    if(getApp().globalData.h5_openid){
      getApp().globalData.zc_dd.openid=getApp().globalData.h5_openid;
    }

    app.request.get("/api/weshop/users/thirdLogin", {
      data: getApp().globalData.zc_dd,
      success: function (e) {
        wx.hideLoading();
        th.setData({loading: 0,is_check:0});

        e.data.code=-5;

        if (e.data.code == 0) {
          app.globalData.user_id = e.data.data.user_id;
        } 
        
        else if(e.data.code==-3){

          wx.showModal({
            title: e.data.msg,
            success: function (e) {
              if(e.confirm){
                getApp().globalData.zc_dd.isreplacemobile=1;

                th.goto_user();
              }
            }
          });
          return false;
        }
        
        else {
          return app.my_warnning("授权登入失败！" + e.data.msg,0,th);
        }
        getApp().globalData.login_back = 1;
        wx.setStorageSync("userinfo", e.data.data);
        wx.setStorageSync("isAuth", !0), app.globalData.userInfo = e.data.data, app.globalData.userInfo.head_pic = s.getFullUrl(app.globalData.userInfo.head_pic);

        //-- 注册的跳转 --
        getApp().go_to_page(th.data.is_reg,function (){
          // wx.navigateBack({ delta: 1 })
          wx.reLaunch({
            url: '/pages/user/index/index',
          })
        })

      },
      failStatus: function (t) {
        wx.hideLoading();
        th.setData({loading: 0,is_check:0});
        return app.my_warnning("授权登入失败,请稍后再试!", 0, that);
      },
      fail: function (t) {
        wx.hideLoading();
        th.setData({loading: 0,is_check:0});
        return i.clearAuth(), i.alertLoginErrorAndGoHome(), !1;
      }
    });


  }

})