// pages/regular_register/regular_register.js
import international from '../../international/appointment_scence/index'
const {
	getBuildingList,
	userWhiteCheck,
	getCompanyList,
	getAdminConfig,
} = require('../../utils/api/api')
const {
	throttle
} = require("../../utils/throttle/throttle");
import {
	getContextByAdminId, selectContextByCardId
} from '../../utils/api/customField'
const app = getApp()

Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		//国际化语言包
		international: international,
		//中英文配置
		language: null,
		// 功能列表
		component_list: [{
			id: 1,
			name_ch: '重新下发',
			name_en: 'Again issued',
			icon: '../../static/mine/deliver_again.png',
			url: ''
		},
		{
			id: 2,
			name_ch: '认证信息',
			name_en: 'Authentication',
			icon: '../../static/mine/certification_msg.png',
			url: ''
		},
		{
			id: 3,
			name_ch: '邀请人员',
			name_en: 'Invite',
			icon: '../../static/mine/my_appointment.png',
			url: ''
		}],
		//楼宇列表
		buildingList: [],
		buildingAdminId: null,
		buildingName: null,
		buildingIndex: null,
		//企业列表
		companyList: [],
		companyAdminId: null,
		companyName: null, 
		companyIndex: null,
		//允许被显示的企业列表
		newCompanyList: [],
		//用户基础信息
		userInfo: null,
		//可供使用的账号信息
		usedAdminInfo: null,
		//是否禁用选择楼宇企业
		disableSelectAdminInfo: false,
		//是否禁用人员认证按钮
		isDisabled: false,
		//楼宇账号是否开启自定义字段
		isShowApplet: false,
		//是否完成自定义字段的填写
		isFillFields: false,
		//自定义字段内容
		customField: null,
		//是否禁用提交按钮
		isSubmit: false,
		//是否能显示功能区
		showMyFun: false,
		//登录参数列表
		needLoginList: [],
		//是否输入手机号 0-否 1-需要
		needPhone: null,
		//是否需要照片 0-否 1-需要
		needPhoto: null,
		//是否需要实名 0-否 1-需要
		needRealname: null,
		//申报下发倒计时
		timeCount: null,
	},
	//获取楼宇列表: tip1-仅一个楼宇则自动填充 tip2-多个楼宇则判断是否扫码或者缓存进入
	getBuildingList() {
		//恢复初始态
		this.setData({
			buildingList: [],
			buildingIndex: null,
			buildingAdminId: null,
			buildingName: null,
			companyList: [],
			companyAdminId: null,
			companyName: null,
			companyIndex: null
		});
		getBuildingList().then(res => {
			let buildingIndex = null;
			//无楼宇，异常
			if (res.data.length < 1) {
				wx.showToast({
					title: '未查询到可用楼宇，请联系管理员',
					icon: "none"
				})
				return;
			}
			//多个楼宇,判断是否有可使用的账号信息
			if (res.data.length > 1 && this.data.usedAdminInfo) {
				let index = res.data.findIndex(item => {
					return item.adminId == this.data.usedAdminInfo.buildingAdminId
				})
				//可使用的信息无效
				if (index <= -1) {
					wx.removeStorageSync('adminInfo');
					app.data.adminInfo = null;
					app.data.temporaryAdminInfo = null;
					return;
				}
				//可使用的信息有效，自动选中
				if (index > -1) {
					buildingIndex = index
					this.setData({
						buildingAdminId: res.data[index].adminId,
						buildingName: res.data[index].name
					})
				}
			}
			//仅一个楼宇，自动填充
			if (res.data.length == 1) {
				buildingIndex = 0;
				this.setData({
					buildingAdminId: res.data[0].adminId,
					buildingName: res.data[0].name
				})
			}
			//有选中的楼宇id
			if (buildingIndex != null) {
				//获取企业列表
				this.getCompanyList();
				//获取是否开启自定义字段
				this.getContextStatusByAdminId(this.data.buildingAdminId)
				//获取楼宇账号配置
				this.getAdminConfig()
			}
			this.setData({
				buildingList: res.data,
				buildingIndex: buildingIndex
			});
		})
	},
	// 根据选择的楼宇查找企业列表: tip1-仅一个企业则自动填充 tip2-多个企业则判断是否扫码或者缓存进入
	getCompanyList() {
		wx.showLoading({
			title: '获取企业列表...',
		});
		//清空原有的选择
		this.setData({
			companyList: [],
			companyAdminId: null,
			companyName: null,
			companyIndex: null
		})
		let data = {
			adminId: this.data.buildingAdminId,
		}
		getCompanyList(data).then(res => {
			wx.hideLoading()
			//接口异常
			if (!res.code === 200) {
				wx.showToast({
					title: res.msg,
					icon: 'none'
				});
				return;
			}
			//楼宇下无企业，异常
			if (res.data.length <= 0) {
				wx.showToast({
					title: '该楼宇下暂无企业,请联系楼宇管理员添加',
					icon: 'none'
				});
				return;
			}
			//楼宇下有企业
			let companyIndex = null
			let newCompanyList = []
			if (res.data.length > 0) {
				//列表只显示可被搜索的企业
				res.data.forEach(item => {
					if (item.isCanSearch) {
						newCompanyList.push(item)
					}
				});
			}
			//没有可被搜索的企业
			if (newCompanyList.length <= 0) {
				wx.showToast({
					title: '该楼宇下暂无企业',
					icon: 'none'
				});
				return;
			}
			//可被搜索的企业数量大于 0 && 有可被使用的账号信息
			if (newCompanyList.length > 1 && this.data.usedAdminInfo && this.data.usedAdminInfo.companyAdminId) {
				let index = res.data.findIndex(item => {
					return item.adminId == this.data.usedAdminInfo.companyAdminId
				})
				//可使用的信息无效
				if (index <= -1) {
					wx.removeStorageSync('adminInfo');
					app.data.adminInfo = null;
					app.data.temporaryAdminInfo = null;
					return;
				}
				//可使用的信息有效
				if (index > -1) {
					companyIndex = index
					this.setData({
						companyAdminId: res.data[index].adminId,
						companyName: res.data[index].name,
					})
				}
			}
			//可被搜索的企业数量为 1 自动填充
			if (newCompanyList.length === 1) {
				companyIndex = 0;
				this.setData({
					companyAdminId: newCompanyList[0].adminId,
					companyName: newCompanyList[0].name
				})
			}
			this.setData({
				companyList: res.data,
				companyIndex: companyIndex,
				newCompanyList,
			})
			// this.getContextByAdminId()
		});
	},
	// 获取账号的配置信息
	getAdminConfig() {
		getAdminConfig({
			adminId: this.data.buildingAdminId
		}).then(res => {
			this.setData({
				needPhone: res.data.whitelistAppPhone,
				needPhoto: res.data.whitelistAppPhoto,
				needRealname: res.data.whitelistAppRealname,
				needLoginList: res.data.whitelistAppLoginList,
			});
			//根据账号配置判断是否有可使用的用户信息
			this.jugdeInfo();
		})

	},
	//获取是否有自定义字段
	getContextStatusByAdminId(orgId) {
		getContextByAdminId(orgId).then(res => {
			if (res.code != 200) {
				wx.showToast({
					title: res.msg,
					icon: 'none'
				})
				return;
			}
			this.setData({
				isShowApplet: res.data,
				isFillFields: !res.data,
			})
			this.canOperation()
			//若存在自定义字段，则拉取自定义字段内容
			if(res.data) {
				this.getContextByAdminId()
			}
		})
	},
	//选择楼宇或企业
	getValue(e) {
		switch (e.currentTarget.dataset.type) {
			case 'buildingAdminId':
				this.setData({
					buildingAdminId: e.detail.adminId,
					buildingName: e.detail.name,
				})
				this.getCompanyList()
				this.getContextStatusByAdminId(e.detail.adminId)
				this.getAdminConfig()
				break;
			case 'companyAdminId':
				this.setData({
					companyAdminId: e.detail.adminId,
					companyName: e.detail.name
				});
				this.getContextByAdminId();
				break;
			default:
				break;
		};
		this.canOperation()
	},
	// 获取组件抛出的认证状态-实名认证
	getCertificationState(e) {
		if (!e.detail) {
			wx.showToast({
				title: '认证失败了，再试一次吧~',
				icon: 'none'
			});
			return;
		}
		wx.showToast({
			title: '认证成功~',
			icon: 'none'
		})
		this.setData({
			isDisabled: true,
		});
		this.updateSetting()
		this.getContextByAdminId();
		//判断是否完成自定义字段的填写，完成则直接提交
		if (this.data.isFillFields) {
			this.sure();
		}
	},
	// 获取组件抛出的认证状态-ocr
	getUpdateState(e) {
		if (!e.detail) {
			return;
		}
		this.updateSetting()
		this.getContextByAdminId()
		//判断是否完成自定义字段的填写，完成则直接提交
		if (this.data.isFillFields) {
			this.sure();
		}
	},
	// 获取用户填写的自定义字段内容
	getContextByAdminId() {
		if (!this.data.companyAdminId || !this.data.userInfo) {
			return;
		}
		selectContextByCardId(this.data.buildingAdminId, this.data.userInfo.userId).then(res => {
			this.setData({
				customField: res.data
			})
			this.canOperation()
		})
	},
	// 判断提交按钮是否禁用
	canOperation() {
		let {
			buildingAdminId,
			companyAdminId,
			isSubmit,
			isFillFields,
		} = this.data;
		isSubmit = (buildingAdminId != null && companyAdminId != null && isFillFields) ? true : false;
		this.setData({
			isSubmit
		})
	},
	// 更新个人信息
	updateSetting() {
		//是否禁用选择楼宇企业选择栏
		let disableSelectAdminInfo = app.data.adminInfo || (app.data.temporaryAdminInfo && app.data.temporaryAdminInfo.companyAdminId);
		this.setData({
			showMyFun: app.data.adminInfo ? true : false,
			isDisabled: app.data.userInfo ? true : false,
			disableSelectAdminInfo: disableSelectAdminInfo,
			usedAdminInfo: this.data.usedAdminInfo || app.data.adminInfo || app.data.temporaryAdminInfo,
			userInfo: app.data.userInfo
		});
	},
	// 判断是否填写完成
	isFillFields(e) {
		if (e.detail == false) {
			this.data.isFillFields = false;
		} else {
			this.data.customField = e.detail;
			this.data.isFillFields = true;
		}
		this.canOperation()
	},
	// 提交
	sure() {
		let {
			buildingAdminId,
			buildingName,
			companyAdminId,
			companyName,
			userInfo,
			isFillFields,
			customField
		} = this.data
		if (!buildingAdminId || !companyAdminId || !userInfo.userId) {
			wx.showToast({
				title: '请先将信息填写完整',
				icon: 'none'
			})
			return;
		}
		let data = {
			adminId: buildingAdminId,
			userId: this.data.userInfo.userId,
			companyAdminId: companyAdminId,
			type: app.data.qrcodeInfo && app.data.qrcodeInfo.type ? 1 : 0,
			addCustomList: isFillFields ? customField : null,
		}
		userWhiteCheck(data).then(res => {
			if (res.code !== 200) {
				wx.showToast({
					title: res.msg,
					icon: 'none'
				})
				return;
			}
			let adminInfo = {
				buildingAdminId: buildingAdminId,
				buildingName: buildingName,
				companyAdminId: companyAdminId,
				companyName: companyName,
				userWhitelistId: res.data[0].userWhitelistId,
				official: true
			}
			wx.setStorageSync('adminInfo', adminInfo);
			app.data.adminInfo = adminInfo;
			this.updateSetting();
			wx.showModal({
				title: '提示',
				content: '恭喜绑定企业成功~',
				showCancel: false,
				success() {}
			});
		});
	},
	// 更改信息
	goToChange() {
		wx.showModal({
			content: '重新认证后会清除目前的认证信息，确认要重新认证吗？',
			cancelText: "我再想想",
			complete: (res) => {
				if (res.confirm) {
					wx.removeStorageSync('adminInfo');
					wx.removeStorageSync('userInfo');
					wx.removeStorageSync('visitorUserInfo');
					wx.removeStorageSync('visitorExtraInfo');
					app.data.adminInfo = null;
					app.data.userInfo = null;
					app.data.visitorUserInfo = null;
					app.data.visitorExtraInfo = null;
					this.doCheckAdmin();
				}
			}
		})
	},
	//其他功能跳转
	goto(e) {
		let id = e.currentTarget.dataset.id
		let url = ''
		if (id == 1) {
			this.doPass()
			return
		} else if (id == 2) {
			url = '/pages/regular_msg/regular_msg'
		} else if (id == 3) {
			wx.requestSubscribeMessage({
				tmplIds: ['261lS0M-ugfPHTOFeTFS6IN8WQshNOCbrPEC51OONy8'],
				success(res) { }
			})
			url = '/pages/regular_invite/regular_invite'
		}
		wx.navigateTo({
			url
		})
	},

	//人脸下发
	doPass: throttle(function () {
		let data = {
			adminId: this.data.usedAdminInfo.buildingAdminId,
			companyAdminId: this.data.usedAdminInfo.companyAdminId,
			userId: this.data.userInfo.userId,
		}
		wx.showLoading({
			title: '申报中..',
		});
		userWhiteCheck(data).then((res) => {
			if (res.code == 200) {
				this.data.timeCount = 30
				this.countDown()
				wx.showModal({
					content: '恭喜申报成功，您已获得闸机快速通行权限，如有疑问，请就近联系管理人员',
					showCancel: false,
				})
			} else {
				wx.showModal({
					content: res.msg,
					showCancel: false,
				})
			};
		})
			.catch(err => { })
			.finally(() => {
				wx.hideLoading()
			})
	}, 30000),
	//申报倒计时
	countDown() {
		let {
			timeCount
		} = this.data;
		if (timeCount > 0) {
			setTimeout(() => {
				timeCount--
				this.setData({
					timeCount
				})
				this.countDown();
			}, 1000)
		}
	},
	//扫码账号信息和缓存的账号信息的处理
	doCheckAdmin() {
		//先渲染已有的人员信息和中英文配置
		this.setData({
			userInfo: app.data.userInfo,
			language: app.data.language
		})
		//临时账号信息&&常客账号信息不一致
		if ((app.data.temporaryAdminInfo && app.data.adminInfo) && app.data.temporaryAdminInfo.companyAdminId && (app.data.temporaryAdminInfo.companyAdminId !== app.data.adminInfo.companyAdminId)) {
			wx.showModal({
				content: `检测到您本次扫码为"${app.data.temporaryAdminInfo.companyName || "未知"}",与上次注册的"${app.data.adminInfo.companyName || "未知"}"不一致，是否按照本次的信息进行认证？`,
				cancelText: "使用上次",
				confirmText: "使用本次",
				complete: (res) => {
					if (res.cancel) {
						app.data.temporaryAdminInfo = null
					}
					if (res.confirm) {
						app.data.adminInfo = null;
						wx.removeStorageSync('adminInfo');
					};
					this.setData({
						usedAdminInfo: app.data.adminInfo || app.data.temporaryAdminInfo
					})
					this.getBuildingList();
					this.updateSetting();
				}
			})
			return;
			//临时账号信息&&常客账号信息其中一个有，或两个没有，或两个都有，但是信息一致
		} else {
			this.setData({
				usedAdminInfo: app.data.adminInfo || app.data.temporaryAdminInfo
			})
			this.getBuildingList();
			this.updateSetting();
		}
	},
	// 判断认证信息是否可以复用 userInfo <-----> visitorUserInfo
	jugdeInfo() {
		//判断是否有常客缓存信息
		if (app.data.userInfo) {
			this.checkInfo()
			return;
		}
		//判断是否有访客信息
		if (!app.data.visitorUserInfo) {
			return;
		}
		//判断访客信息的严格等级是否大于等于登录要求 实名认证>非实名
		if (!(!this.data.needRealname || app.data.visitorUserInfo.needRealname)) {
			return;
		}
		//判断已缓存的访客认证信息是否包含登录要求
		for (let index = 0; index < this.data.needLoginList.length; index++) {
			if (app.data.visitorUserInfo.needLoginList.indexOf(this.data.needLoginList[index]) <= -1) {
				return;
			}
		};
		wx.setStorageSync('userInfo', app.data.visitorUserInfo)
		app.data.userInfo = app.data.visitorUserInfo;
		this.updateSetting()
	},
	//判断常客缓存信息是否可以使用
	checkInfo() {
		//判断常客信息的严格等级是否大于等于登录要求 实名认证>非实名
		if (!(!this.data.needRealname || app.data.userInfo.needRealname)) {
			wx.showModal({
				content: '检测到账号登录条件已经变更为实名认证模式,请重新认证并绑定',
				complete: (res) => {
					wx.removeStorageSync('userInfo');
					app.data.userInfo = null;
					this.doCheckAdmin();
				}
			})
			return;
		}
		//判断已缓存的常客认证信息是否包含登录要求
		for (let index = 0; index < this.data.needLoginList.length; index++) {
			if (app.data.userInfo.needLoginList.indexOf(this.data.needLoginList[index]) <= -1) {
				wx.showModal({
					content: '检测到账号登录条件已增加,请重新认证并绑定',
					complete: (res) => {
						wx.removeStorageSync('userInfo');
						app.data.userInfo = null;
						this.doCheckAdmin();
					}
				})
				return;
			}
		};
	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		this.doCheckAdmin();
	},

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

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

	},

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

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

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

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

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