// packageA//pages/distribution/commision/commision.js
const app =  getApp();
let self = null;
var  os = app.globalData.setting,
ut = require("../../../../utils/util.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
		isInputFocus: false,//记录搜索输入框是否聚焦
		inputVal: '',//记录搜索输入框的内容
		isSort: false,//控制排序开关状态，true开启排序
		isDescending: false, //isDescending降序，ascending升序
		tabArr: [],
		currentTabIndex: 0,
		isShowRow: false,//控制视图切换状态
		isHiddenDropdown: true,//控制筛选下拉菜单显隐
		list: null,
		isLoading: false, // 检测是否已经发送请求,防止重复发送请求
		noMore: false, // 检测是否有更多数据,true为没有更多数据,false为还有数据
		pageNum: 1, // 当前页数
		isCheckAll: false, //记录是否全选
		currentQuery: {
			store_id: app.globalData.setting.stoid,
		},
		is_no_plus:1,
		default_img: '/miniapp/images/default_g_img.gif',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
	  
	     wx.setNavigationBarTitle({
	       title: "上下架商品",
	     });
	  
		self = this;//保存全局指针
		app.isLogin().then(function(data) {//进入页面前已经授权登录成功
			self.setData({
				userInfo: data,
			});
		});
		
		
		//动态设置标题：0选择商品，1上架商品
		let title = '';
		let tabArr = [];
		if(options.index == 0) {
			title = '选择上架商品';
			tabArr = ['最新','销量','评论','价格'];
		} else {
			title = '选择下架商品';
			tabArr = ['已选','必营','销量','价格'];
		};
		wx.setNavigationBarTitle({
			title,
		});
		this.setData({
			options,
			tabArr,
		});

		//调用接口判断商家plus有没有过期
		getApp().request.promiseGet("/store/storemoduleendtime/page?store_id=" + os.stoid + "&type=3", {}).then(res => {
			if (res.data.code == 0) {
				var arr = res.data.data.pageData;
				if (arr.length > 0) {
					var item = arr[0];
					if (item.is_sy == 0) {
						var now = Date.parse(new Date()); now = now / 1000;
						if (item.end_time < now) {
							self.setData({ is_no_plus: 0 })
						}
					}
				}
			}
		})
		
		
		
		
  },

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

  },

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

        getApp().check_can_share();
		let url = '/api/weshop/goods/page?isnewwhere=1';
		let currentQuery = this.data.currentQuery;
		if(app.globalData.userInfo) {
			if(!this.data.isLogin) {
				this.setData({
					userInfo: app.globalData.userInfo,
					imghost: app.globalData.setting.imghost,
					isLogin: true,
					'currentQuery.user_id': app.globalData.user_id,
				});
				
				if(this.data.options.index == 0) {//上架商品
					// 请求数据
					currentQuery.is_mainshow = 1;
					currentQuery.isonsale = 1;
					currentQuery.searchtype = 2;
					
				} else {//下架商品
					currentQuery.searchtype = 1;
					
				};
				currentQuery.orderType = 'desc';
				currentQuery.dis_type = 1;
				this.getData(true, url, currentQuery);
				
				// 加载筛选条件:国别
				app.request.promiseGet('/api/weshop/goods/listGroupnation', {
					data: currentQuery,
					// isShowLoading: true,
				}).then(function(res) {
					console.log('nation=====>', res.data.data);
					self.setData({
						nationList: res.data.data,
					});
				});
				// 加载筛选条件:品牌
				app.request.promiseGet('/api/weshop/goods/listGroupbrand', {
					data: currentQuery,
					// isShowLoading: true,
				}).then(function(res) {
					console.log('brand=====>', res.data.data);
					self.setData({
						brandList: res.data.data,
					});
				});
				
				
				
				//更新一下会员的信息
				if(getApp().globalData.user_id) {
					 // if(!getApp().globalData.userInfo['is_distribut']){
						//  this.setData({ishidden_comise:1})
					 // }			
					 getApp().request.get("/api/weshop/users/get/" + os.stoid + "/" + getApp().globalData.user_id, {
					   isShowLoading:false,  
					   success: function (e) {
						 getApp().globalData.userInfo = e.data.data;
						 getApp().getConfig2(function (e) {
						   var swithc_list = e.switch_list;
						   var sw_arr = JSON.parse(swithc_list);
						   //---如果后台有开等级卡的开关---
						   if (sw_arr.rank_switch && sw_arr.rank_switch == "2") {
							 self.setData({
							   rank_switch: true
							 });
							 //---回调卡的列表---
							 self.getPlusCardType(function (ob) {
							   self.setData({
								 card_list: ob.card_list
							   });
							   var ti = setInterval(function () {
								 var user = getApp().globalData.userInfo;
								 if (!user) return false;
								 clearInterval(ti);
								 if (user.card_field && user['card_expiredate']) {
								   var str = user['card_expiredate'].replace(/-/g, '/');
								   var end = new Date(str);
								   end = Date.parse(end) / 1000;
								   var now = ut.gettimestamp();
								   //--- 判断是等级会员，且在有效期范围内 ---
								   if (user.card_field && now < end) {
									 var card_name = ob.name_map.get(user.card_field);
									 if (card_name.length > 4) card_name = card_name.substring(0, 8);
									 self.setData({
									   card_field: user.card_field,
									   card_name: card_name,
									   card_list: ob.card_list
									 });
								   }
								 }
							   }, 500)
							 })
						   }
						 })
					   }
					 })
				 }
				 
				 
				 
			};
		};
  },

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

  },

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

  },

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

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
		let data = this.data.currentQuery;
		let options = this.data.options;
		let url = '';
		
		if(options.index == 0) {
			url = '/api/weshop/goods/page?isnewwhere=1&is_mainshow=1&isonsale=1&dis_type=1';
		} else {
			url = '/api/weshop/goods/page?isnewwhere=1';
		};
		
		
		this.scrollToLower(url, data, function() {
			let items = self.data.list.pageData;
			let values = self.data.checkedArr;
			let isCheckAll = self.data.isCheckAll;
			
			if(items.length == values.length) {
				if(!isCheckAll) {
					isCheckAll = !isCheckAll;
				};
			} else {
				if(isCheckAll) {
					isCheckAll = !isCheckAll;
				};
			};
			
			self.setData({
				isCheckAll,
			});
		});
		
  },

  /**
   * 用户点击右上角分享
   */
   onShareAppMessage: function () {   	  getApp().globalData.no_clear=1

  },
	
	/**
	 * 点击下拉菜单
	 */
	clickDropdown() {
		this.setData({
			isHiddenDropdown: !this.data.isHiddenDropdown,
		});
	},
	
	/**
	 * 点击遮罩层
	 */
	clickMask() {
		this.setData({
			isHiddenDropdown: true,
		});
	},
	
	/**
	 * 选择下拉菜单项
	 */
	selectDropdown(e) {
		let currentIndex = e.target.dataset.index;
		this.setData({
			isHiddenDropdown: true,
			currentSelect: this.data.dropdownArr[currentIndex],
		});
	},
	
	/**
	 * 搜索输入框聚焦
	 */
	inputFocus() {
		this.setData({
			isInputFocus: true,
		});
	},
	
	/**
	 * 搜索输入框失焦
	 */
	inputBlur() {
		this.setData({
			isInputFocus: false,
		});
	},
	
	/**
	 * 搜索输入框输入内容
	 */
	input(e) {
		this.data.inputVal = e.detail.value;
	},
	
	/**
	 * 搜索输入框清空内容
	 */
	inputClear() {
		let inputVal = this.data.inputVal;
		console.log('input', inputVal);
		if(inputVal) {
			this.setData({
				inputVal: '',
			});
		};
	},
	
	/**
	 * 点击搜索
	 */
	search(callback) {
		let url = '';
		let currentTabIndex = 0;
		let data = this.data.currentQuery;
		if(data.orderField) delete data.orderField;
		if(data.orderType) delete data.orderType;
		// if(this.data.inputVal) {
			data.key_str = this.data.inputVal;
			
		// };
		if(this.data.isHiddenDropdown) {
			if(data.nation_id) delete data.nation_id;
			if(data.brand_id) delete data.brand_id;
			if(data.startprice) delete data.startprice;
			if(data.endprice) delete data.endprice;
		};
		if(data.key_str != '') {
				currentTabIndex = 5;
		};
		this.setData({
			list: null,
			currentTabIndex,
		});
		// console.log('data', data);
		
		
		if(this.data.options.index == 0) {//上架商品
			url = '/api/weshop/goods/page?isnewwhere=1&is_mainshow=1&isonsale=1&dis_type=1';
		} else {//下架商品
			data.dis_type = 1;
			url = '/api/weshop/goods/page?isnewwhere=1&searchtype=1';
		};
		this.getData(true, url, data)
		.then(function(callback) {
			if(callback) callback();
		});
	},
	
	/**
	 * 点击排序
	 */
	clickSort() {
		let data = this.data.currentQuery;
		// if(data.orderType == 'desc') delete data.orderType;
		if(!this.data.isSort) {
			this.setData({
				isSort: true,
			});
		} else {
			this.setData({
				isDescending: !this.data.isDescending,
			});
		};
		if(this.data.isDescending) {
			data.orderType = 'desc';
		} else {
			data.orderType = 'asc';
		};
	},
	
	/**
	 * 点击视图切换按钮
	 */
	change() {
		this.setData({
			isShowRow: !this.data.isShowRow
		});
	},
	
	/**
	 * 点击Tab
	 */
	clickTab(e) {
		let url = '';
		let isSort = this.data.isSort;
		let data = this.data.currentQuery;
		let isDescending = this.data.isDescending;
		let currentIndex = e.target.dataset.index;
		let options = this.data.options; 
		
		if(currentIndex != 3) {
			if(isSort) {
				isSort = false;
			};
			if(isDescending) {
				isDescending = false;
			};
		};
		
		if(data.page) delete data.page;
		if(data.key_str) delete data.key_str;
		
		// data.orderType = 'desc';
		// if(data.nation_id) delete data.nation_id;
		// if(data.brand_id) delete data.brand_id;
		// if(data.startprice) delete data.startprice;
		// if(data.endprice) delete data.endprice;
		
		this.setData({
			currentTabIndex: currentIndex,
			isSort,
			isDescending,
			list: null,
			noMore: false,
			pageNum: 1,
			isCheckAll: false, //清除全选状态
		});
		
		switch(currentIndex) {
			case 0: {
				if(data.orderField) delete data.orderField;
				// if(data.orderType) delete data.orderType;
				data.orderType = 'desc';
				if(options.index == 1) {//下架：已选
					data.searchtype = 1;
					data.dis_type = 1;
				};
				break;
			};
			case 1: {
				if(options.index == 0) {//上架：销量排序
					// if(data.orderType) delete data.orderType;
					data.orderField = 'sales_sum';
				} else {//下架：必营
					if(data.searchtype) delete data.searchtype;
					if(data.orderField) delete data.orderField;
					// if(data.orderType) delete data.orderType;
					data.dis_type = 0;
				};
				data.orderType = 'desc';
				break;
			};
			case 2: {
				if(options.index == 0) {//上架：评论排序
					// if(data.orderType) delete data.orderType;
					data.orderField = 'comment_count';
				} else {//下架：销量排序
					// if(data.orderType) delete data.orderType;
					data.orderField = 'sales_sum';
					data.dis_type = 1;
					data.searchtype = 1;
				};
				data.orderType = 'desc';
				break;
			};
			case 3: {
				// if(data.orderType) delete data.orderType;
				data.orderField = 'final_price';
				data.dis_type = 1;
				break;
			};
		};
		
		if(options.index == 0) {
			url = '/api/weshop/goods/page?isnewwhere=1&is_mainshow=1&isonsale=1&dis_type=1';
		} else {
			url = '/api/weshop/goods/page?isnewwhere=1';
		};
		this.getData(true, url, data);
	},
	
	/**
	 * 点击筛选
	 */
	clickFilter() {
		this.setData({
			isHiddenDropdown: !this.data.isHiddenDropdown,
		});
	},
	
	/**
	 * 点击遮罩层，关闭筛选下拉菜单
	 */
	clickMask() {
		if(!this.data.isHiddenDropdown) {
			this.setData({
				isHiddenDropdown: true,
			});
		}
	},
	
	/**
	 * promiseGet请求数据
	 */
	getData: function(isInit, url, data, isShowLoading) {

		var user_id=getApp().globalData.user_id;
		if(!user_id) user_id=0;
		data.user_id=user_id;

		return new Promise(function(resolve, reject) {
			
			app.request.promiseGet(url, {
				data: data,
				isShowLoading: !isShowLoading ? isShowLoading : true,
			})
			.then(function(res) {
				// console.log('1121', res.data.code);
				if(res.data.code == 0) {
					
					self.setData({
						isLoading: false
					});
					
					if(isInit) {// 第一次加载
						self.setData({
							list: res.data.data
						});
					} else {
						self.setData({
							'list.pageData': self.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)) {
						self.setData({
							noMore: true
						});
					};
					
				} else {
					self.setData({
						'list.pageData': []
					});
				};
				resolve();
			})
			.catch(function(err) {
				console.log('出错拉！！！！',err);
				self.setData({
					'list.pageData': []
				});
			});
			
		});
		
	},
	
	
	/**
	 * 上拉加载数据
	 */
	scrollToLower(url, requestData, callback) {
		// 数据总量
		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(function() {
				callback();
			});
		};
	},
	
	/**
	 * 点击多选框
	 */
	checkboxChange(e) {
		// 全选的情况下,取消选择某个单项,全选状态取消
		// 手动选择所有单项，全选状态点亮
		let items = this.data.list.pageData;
		let values = e.detail.value;
		let isCheckAll = this.data.isCheckAll;
		
		if(items.length == values.length) {
			if(!isCheckAll) {
				isCheckAll = !isCheckAll;
			};
		} else {
			if(isCheckAll) {
				isCheckAll = !isCheckAll;
			};
		};
		
		this.setData({
			isCheckAll,
			checkedArr: values,
		});
		// console.log('选择的数组1',values);
	},
	
	/**
	 * 全选
	 */
	clickCheckAll(e) {
		let checkedArr = [];
		let items = this.data.list.pageData;
		for(let i = 0, length = items.length; i < length; i++) {
			items[i].checked = !this.data.isCheckAll;
			if(items[i].checked) {
				checkedArr.push(items[i].goods_id);
			};
		};
		this.setData({
			'list.pageData': items,
			isCheckAll: !this.data.isCheckAll,
			checkedArr,
		});
		// console.log('选择的数组',checkedArr);
	},
	
	/**
	 * 处理多选的e.detail.value
	 */
	handleValues(arr) {
		if(arr) {
			let newArr = [];
			arr.forEach(function(item, index) {
				newArr.push({'goods_id': item});
			});
			// console.log('newArr', newArr);
			return newArr;
		};
	},
	
	/**
	 * 一键上架
	 */
	putOn() {
		let checkedArr = this.data.checkedArr;
		let checkedList = this.handleValues(checkedArr);

		if(checkedArr && checkedArr.length != 0 ) {
			app.request.promisePost('/api/weshop/users/distribut/UpGoods', {
				is_json: true,
				data: {
					storeId: app.globalData.setting.stoid,
					userId: app.globalData.user_id,
					goods: checkedList,
					searchtype: 2,
				},
			}).then(function(res) {
				if(res.data.code == 0) {
					self.setData({
						isCheckAll: false,
						checkedArr: null,
					});
					wx.showToast({
					  title: '上架成功',
					  icon: 'success',
					  duration: 1000,
					});
					
					self.getData(true, '/api/weshop/goods/page?isnewwhere=1&is_mainshow=1&isonsale=1&dis_type=1', self.data.currentQuery, false);	
				} else {
					wx.showToast({
					  title: '上架失败',
					  icon: 'success',
					  duration: 1000,
					});
				}
				
			});
		} else {
			wx.showToast({
			  title: '请选择上架商品',
			  icon: 'none',
			  duration: 1000,
			});
		};
		
	},
	
	/**
	 * 一键下架
	 */
	pullOff() {
		let data = {
			storeId: app.globalData.setting.stoid,
			userId: app.globalData.user_id,
		};
		let isCheckAll = this.data.isCheckAll;
		let checkedArr = this.data.checkedArr;
		
		if(isCheckAll) {
			// console.log('全选啦~');
			data.type = 1;
		} else {
			// var checkedArr = this.data.checkedArr;
			var checkedList = this.handleValues(checkedArr);
			data.goods = checkedList;
		};
		
		
		if(checkedArr && checkedArr.length != 0) {
			app.request.promisePost('/api/weshop/users/distribut/DownGoods', {
				is_json: true,
				data: data,
			}).then(function(res) {
				if(res.data.code == 0) {
					self.setData({
						isCheckAll: false,
						checkedArr: null,
					});
					wx.showToast({
					  title: '下架成功',
					  icon: 'success',
					  duration: 1000,
					});
					self.getData(true, '/api/weshop/goods/page?isnewwhere=1&dis_type=1&searchtype=1', self.data.currentQuery, false);
				} else {
					wx.showToast({
					  title: '下架失败',
					  icon: 'success',
					  duration: 1000,
					});
				}
				
			});
		} else {
			wx.showToast({
			  title: '请选择下架商品',
			  icon: 'none',
			  duration: 1000,
			});
		};
	
	},
	
	/**
	 * 点击跳转
	 */
	goto(e) {
		let url = '';
		if(e.target.dataset.name == 'checkbox') {
			return;
		} else {
			if(e.target.dataset.url) {
				url = e.target.dataset.url;
			} else {
				url = e.currentTarget.dataset.url;
			}
			app.goto(url);
		};
	},
	
	
	/**
	 * 筛选：选择
	 */
	select(e) {
		let currentIndex = e.target.dataset.index;
		let name = e.target.dataset.name;
		let id = e.target.dataset.id;
		let currentQuery = this.data.currentQuery;

		switch(name) {
			case 'nation': {
				this.setData({
					nationIndex: currentIndex,
				});
				currentQuery.nation_id = id;
				break;
			};
			case 'brand': {
				this.setData({
					brandIndex: currentIndex,
				});
				currentQuery.brand_id = id;
				break;
			};
		};
		
	},
	
	
	/**
	 * 筛选：获取价格区间
	 */
	getPrice(e) {
		let isMax = e.target.dataset.ismax;
		let price = e.detail.value;
		let currentQuery = this.data.currentQuery;
		
		if(isMax == 0) {
			currentQuery.startprice = price;
		} else {
			currentQuery.endprice = price;
		};
	},
	
	/**
	 * 筛选：点击确定
	 */
	startFilter() {
		let data = this.data.currentQuery;
		let startprice = parseFloat(data.startprice);
		let endprice = parseFloat(data.endprice);
		
		// 如果筛选条件为空,按确定按钮不发送请求
		if(!data.nation_id && !data.brand_id && !startprice && !endprice && !this.data.inputVal) {
			this.setData({
				isHiddenDropdown: true,
				currentTabIndex: 0,
			});
			if(data.orderField) delete data.orderField;
			this.getData(true, '/api/weshop/goods/page?isnewwhere=1', data);
			return;
		};
		
		if(startprice && endprice) {
			if(startprice > endprice) {
				wx.showToast({
				  title: '最低价不能高于最高价',
				  icon: 'none',
				  duration: 2000
				});
				return;
			};
		};
		if(!this.data.inputVal) {
			if(data.key) delete data.key;
		};

		this.search(function() {
			self.setData({
				isHiddenDropdown: true,
			});
		});
	},
	
	/**
	 * 筛选：重置
	 */
	reset() {
		let data = this.data.currentQuery;
		
		if(data.nation_id) delete data.nation_id;
		if(data.brand_id) delete data.brand_id;
		if(data.startprice) delete data.startprice;
		if(data.endprice) delete data.endprice;
		if(data.key) delete data.key;
		
		this.setData({
			nationIndex: null,
			brandIndex: null,
			price: null,
			inputVal: null,
		});
	},
	
	
	//--- 获取卡类列表 ---
	getPlusCardType: function (func) {
	  var storid = os.stoid;
	  var th = this;
	  getApp().request.promiseGet("/api/weshop/plus/vip/mem/bership/list?" + "storeId=" + storid,
	    {}).then(res => {
	
	      if(res.data.code!=0 || !res.data.data){
	        var ob = {
	            "card_list": [],
	            "name_map": ""
	        };
	        func(ob);
	        return false;
	      }
	
	      var plusCard = res.data.data;
	      var arr = [1219, 2089, 3031];
	      var new_arr = new Array();
	      var card_name_map = new Map();
	
	      var user = getApp().globalData.userInfo;
	      if(plusCard) {
	        for (var i = 0; i < plusCard.length; i++) {
	          if ((!user || user.card_field == null || user.card_field == "") && (plusCard[i].IsStopBuy == true)) {
	            continue;
	          }
	          var name = "card" + plusCard[i].CorrPrice.toLowerCase();
	          card_name_map.set(name, plusCard[i].CardName);
	          new_arr.push(plusCard[i]);
	
	        }
	      }
	      var ob = {
	        "card_list": new_arr,
	        "name_map": card_name_map
	      };
	      func(ob);
	    })
	},
})