// packageF/storeManagement/storeMemberInfo/storeMemberInfo.js
import util from '../../../utils/util.js';
var behavior = require('../common.js');
var app = getApp();
Page({
  behaviors: [behavior],
  /**
   * 页面的初始数据
   */
  data: {
    memberId: '',
    memberData: {},
    memberChild: {},
    titleBgMode: "hide",
    rechargePopup: false, // 积分 余额共用一个弹框
    typeText:"",
    popText: '', // 积分 余额
    recharge: {
      integral: '',
      balance: '',
      remarks: '',
    },
    recommendId:"",//推荐人Id
    recommendInfo:{},//推荐人信息
    couponPopup: false, // 优惠券
    CouponAll:[],//所有优惠劵
    ChooseCouponPopup:false,//选择优惠劵开关
    info:{},   //赠送优惠劵名称
    couponsName:"",//优惠劵名称
    chooseCouponValue:'',
    coupons: {
      id: '',
      name: '',
      number: '',
      emptyName: false,
    },
    isEmitLevel:false,
    level_list:[],
    member_list:[],
    memberFlag:true,
    //会员限期
    currentDate: new Date().getTime(),
    minDate: new Date('1990-1-1').getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      return value;
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(options.id){
      this.setData({memberId:options.id});
      this.getData();
      this.getAllCoupon();
      this.getMemberData()
    }
  },
  //获取会员分组
  getMemberData(){
    app._postNetWork({
      url:app.getNetAddresss("plugin.shop-assistant.frontend.member.get-group"),
      success:(res) => {
        if(res.data.result == 1){
          this.setData({
            member_list:res.data.data
          })
        }
      }
    })
  },
  changeMember_groupId(e){
    this.setData({
      ['memberChild.group_id']:e.detail
    })
  },
  SearchRecommend(e){
    this.setData({recommendId:e.detail.value})
    this.throttleFn("recommend")
  },
  //获取会员信息
  getMemberInfo(){
    this.setData({memberFlag:false})
    app._postNetWork({
      url:app.getNetAddresss("plugin.shop-assistant.frontend.member.search-member"),
      data:{parent_id:this.data.recommendId},
      success:(res) => {
        if(res.data.result == 1 && res.data.data.length!==0){
          this.setData({recommendInfo:res.data.data[0],memberFlag:true})
        }else{
          this.setData({recommendInfo:{},memberFlag:false})
        }
      }
    })
  },
  onClick(event){
    let info =event.currentTarget.dataset.info
    this.setData({info,ChooseCouponPopup:false})
  },
  //选择优惠劵搜索结果
  setCouponsName(e){
    let name = e.detail.value;
    let searchCoupons= this.data.CouponAll.filter(item => {
      if(item.name.indexOf(name)!==-1){
        return item;
      }
    })
    if(name!==''){
      this.setData({CouponAll:searchCoupons})
    }else{
      this.getAllCoupon()
    }
  },
  //获取所有优惠劵
  getAllCoupon(){
    app._postNetWork({
      url: app.getNetAddresss("plugin.shop-assistant.frontend.coupon.all-coupon"),
      success: (res) => {
        if(res.data.result == 1){
          this.setData({CouponAll:res.data.data.list})
        }
      }
    });
  },
  //修改会员限期
  onInput(event){
    this.setData({
      currentDate: event.detail,
    });
  },
  setIsEmitLevel(e){
    if(e){
      let {text:typeText} = e.currentTarget.dataset;
      this.setData({typeText})
    }
    this.setData({isEmitLevel:!this.data.isEmitLevel})
  },
  // 选择优惠劵
  onChangeCoupon(event){
    this.setData({chooseCouponValue:event.detail})
  },
  changeLevel_id({detail}){
    this.setData({["memberChild.level_id"]:detail})
  },
  getlevel_name(level_id){
    let {level_list} = this.data;
    for(let i=0;i<level_list.length;i++){
      let item = level_list[i];
      if(level_id === item.id) return this.setData({["memberChild.level"]:item});
    }
  },
  validity(){
     let d1 = new Date(this.data.currentDate),d2=new Date()
     let cha = d1.getTime()-d2.getTime();
     let day = Math.floor(cha/(24*60*60*1000));
     if(day == -1){
       return 1
     }else if(day == 0){
       return 2
     }else if(day<-1){
       return ''
     }else{
      return day +2
     }
  
  },
  emitLevel(){
    this.setIsEmitLevel();
    let urlStr  = '',json={};
    if(this.data.typeText == '推荐人'){
      urlStr = app.getNetAddresss("plugin.shop-assistant.frontend.member.change-parent");
      json = {
        uid:this.data.memberId,
        arent_id:this.data.recommendId
      }
    }else{
      urlStr = app.getNetAddresss("plugin.shop-assistant.frontend.member.update-member");
      json = {
        id:this.data.memberId,
        member:{
          level_id: this.data.memberChild.level_id || '',
          validity:this.validity(),
          group_id:this.data.memberData.yz_member.group_id || ''
        }
      }
    }
    app._postNetWork({
      url: urlStr,
      data: json,
      success: ({data:{result,msg}}) => {
        if (result != 1) return app.tips(msg);
        app.tips("修改成功");
        this.data.typeText !== '推荐人' && this.getlevel_name(json.member.level_id);
        this.getData();
      }
    });
  },
  showRechargePopup(evt){
    let type = evt.currentTarget.dataset.type;
    let changeData={
      rechargePopup:true,
      recharge:{ 
        integral: '',
        balance: '',
        remarks: ''},
    };
    if(type == "integral"){
      changeData['popText']="积分";
    }else {
      changeData['popText']="余额";
    }
    this.setData(changeData);
  },
  closeRechargePop(){
    this.setData({
      rechargePopup:false
    });
  },
  setRechargeContent(evt){
    let name = evt.currentTarget.dataset.name;
    this.data.recharge[name] = evt.detail.value;
  },
  setCouponsContent(evt){
    let name = evt.currentTarget.dataset.name;
    if(name == 'id'){
      this.setData({
        'coupons.id':evt.detail.value
      });
      this.throttleFn();
    }else {
      this.data.coupons[name] = evt.detail.value;
    }
  },

  getData(){
    let urlStr = app.getNetAddresss("plugin.shop-assistant.frontend.member.get-detail");
    app._postNetWork({
      url: urlStr,
      data: {id:this.data.memberId},
      success: (resdata) => {
        var res = resdata.data;
        if (res.result != 1) return app.tips(res.msg);
        this.setData({
          memberData:res.data,
          memberChild:res.data.yz_member ? res.data.yz_member : {},
          'memberData.createtime':util.formatTimeTwo(res.data.createtime, 'Y-M-D h:m:s'),
          level_list:res.data.level_list || []
        });
      }
    });
  },

  changeAgent(evt){
    this.setData({
      'memberChild.is_agent':evt.detail
    });
    let urlStr = app.getNetAddresss("plugin.shop-assistant.frontend.member.update-agent");
    app._postNetWork({
      url: urlStr,
      data: {id:this.data.memberId,is_agent: this.data.memberChild.is_agent},
      success: (resdata) => {
        var res = resdata.data;
        if (res.result != 1){
          this.setData({
            'memberChild.is_agent':evt.detail==1 ? 0 : 1
          });
          return app.tips("修改失败");
        }
        app.tips("修改成功");
       
      }
    });
  },


  // 确认充值
  confirmRecharge () {
    if (this.data.popText === "积分") {
      this.rechargeIntegral();
    } else {
      this.rechargeBalance();
    }
  },

  // 充值积分
  rechargeIntegral () {
    if (!this.data.recharge.integral) {
      return app.tips("请输入充值数量");
    }
    let json = {};
    json.uid = this.data.memberId;
    json.integral = {
      integral: this.data.recharge.integral * 1,
      remark: this.data.recharge.remarks
    };
    let urlStr = app.getNetAddresss("plugin.shop-assistant.frontend.member.recharge-integral");
    app._postNetWork({
      url: urlStr,
      data: json,
      success: (resdata) => {
        var res = resdata.data;
        app.tips(res.msg);
        if (res.result != 1) return ;
        this.closeRechargePop();
        this.getData();
      }
    });
  },

  // 充值余额
  rechargeBalance () {
    if (!this.data.recharge.balance) {
      return app.tips("请输入充值数量");
    }
    let json = {};
    json.uid = this.data.memberId;
    json.balance = {
      balance: this.data.recharge.balance * 1,
      remark: this.data.recharge.remarks
    };
    let urlStr = app.getNetAddresss("plugin.shop-assistant.frontend.member.recharge-balance");
    app._postNetWork({
      url: urlStr,
      data: json,
      success: (resdata) => {
        var res = resdata.data;
        app.tips(res.msg);
        if (res.result != 1) return ;
        this.closeRechargePop();
        this.getData();
      }
    });
  },
  //打开选择优惠劵
  showChooseCoupon(){
    this.setData({ChooseCouponPopup:true})
  },
  // 优惠券弹框
  showCouponPopup () {
    this.setData({
      couponPopup:true,
      coupons : {
        id: '',
        name: '',
        number: '',
        emptyName: false,
      }
    });
  },
  // 节流
  throttleFn(type="conpon") {
    if (this.timeoutId) {
      clearTimeout(this.timeoutId);
    }
    this.timeoutId = setTimeout(() => {
      type=='conpon'? this.searchConpon():this.getMemberInfo()
    }, 800);
  },
  // 查询优惠券
  searchConpon () {
    let urlStr = app.getNetAddresss("plugin.shop-assistant.frontend.coupon.coupon-detail");
    app._postNetWork({
      url: urlStr,
      data: {id:this.data.coupons.id},
      success: (resdata) => {
        var res = resdata.data;
        if (res.result != 1){
          this.setData({
            'coupons.emptyName':true
          });
          return app.tips(res.msg);
        }
        this.setData({
          'coupons.emptyName':false,
          'coupons.name':res.data.name
        });
      }
    });
  },
  // 确定赠送
  confirmGive () {
    // if (!this.data.coupons.id) {
    //   return app.tips('请输入优惠券id');
    // }
    if(this.data.info && !this.data.info.name){
      return app.tips("请选择优惠劵")
    }
    if (!this.data.coupons.number) {
      return app.tips('请输入赠送优惠券数量');
    }
    // if (this.data.coupons.id && !this.data.coupons.name) {
    //   return app.tips('未查询到优惠券');
    // }
    let json = {
      uid: this.data.memberId,
      id: this.data.info.id,
      send_total: this.data.coupons.number * 1
    };

    let urlStr = app.getNetAddresss("plugin.shop-assistant.frontend.coupon.send-coupon");
    app._postNetWork({
      url: urlStr,
      data: json,
      success: (resdata) => {
        var res = resdata.data;
        app.tips(res.msg);
        if (res.result != 1) return;
        this.setData({couponPopup:false})
        this.getData();
      }
    });
  },

  closeCouponPop (e) {
    let {type}=e.currentTarget.dataset
    this.setData({
      [type]:false
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

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

  },

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

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  onPageScroll(evt){
    if (evt.scrollTop >= 50 && this.data.titleBgMode == "hide") {
      this.setData({titleBgMode:'show'});
    } else if (evt.scrollTop <= 50 && this.data.titleBgMode == "show") {
      this.setData({titleBgMode:'hide'});
    }
  },

  setTopping(){
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
});