// pages/regular_visit_details/regular_visit_details.js
const {
	userWhiteHandleVisitList,
	userWhiteGetSnList,
	visitoryDownFaceAgain,
	visitoryVisitList
} = require('../../utils/api/api')
const app = getApp()
import international from '../../international/appointment_scence/index'
const {
	throttle
} = require("../../utils/throttle/throttle");
import QRCode from '../../utils/util/weapp-qrcode'

Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		//国际化语言包
		international: international,
		//中英文配置
		language: app.data.language,
		//相关信息
		regularList: null,
		//通用二维码
		qrCode1: "",
		//梯控二维码
		qrCode2: "",
		//单子当前时效状态 1-已失效 2-未到时间 3-正常
		qrCodeType: null,
		// 通道权限列表--设备列表
		machineList: [],
		snListLength: null,
		snList: null,
		isRegular: false,
		// 人员类型列表
		personTypeList: [{
			id: 0,
			name_ch: '访客',
			name_en: 'visit',
		},
		{
			id: 1,
			name_ch: '同事',
			name_en: 'friend',
		},
		{
			id: 2,
			name_ch: '亲属',
			name_en: 'family',
		},
		],
		personnelType: 0,
		//备注
		remark: '', 
		//2同意1拒绝
		reviewStatus: 2, 
		//1：申请记录；2：邀请记录；3.拜访信息
		clickPage: 1, 
		//是否显示下发按钮
		showBtn: true,
	},
	getShowBtn(n) {
		this.setData({
			showBtn: n.detail
		})
	},
	// 常客获取楼宇的设备列表(sn和name)
	userWhiteGetSnList() {
		let adminInfo = this.data.usedAdminInfo
		if (adminInfo) {
			userWhiteGetSnList({
				adminId: adminInfo.buildingAdminId,
				companyId: adminInfo.companyAdminId
			}).then(res => {
				this.setData({
					machineList: res.data
				})
			})
		}
	},
	//获取开始时间
	getValue(e) {
		var {
			form
		} = this.data;
		switch (e.currentTarget.dataset.type) {
			case 'snList':
				this.setData({
					snList: e.detail,
					snListLength: e.detail.length
				})
				break;
			case 'personnelType':
				this.setData({
					personnelType: e.detail,
				})
				break

			default:
				form[e.currentTarget.dataset.type] = e.detail
				break;
		}
	},

	// 打开通道权限弹出框
	showSN() {
		this.setData({
			chooseSN: true
		})
	},
	// 选择通过/拒绝
	chooseFun(e) {
		this.setData({
			reviewStatus: e.currentTarget.dataset.type,
			remark: '',
		})
	},
	// 备注
	onInput(e) {
		this.setData({
			remark: e.detail
		})
	},
	//点击提交按钮
	handle(e) {
		let {
			snList,
			regularList,
			remark,
			reviewStatus,
			personnelType
		} = this.data
		wx.requestSubscribeMessage({
			tmplIds: ['sYVZwmwu3gGNF4Ywjo0qgx-Gu7MEj59EDJvmOaQPVA0'],
			success(res) {
				let data = {
					snList: snList || [],
					reviewStatus,
					userVisitorListDetailId: regularList.userVisitorListDetailId,
					personnelType,
					remark,
				}
				userWhiteHandleVisitList(data).then(res => {
					//提交失败
					if (res.code != 200) {
						wx.showToast({
							title: res.msg,
							icon: 'none'
						})
						return;
					}
					//提交成功
					wx.showModal({
						title: '提醒',
						content: '操作成功！',
						showCancel: false,
						success(res) {
							wx.navigateBack({
								delta: 1,
							})
						}
					})
				})
			}
		})
	},
	// 访客重新下发
	visitoryDownFaceAgain: throttle(function () {
		visitoryDownFaceAgain({
			userVisitorListDetailId: this.data.regularList.userVisitorListDetailId
		}).then(res => {
			if (res.code === 200) {
				wx.showToast({
					title: '下发成功!',
					icon: 'none'
				})
			} else {
				wx.showToast({
					title: res.msg,
					icon: 'none'
				})
			}

		})
	}, 5000),
	//再次邀请
	inviteAgain() {
		let that = this;
		that.data.flag = 1;
		return new Promise((reslove)=>{
			reslove({
				title: '您收到一个来自' + that.data.regularList.visiteeXm + '邀请函',
				path: '/pages/visitor_make/visitor_make?userVisitorDetailId=' + that.data.regularList.userVisitorListDetailId,
				imageUrl: '../../static/comment/invitation.jpg',
			})
		})
	},
	//创建二维码
	creatQrCode(type, text) {
		if (!text) {
			return;
		};
		let that = this;
		//数据 - canvasId 对应对象
		let obj = {
			qrCode1: "myQrcode1",
			qrCode2: "myQrcode2"
		}
		new QRCode(obj[type], {
			text: text,
			width: 176, //canvas 画布的宽
			height: 176, //canvas 画布的高
			padding: 0, // 生成二维码四周自动留边宽度，不传入默认为0
			correctLevel: QRCode.CorrectLevel.L, // 二维码可辨识度
			callback: (res) => {
				that.setData({
					[type]: res.path,
				})
			}
		})
	},
	//请求接口查询单子状态
	getRecordInfo() {
		let data = {
			data: {
				userId: this.data.regularList.userId,
				userVisitorListDetailId: this.data.regularList.userVisitorListDetailId,
			},
			pageNum: 1,
			pageSize: 1,
		}
		visitoryVisitList(data).then(res => {
			this.checkRecordStatus(res.data.list[0]);
		})
	},
	//查询单子的审核状态和签离状态来决定是否渲染基础信息
	checkRecordStatus(newData) {
		this.checkRecordTimeStatus(newData);
		//审核状态是未变更&&签离状态是未变更
		if ((newData.reviewStatus == this.data.regularList.reviewStatus) && (newData.isSignOut == this.data.regularList.isSignOut)) {
			return;
		}
		//审核状态是已变更&&签离状态是已变更
		this.setData({
			regularList: newData
		});
	},
	//查询单子的时效性来决定是否渲染二维码数据
	checkRecordTimeStatus(newData) {
		//未到开始时间&与目前状态不同
		var now = Date.now();
		var startTime = Date.parse(new Date(newData.startTime+':00'));
		if (now < startTime) {
			if(this.data.qrCodeType != 2) {
				this.setData({
					qrCodeType: 2
				})
			}
			return;
		}
		//大于结束时间&与目前状态不同
		var endTime = Date.parse(new Date(newData.endTime+':00'));
		if (now > endTime) {
			if(this.data.qrCodeType != 1) {
				this.setData({
					qrCodeType: 1
				})
			}
			return;
		}
		//单子时效性正常，但与目前状态相同
		if (this.data.qrCodeType == 3) {
			return;
		}
		this.setData({
			qrCodeType: 3
		})
		this.creatQrCode('qrCode1', newData.commonQrCode);
		this.creatQrCode('qrCode2', newData.ladderQrCode);
	},
	//基础数据使用
	doCheckInfo(options) {
		this.data.usedAdminInfo = app.data.adminInfo;
		this.data.userInfo = app.data.userInfo;
		//赋值页面业务类型&数据&是否是常客进入
		this.setData({
			clickPage: Number(options.clickPage || 0),
			regularList: JSON.parse(options.list),
			isRegular: options.isRegular ? true : false,
		})
		//常客审核申请记录-1
		if (options.clickPage == 1) {
			this.userWhiteGetSnList();
			this.checkRecordStatus(this.data.regularList);
		}
		//常客查看邀请记录-2
		if (options.clickPage == 2) {
			this.checkRecordStatus(this.data.regularList);
		}
		//访客查看拜访记录-3
		if (options.clickPage == 3) {
			this.checkRecordStatus(this.data.regularList);
			//设置轮询检查单子时效以及单子状态
			this.data.recordTimer = setInterval(() => {
				this.getRecordInfo()
			}, 5000)
		}
	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		console.log(options);
		this.doCheckInfo(options);
	},
	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {
		this.setData({
			language: app.data.language
		});
		if (this.data.flag == 1) {
			this.data.flag = null;
			wx.showModal({
				content: '分享邀请函成功',
				showCancel: false,
				complete: (res) => {
					wx.navigateBack({
						delta: 1,
					})
				}
			})
		}
	},

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

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {
		clearInterval(this.data.recordTimer)
	},

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

	},

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

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function () {
		let userInfo = app.data.userInfo
		let promise = this.inviteAgain()
		return {
			title: '您收到一个来自' + userInfo.username + '邀请函',
			path: '/pages/visitor_make/visitor_make?userVisitorDetailId=null',
			imageUrl: '../../static/comment/invitation.jpg',
			promise
		}
	}
})
