var t = getApp(),
  a = t.request,
  o = t.globalData.setting,
  os = o,
  i = require("../../../../utils/util.js"),
  ut = i,
  s = require("../../../../utils/common.js");
var regeneratorRuntime = require('../../../../utils/runtime.js');
const {
  barcode,
  qrcode
} = require('../../../../utils/index.js');
let _this = null;
 
Page({
  data: {
    iurl: getApp().globalData.setting.imghost,
    val:false,
    datet: "",
    dates: "",
    parameter: false,
    details:[],//数据
    isBind:true,//控制清空时间日期的按钮
    isBinds: true,
    select: false,//下拉框
    grade_name: '未使用',
    // grades: [ //old
    //   '所有',
    //   '已使用',
    //   '已过期',
    //   '未使用',
    // ],
		currentIndex: 0, //tab项当前指示器
		grades: [
		  '未使用',
		  '已使用',
		  '已过期',
		],
    display:false,
    is_no_more: 0,
    current_page:1,
	by_list:[],
	isloading:0,
	pageNum: 1,
	  currentIndex:0
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
	   _this = this;
	  // this.setData({
		//   details: []
	  // });
	  // this.wjquery();
      if(options.index){
		  this.setData({currentIndex:options.index});
	  }



  },
  /**
     * 生命周期函数--监听页面显示
     */
  onShow: function (options) {
		var th = this;
		
    wx.setNavigationBarTitle({
      title: "我的优惠券",
    });
		
		/**
		 * 控制显示微券兑换
		 * by sty
		 */
		getApp().getConfig2(function (ee) {
			var json_d = JSON.parse(ee.switch_list);
			let is_show_dhwz = json_d.dhwz_switch;
			let grades = th.data.grades;
			// console.log('is_show_dhwz----------------------------',is_show_dhwz);
			if (is_show_dhwz) {
				if (grades.indexOf('微券兑换') == -1) {
					grades.push('微券兑换');
					th.setData({grades});
				}

			}

			th.setData({is_show_dhwz});
			th.init_data(th.data.currentIndex);

		},1);




  },
	//跳转商品
  nvShop(){
    let url= '/pages/goods/goodsList/goodsList'  
    getApp().goto(url)
  },
  //跳转商品详情
	nvShopInfo(e){
    let useobjectid = e.currentTarget.dataset.useobjectid;
    //------------------------------------------------
    getApp().request.get('/api/weshop/goods/list', {
      data: {
        store_id: os.stoid,
        erpwareid: useobjectid,
      },
      success(res) {
        if (res.data.code ==0) {
          let good = res.data.data;
          if (good.length>0) {
            let item = good[0]
            let url = `/pages/goods/goodsInfo/goodsInfo?goods_id=${item.goods_id}&prom_type=${item.prom_type}&prom_id=${item.prom_id}`
            getApp().goto(url)
          }else{
            getApp().showWarning("该商品不存在");
          }
        }
      }
    })

   
   
    // wx.reLaunch({
    //   url: '/pages/goods/goodsInfo/goodsInfo',
    // })






     //------------------------------------------------
  },
	
  // 点击选中二维码
  click: function (e) {
    var val = e.currentTarget.dataset.cashrepno;
    getApp().globalData.val = val;
    wx.navigateTo({
      url: '../qr_code/qr_code',
    })
  },
  // 点击返回主页
  // clicks: function () {
  //   this.setData({
  //     hide:true, display:false
  //   })
  // },
  //监听输入框显示清空按钮
  watchPassWord: function (event) {
    var val = event.detail.value;
    if (val != "" && val != null) {
      var isBind = false;
      this.setData({ isBind: isBind });

    }
  },
  /**
   *  点击下拉框
   */
  bindShowMsg() {
    this.setData({
      select: !this.data.select
    })
  },
  /**
   * 已选下拉框
   */
  // mySelect(e) {
  //   var name = e.currentTarget.dataset.name;
  //   this.setData({
  //     grade_name: name,
  //     select: false
  //   })
  // },
	
	/**
	 * 点击tab
	 * by sty
	 */
	clickTab(e) {
		let index = e.target.dataset.index;
		let name = e.target.dataset.name;
		
		this.setData({
			is_get: 0,
			pageNum: 1,
			grade_name: name,
			currentIndex: index,
			is_no_more: 0,
			current_page: 1,
			noMore: false,
			details: [],
			by_list: [],
			showQr: false,
		});
		
		
		if(index == 3) {//微券兑换
			this.exchange();
		} else {//其他
			this.wjquery();
		};
	},

	init_data(idx){

		var name=this.data.grades[idx];
		this.setData({
			is_get: 0,
			pageNum: 1,
			grade_name: name,
			currentIndex: idx,
			is_no_more: 0,
			current_page: 1,
			noMore: false,
			details: [],
			by_list: [],
			showQr: false,
		});

		if(idx == 3) {//微券兑换
			this.exchange();
		} else {//其他
			this.wjquery();
		};
	},

	
	/**
	 * 点击"立即使用"
	 * by sty
	 */
	clickUse(e) {
		let useIndex = e.currentTarget.dataset.index;
		let val = e.currentTarget.dataset.cashrepno;
		
		
		this.setData({
			showQr: true,
			useIndex,
		});
		this.qrcode(val);
	},
	
	/**
	 * 关闭二维码
	 * by sty
	 */
	closeQr() {
		this.setData({
			showQr: false,
		});
	},
	
	/**
	 * 生成二维码
	 * by sty
	 */
	qrcode:function(val){
	  // console.log(val);
	  barcode('barcode', val, 600,160);
	  qrcode('qrcode', val, 300, 300);
	},
	
	/**
	 * 请求微券列表
	 * by sty
	 */
	async exchange() {
		var result;
		var user_id = getApp().globalData.user_id;
		var store_id = os.stoid;
		
		
		this.getData(true, '/api/weshop/users/listExchangeCoupons', {
			user_id: user_id, store_id: store_id, 
		}).then(()=>{
			_this.setData({
				result: _this.data.list.pageData,
			});
		});
		
		// await getApp().request.promiseGet("/api/weshop/users/listExchangeCoupons", {
		// 	data: {
		// 		user_id: user_id, store_id: store_id,
		// 	}
		// }).then(res => {
		// 	// var msg = res.data;
		// 	// result = msg.data.pageData;
		// })
		// e.setData({
		// 	result: result
		// })
	},
	
	/**
	 * 微券兑换对话框
	 * by sty
	 */
	async clickExchange(e) {
	  var th=this;
	  var index = e.currentTarget.dataset.index;
	  var item = this.data.result[index];
	  this.data.monye = item.ToSum;
	  this.data.integr = item.Integral;
	  this.data.number = item.Number;
		
		let content = `确定使用${th.data.integr}积分兑换代金券面值${th.data.monye}元吗?`;
		wx.showModal({
		  title: '提示',
		  content: content,
		  success (res) {
		    if (res.confirm) {
		      console.log('用户点击确定');
					th.sure_pay();
		    } else if (res.cancel) {
		      console.log('用户点击取消')
		    }
		  }
		});
		

	
	  // var my_con = this.selectComponent("#my_con"); //组件的id
	  // var title="是否使用"+th.data.integr+"积分兑换代金券面值"+th.data.monye+"元";
	  // my_con.open(title, "确定", "取消", th.sure_pay, null)
	},
	
	
	/**
	 * 微券兑换
	 * by sty
	 */
	sure_pay:function(){
	  var monye=this.data.monye;
	  var integr=this.data.integr;
	  var number=this.data.number;
	
	  var user_id = getApp().globalData.user_id;
	  console.log(integr,"是什么微卷",typeof integr,monye);
	  var store_id = os.stoid;
	  getApp().request.post("/api/weshop/users/saveInterToCash", {
	    data: {
	      user_id: user_id,
	      store_id: store_id,
	      money:monye,
	      integ:integr,
	      number:number,
	    },
	    success: function (su) {
	      if (su.data.data!=null) {
	        // getApp().showWarning("兑换成功");
					wx.showToast({
						title: '兑换成功',
						icon: 'success',
					});
	      }else{
	        // getApp().showWarning("积分不足");
					wx.showToast({
						title: '积分不足',
						icon: 'error',
					});
	      }
	    }
	
	  })
	},
	
  
  //明细查询
  Gettime:function(e){
    var page = 0;
    //开始获取时间
    var th = this;
    var stime = th.data.datet;
    var etime = th.data.dates;
    var tpye = th.data.grade_name;
   
    //开始获取时间结束
    //删除字符中的——
    var datatk = stime.replace(/[-]/g, "");
    var dataj = etime.replace(/[-]/g, ""); 
    //转换类型
    var datak = parseInt(datatk);
    var dataj = parseInt(dataj);
    
    //判断初始时间小于结束时间
    if (datak > dataj) {
      getApp().showWarning("结束时间错误");    
    } else {
      this.setData({ details: [] });
      this.data.current_page=1;
	  this.data.is_no_more=0;
	  this.data.by_list=[];
	  this.data.details=[];
      this.wjquery();
    }

  },
	
  //微卷查询流水明细
  async wjquery() { 
    if(this.data.isloading) return;
		if(this.data.is_no_more) return;
		this.data.isloading=1;
		var th=this;
	
    var len = this.data.details.length;
    
    var e = this,sum, val, number;
    var user_id = getApp().globalData.user_id;
    var store_id = os.stoid;
		
    var stime = this.data.datet; 
    var etime = this.data.dates; 
		
    var tpye = this.data.grade_name;
    console.log("是什么类型",tpye);
    var IsUse = 0;
    var e = this;
    var get_data = {
      user_id: user_id,
      store_id: store_id,
      // pageSize: 10,
      page: e.data.current_page,
    };
	
	var dd={ 
		user_id: user_id, 
		store_id: store_id,
		// pageSize: 10,
	};
	dd.isuse=0;
    // 判断下拉框，添加类型
   if (tpye == "已使用"){   
      get_data.IsUse = 1;
	  dd.isuse=1;
   } else if (tpye == "已过期"){      
      get_data.IsUse = 2;
   } else if (tpye == "未使用"){
      get_data.IsUse = 0;
    };
    if (etime != "" && etime != null) {
      get_data.EndDate = etime;
	  
	  //时间要转成时间戳
	  var new_t=new Date(etime)/1000;  
	  dd.etime=new_t;	  
    }

    if (stime != "" && stime != null) {
       get_data.BeginDate= stime;
	   //时间要转成时间戳
	   var new_t=new Date(stime)/1000;  
	   dd.stime=new_t;
    }
	
	var by_list=[];
	if(th.data.current_page==1){
		  //先拿包邮券
		  await getApp().request.promiseGet("/api/weshop/userfeemail/pageAndArea?pageSize=100", {
		      data: dd,   
		  }).then(res => {
				
					if(res.data.code == 0) {
						th.setData({
							 byTotal: res.data.data.total,
						});
					};
				 
			   if(res.data.code==0 && res.data.data && res.data.data.total>0){
					 
			       by_list=res.data.data.pageData; 
				   for(var i in by_list){
					    by_list[i].isby=1;
						//过滤是时间的范围
					    if(get_data.IsUse == 2 && by_list[i].use_end_time<=ut.gettimestamp()){
					    	 th.data.by_list.push(by_list[i]);										   
					    }else if(get_data.IsUse == 0){
							 th.data.by_list.push(by_list[i]);
						}else if(get_data.IsUse==1){
							 th.data.by_list.push(by_list[i]);
						}else if(get_data.IsUse==undefined){
							  th.data.by_list.push(by_list[i]);
						}
				   }			  
			   }
		  })
	}
  
    var big_arr = this.data.details; ///api/weshop / users / listQuan
	if(th.data.current_page==1 && th.data.by_list.length>0) {
		big_arr=th.data.by_list;
	};
		
	
    await getApp().request.promiseGet("/api/weshop/users/listQuan", {  
        data: get_data,
        isShowLoading: 1
      
    }).then(res => {
     
	  th.data.isloading=0; 
      var a = res.data;
      var len = e.data.details.length;
      var details = a.data.pageData;
			
			th.setData({
				pageSize: a.data.pageSize,
				wjTotal: a.data.total,
			});
         
      if (details.length == 0) {
				this.setData({
					is_no_more: 1,
				});
        // getApp().showWarning("未找更多数据");
		if(th.data.by_list && th.data.current_page==1){
			 th.setData({ val: val,details:th.data.by_list});
			 details=th.data.by_list;
			 setTimeout(function () {
			   for (var i = 0; i < details.length; i++) {
			     var no = i + len;
			     qrcode('qrcode' + no, details[i].no,460, 460);
			   }
			 }, 100)
		}	      
        return false;
      }
	  
	  th.data.current_page++;  
      val = a.data.total+th.data.by_list.length;

      big_arr=big_arr.concat(details);
      this.setData({
        details: big_arr,val: val,
				is_get: 1,
				current_page: this.data.current_page,
      });

      setTimeout(function () {
		if(by_list) details=big_arr;	
        for (var i = 0; i < details.length; i++) {
          var no = i + len;
          qrcode('qrcode' + no, details[i].CashRepNo?details[i].CashRepNo:details[i].no,460, 460);
        }
      }, 100)
    })
    
      
    
  },
	
	
	// 使用说明详情展开
	clickDetails: function(e) {
		let details = this.data.details;
		let index = e.currentTarget.dataset.index;
		details[index].isShowDetails = !details[index].isShowDetails;
		this.setData({
			details,
		});
	},
	
	
	
  //---加载更多是靠这个函数----
  onReachBottom: function () {
		if(this.data.currentIndex != 3) {
			this.wjquery();
		} else {
			this.scrollToLower('/api/weshop/users/listExchangeCoupons', {
				user_id: getApp().globalData.user_id,
				store_id: os.stoid,
			}, function() {
				// console.log('!!!!!', _this.data.list.pageData);
				_this.setData({
					result: _this.data.list.pageData,
				});
			});
		};
  },
	
	
  //起始时间
  // bindDateChenge: function(e) {
  //   console.log("是什么", e.detail.value);
  //   var isBind = false;
  //   this.setData({
  //     datet: e.detail.value, isBind: isBind 
  //   });
  // },
  // 结束时间
  // bindDateChenges: function(e) {
  //   console.log("是什么", e.detail.value);
  //   var isBinds = false;
  //   this.setData({
  //     dates: e.detail.value, isBinds: isBinds 
  //   });
  // },
  //catchtap阻止冒泡，点击清除开始时间的按钮
  // eliminate:function(){
  //   console.log("试试");
  //   var isBind= true;
  //   var data="";
  //   this.setData({ datet: data, isBind: isBind})
  // },
   //catchtap阻止冒泡，点击清除结束时间的按钮
  // eliminates: function () {
  //   console.log("试试");
  //   var isBinds = true;
  //   var dates = "";
  //   this.setData({ dates: dates, isBinds: isBinds })
  // },
	
	
	
	
	
	
	// 上拉加载请求数据
	getData: function(isInit, url, data) {
		return getApp().request.promiseGet(url, {data: data, isShowLoading: true,})
		 .then((res) => {
				 _this.data.isLoading = false;
				if(res.data.code == 0) {
					if(isInit) {// 第一次加载
						_this.setData({
							list: res.data.data
						});
					} else {
						_this.setData({
							'list.pageData': _this.data.list.pageData.concat(res.data.data.pageData)
						});
					};
					
					if((res.data.data.pageData.length == 0) || (res.data.data.pageSize * res.data.data.page >= res.data.data.total)) {
						_this.setData({
							noMore: true
						});
					};
				};
		 });
	},
	
	
	// 上拉加载
	scrollToLower(url, requestData, callback) {
		// 页面数据
		// let pageData = this.data.list.pageData;
		// 数据总量
		let total = this.data.list.total;
		// 单页最大数据量
		let pageSize = this.data.list.pageSize;
		// 如果数据总量不为0且小于或等于单页最大数据量，说明数据已全部加载，显示‘没有更多了’
		if((total != 0)&&(total <= pageSize)) {
			this.setData({
				noMore: true
			});
		};
		
		if(!this.data.isloading && !this.data.noMore) {
			this.setData({
				isLoading: true,
				pageNum: this.data.pageNum + 1
			});
			requestData.page = this.data.pageNum;
			this.getData(false, url, requestData).then(()=>{
				if(callback) {
					callback();
				};
			});
		};
	},
	
	// 禁用滚动
	// disableScroll() {
	// 	this.setData({
	// 		scrollType: 'disableScroll'
	// 	});
	// },
	
	//启用滚动
	// enableScroll() {
	// 	this.setData({
	// 		scrollType: '',
	// 	});
	// },
	
	touchStart() {},
	touchMove() {},
	touchEnd() {},
  
})