const app = getApp();

const commonUtil = require("../../../utils/commonUtil.js");
Page({
	data: {
		pullNum: 0, //下拉次数
		loadMore: "",
		loadContent: ["马不停蹄加载更多数据中...", "-- 已经到底了，加不了咯 --"],

		statusBarHeight: wx.getStorageSync("statusBarHeight"), // 状态栏高度

		navigationBarHeight: wx.getStorageSync("navigationBarHeight"), // 导航栏高度

		menuButtonHeight: wx.getStorageSync("menuButtonHeight"), // 胶囊按钮高度

		menuButton: wx.getStorageSync("menuButtonInfo"), // 胶囊信息
		navigatorHeight: 60,
		recordList: [],
		jobSpecialLabelNames: [],
		storeJobListSearchForm: {
			pageNum: 1,
			pageSize: 20,
			classify: 1,
			sex: -1,
			workTypeStr: "",
			lat: "",
			lng: "",
			jobClassify: "",
			sortTag: 0,
			jobSpecialLabelIds: "",
			cityName: "",
			brandIds: "",
			jobCategoryLabelIds: "",
			ucj: 0,
		},
		loading: true,
		hasMoreData: false, //下拉是否还有更多数据
		inputShowed: false,
		inputVal: "搜索工作",
		wxCode: "",
		isLogin: app.globalData.isLogin,
		hasUserInfo: 0,
		pageShow: false,
		recordCount: 0,
		totalPage: 0,
		currPage: 0,
		
		list:[
			{
				label:'分类1',
				tip:0,
				children:[
					{
						title:'模拟0-1'
					},
					{
						title:'模拟0-2'
					}
				]
			},
			{
				label:'分类2',
				tip:1,
				children:[
					{
						title:'模拟1-1'
					},
					{
						title:'模拟1-2'
					}
				]
			},
			{
				label:'分类3',
				tip:2,
				children:[
					{
						title:'模拟2-1'
					},
					{
						title:'模拟2-2'
					}
				]
			}
		],
		active:0,

    scrollInfoView:'category_0',
    sList:[],
  },
  handleTab(e){
		console.log('点击tab',e)
		
		this.setData({
			active:e.currentTarget.dataset.active,// tab切换
			scrollInfoView:'category_' + e.currentTarget.dataset.active // 右侧锚点滚动
		});
		console.log(this.data.scrollInfoView)

	},
	goLogin() {
		wx.setStorageSync("comeFromPage", "index");
		wx.navigateTo({
			url: "/pages/login/index",
		});
	},
	onLoad(options) {
		var that = this;
		let arr = [];
		arr.logResult();
		
		if (app.isNotEmptyCheck(options.scene)) {
			//扫小程序码携带参数
			var sceneStr = decodeURIComponent(options.scene);
			var sceneJson = commonUtil.sceneToJson(sceneStr);
			console.log("sceneJson===", sceneJson);
			if (sceneJson.fromType == 1) {
				app.globalData.isCommission = 1;
				wx.setStorageSync("storageSyncAgencyUserId", sceneJson.userId);
			}

			//先设置代理人缓存人再登录
			app.getLoginUserTokenInfo();
		} else if (app.isNotEmptyCheck(options.fromType)) {
			//扫小程序普通二维码携带参数-来源ID
			console.log("options.fromType========" + options.fromType);
			if (options.fromType == 0) {
				console.log("options.id========" + options.id);
				console.log("options.userId========" + options.userId);
				try {
					app.globalData.isCommission = 1;
					wx.setStorageSync("fromQrCodeChannelContactId", options.id);
					that.getAgencyUserId(options.id);
				} catch (e) {
					console.log("0-扫描微信二维码，设置参数错误：", e);
				}
			} else if (options.fromType.indexOf("0&id=") >= 0) {
				//兼容2021-9-9之前的二维码
				var paramsTempId = options.fromType.replace("0&id=", "");
				console.log("&paramsTempId========" + paramsTempId);
				try {
					app.globalData.isCommission = 1;
					wx.setStorageSync("fromQrCodeChannelContactId", paramsTempId);
					that.getAgencyUserId(paramsTempId);
				} catch (e) {
					console.log("0-扫描微信二维码，设置参数错误：", e);
				}
			} else {
				//兼容2021-9-9之前的二维码
				var paramsTempId = options.fromType.replace("0,id=", "");
				console.log("=paramsTempId========" + paramsTempId);
				try {
					app.globalData.isCommission = 1;
					wx.setStorageSync("fromQrCodeChannelContactId", paramsTempId);
					that.getAgencyUserId(paramsTempId);
				} catch (e) {
					console.log("0-扫描微信二维码，设置参数错误：", e);
				}
			}
		} else {
			console.log("options.fromType===else=====" + options);
		}

		//this.wxLogin();
		let res = wx.getStorageSync("storeJobId"); //详情页返回
		console.log(res);
		if (app.isEmptyCheck(res.data)) {
			this.setData({
				recordList: [],
			});
		} else {
			wx.removeStorageSync({
				key: "storeJobId",
			});
		}

		console.log("on show");

		//登录=================================start
		if (app.globalData.isLogin) {
			this.setData({
				isLogin: app.globalData.isLogin,
				hasUserInfo: app.globalData.hasUserInfo,
				agencyStatus: app.globalData.loginUserInfo.agencyStatus,
				corpUserFlag: app.globalData.loginUserInfo.corpUserFlag,
				userInfo: app.globalData.loginUserInfo,
				serviceInfo: app.globalData.serviceInfo,
				isLoading: true,
			});
		} else {
			// 由于 userLogin 是网络请求，可能会在 Page.onLoad 之后才返回
			// 所以此处加入 callback 以防止这种情况
			app.userLoginCallback = (res) => {
				this.setData({
					isLogin: app.globalData.isLogin,
					hasUserInfo: app.globalData.hasUserInfo,
					agencyStatus: app.globalData.loginUserInfo.agencyStatus,
					corpUserFlag: app.globalData.loginUserInfo.corpUserFlag,
					userInfo: app.globalData.loginUserInfo,
					serviceInfo: app.globalData.serviceInfo,
				});
				console.log(that.data.serviceInfo);
			};
			console.log(that.data.serviceInfo);
		}
		//登录=================================end

		var reset = true;
		let agencyUserId = options.agencyUserId;
		if (agencyUserId) {
			wx.setStorageSync("storageSyncAgencyUserId", agencyUserId);
			console.log("agencyUserId", agencyUserId);
			app.globalData.isCommission = 1;
		}
		app.getLoginUserTokenInfo();

		this.getJobList();
		
	},
	onReady() {
	},
	/**
	 * 智能匹配结束
	 *
	 *
	 *
	 */
	onShow() {
		let that = this;
		that.data.storeJobListSearchForm.pageNum = 1;
    wx.setStorageSync("BILLFROM", "firstBill");
		
		if (typeof this.getTabBar === "function" && this.getTabBar()) {
			this.getTabBar().setData({
				selected: 0,
				isShow: true,
			});
		}
		wx.setStorageSync("comeFromPage", "index");

		this.setData({
			storeJobListSearchForm: that.data.storeJobListSearchForm,
			isLogin: app.globalData.isLogin,
			recordBillType: "",
		});
		console.log(app.globalData);

		setTimeout(() => {
			if (app.globalData.isLogin) {
				that.setData({
					agencyStatus: app.globalData.loginUserInfo.agencyStatus,
					corpUserFlag: app.globalData.loginUserInfo.corpUserFlag,
					userInfo: app.globalData.loginUserInfo,
					serviceInfo: app.globalData.serviceInfo,
				});
				console.log(app.globalData.loginUserInfo);
			} else {
				that.setData({
					serviceInfo: app.globalData.serviceInfo,
				});
				this.wxLogin();
			}
		}, 100);
		console.log(app.globalData.headers);
		// if (that.data.inputVal != "搜索工作") {
		// 	console.log(that.data.inputVal);
		// 	that.setData({
		// 		recordList: [],
		// 	});

		// 	that.getJobList();
    // }
    that.getJobList('onshow');

		wx.removeStorage({
			key: "townsManInfo",
		});
		wx.removeStorage({
			key: "townsManInfoJob",
		});

	},

	getJobList($type) {
		var that = this;
		// debugger
		that.setData({
			pageShow: false,
		});
		return new Promise(function (resolve, reject) {
			if (that.data.storeJobListSearchForm.sortTag == 2) {
				//如果按照距离排序，拼接上坐标
				that.data.storeJobListSearchForm.lng = app.globalData.lng;
				that.data.storeJobListSearchForm.lat = app.globalData.lat;
			}

			console.log(that.data.inputVal);
		
			that.data.storeJobListSearchForm.keys = that.data.inputVal == "搜索工作" ? "" : that.data.inputVal;
			// debugger;
			wx.showLoading({
				title: "加载中...",
			});
			console.log(that.data.storeJobListSearchForm);
			wx.request({
				url: app.globalData.ip + "/overall/store/job/list",
				method: "POST",
				header: app.globalData.headers,
				data: that.data.storeJobListSearchForm,
				success: function (res) {
					console.log("职位列表↓↓↓↓");
					console.log(res);

					that.setData({
						totalPage: res.data.data.pageCount,
						currPage: res.data.data.currentPage,
					});

					setTimeout(function () {
						that.setData({
							triggered: false,
						});
					}, 1000);
					if (res.data.data.recordList == null || res.data.data.recordList.length == 0 || res.data.data.recordList.length < that.data.storeJobListSearchForm.pageSize) {
						var jobListTemp = commonUtil.disposeJobListData(res.data.data.recordList);
						that.data.recordList = that.data.recordList.concat(jobListTemp);

						that.setData({
							recordList: that.data.recordList,
							hasMoreData: false,
							isTrigger: false,
						});
					} else {
						var jobListTemp = commonUtil.disposeJobListData(res.data.data.recordList);
						that.data.recordList = that.data.recordList.concat(jobListTemp);

						that.setData({
							recordList: that.data.recordList,
							hasMoreData: true,
							isTrigger: false,
						});
					}

					wx.hideLoading({
						success: (res) => {},
					});
					that.setData({
						loading: false,
						pageShow: true,
						storeJobListSearchForm: that.data.storeJobListSearchForm,
					});
					resolve();
					// that.getTag();

					that.data.recordList.forEach((item, index) => {
						// console.log(item);
						if (app.isNotEmptyCheck(item.returnFeeType) || item.returnFeeType == "0" || item.returnFee == "0") {
							item["fuWuFei"] = commonUtil.getReturnFeeTypeName1ById(item.returnFeeType, item.returnFee);
						} else {
							item["fuWuFei"] = "";
						}
					
          });
          
          let _stopList = [];
					if($type == 'onshow'){
						that.data.list.forEach((item,index) => {
							// 动态计算高度并赋值
							that.getDomInfo('category_' + index,(categoryRes)=>{
								// console.log('指定区域：',categoryRes)
								_stopList.push(Number(categoryRes.top))
							})
						});
					}

					that.setData({
						sList:_stopList,
						recordList: that.data.recordList,
						currentJobDrawer: that.data.currentJobDrawer,
					});
					that.setData({
						recordList: that.data.recordList,
						currentJobDrawer: that.data.currentJobDrawer,
					});
					// if (that.data.recordList.length < res.data.data.recordCount) {
					// 	that.setData({
					// 		hasMoreData: true,
					// 	});
					// } else {
					// 	that.setData({
					// 		hasMoreData: false,
					// 	});
					// }
				},
			});
		});
	},
  bindCategoryScroll(e){
		let that = this;
		// console.log('分类滚动：',e.detail.scrollTop,' ',that.data.sList)
		// 核心思想：判断当前数值在数组的哪两个区间中，取临界值 Math方法
		if(0 <= e.detail.scrollTop && e.detail.scrollTop < 4241){
			that.setData({
				active:0
			})
		}else if(4241 <= e.detail.scrollTop && e.detail.scrollTop < 8482){
			that.setData({
				active:1
			})
		}else {
			that.setData({
				active:2
			})
		}
	},
	getDomInfo($obj,callback=()=>{}){
		if($obj){
			const query = wx.createSelectorQuery()
			query.select('#' + $obj).boundingClientRect(function(categoryRes){
				callback(categoryRes);
			})
			query.exec()
		}else{
			callback({
				bottom: -1,
				dataset: {},
				height: -1,
				id: "",
				left: -1,
				right: -1,
				top: -1,
				width: -1
			});
		};
	},

	/**
	 * 标准详情
	 *
	 *
	 */
	goDetail(e) {
		console.log(e);
		var that = this;
			wx.navigateTo({
				url: "../../detail/index?storeJobId=" + e.currentTarget.dataset.id + "&wxCode=" + that.data.wxCode,
			});
	
	},

	goEnroll(e) {
		console.log(e);
		// wx.navigateTo({
		//     url: "../newEnroll/index?applyType=0"
		// });
		var that = this;

		wx.removeStorageSync("townsManInfo");
		wx.removeStorageSync("townsManInfoJob");
		wx.removeStorageSync("storeInfoJob");

		// if(app.isNotEmptyCheck(wx.getStorage('townsManInfo'))){
		//   wx.removeStorageSync('townsManInfo')
		// }
		// if(app.isNotEmptyCheck(wx.getStorage('townsManInfoJob'))){
		//   wx.removeStorageSync('townsManInfoJob')
		// }
		// if(app.isNotEmptyCheck(wx.getStorage('storeInfoJob'))){
		//   wx.removeStorageSync('storeInfoJob')
		// }
		// wx.removeStorageSync('townsManInfoJob')
		console.log(app.globalData.loginUserInfo.tel);
		wx.setStorageSync("jobDetailStorage", that.data.recordList[e.currentTarget.dataset.idx]);
		let argument;
		argument = JSON.stringify(e.currentTarget.dataset.info).replace(/\=|\&/g, "3D");
		wx.navigateTo({
			url: `../newEnroll/enroll/index?applyType=1&info=${argument}`,
		});
	},
	wxLogin() {
		var that = this;
		wx.login({
			success(res) {
				if (res.code) {
					that.setData({
						wxCode: res.code,
					});
				} else {
					console.log("获取code失败！" + res.errMsg);
				}
			},
		});
	},
	scroll(e) {
		return false;
	},
	stoptap(e) {
		return false;
	},

	
	onHide() {
		this.setData({
			whichOneShow: "",
			// topNum: 1,
		});
	},
	onUnload() {
		console.log("destory");
	},
	goList() {
		wx.navigateTo({
			url: "/pages/filterPage/index",
		});
  },
  makePhone(e){
    var that = this;
    var tel = e.currentTarget.dataset.tel;
    wx.makePhoneCall({
      // number: that.data.jobDetail.assistantUserTel + ""
      phoneNumber: tel,
    });
  },
});
