// pages/visitor_make/visitor_make.js
import {
	getBuildingList,
	getCompanyList,
	getUserWhiteByphoneAndAdminId,
	visitorySubmit,
	getVisitoryByUserVisitorListDetailId,
	getAdminConfig,
} from '../../utils/api/api'
import {
	getContextByAdminId, selectContextByCardId
} from '../../utils/api/customField'
import international from '../../international/appointment_scence/index'


const app = getApp()
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		//国际化语言包
		international: international,
		//中英文配置
		language: app.data.language,
		//是否禁用人员认证按钮
		isDisabled: false,
		//展示访客确认页面
		chooseOne: true,
		// swiper的index
		currentIndex: 0,
		// swiper滚动长度
		swiperDx: 0,
		// 拜访事由列表
		reasonList: [{
			name: '业务洽谈'
		},
		{
			name: '会议邀请'
		},
		{
			name: '施工安装'
		},
		{
			name: '探亲访友'
		},
		{
			name: '工作检查'
		},
		{
			name: '面试邀请'
		},
		{
			name: '快递外卖'
		},
		{
			name: '家政保洁'
		},

		],
		reasonIndex: 0,
		// 人员类型列表
		personTypeList: [{
			id: 0,
			name_ch: '访客',
			name_en: 'visitors',
		},
		{
			id: 1,
			name_ch: '同事',
			name_en: 'colleagues',
		},
		{
			id: 2,
			name_ch: '亲属',
			name_en: 'relatives',
		},
		],
		personTypIndex: 0,
		visitorUserInfo: null,
		// 提交表单
		form: {
			reason: '业务洽谈'
		},
		//所有楼宇列表
		all_buildingList: [],
		auditList: null,
		//1->访客自主提交 2->访客受邀
		type: 1,
		//传入组件的预约开始时间
		startTime: null,
		//所在楼宇是否禁用
		disableBuilding: false,
		//楼宇列表
		buildingList: [],
		buildingAdminId: null,
		buildingName: null,
		buildingIndex: null,
		//企业列表
		companyList: [],
		companyAdminId: null,
		companyName: null, //是否显示企业名称&存储企业名称
		companyIndex: null,
		//用户基础信息
		userInfo: null,
		//可供使用的账号信息
		usedAdminInfo: null,
		//是否禁用选择楼宇企业
		disableSelectAdminInfo: false,
		//登录参数列表
		needLoginList: [],
		//是否输入手机号 0-否 1-需要 
		needPhone: null,
		//是否需要照片 0-否 1-需要
		needPhoto: null,
		//是否需要实名 0-否 1-需要
		needRealname: null,
		//楼宇审核方式 1-常客审核 2-指定人员审核 
		buildingCheckType: 1,
		//受邀人手机号与本人手机号一致时禁用状态 true-禁用 false-不禁用
		disableComplete: false,
		// 步骤列表
		stepsList: [{
			name: '访客确认',
			name1: 'Visitors confirm',
			complete: false
		},
		{
			name: '拜访信息填写',
			name1: 'Visit information',
			complete: false
		}],
		//是否禁用拜访信息
		isAudit: false,
		//是否开启自定义字段
		isShowApplet: false,
		//自定义字段内容
		customField: null,
		//是否仅需认证
		justCertification: false,
	},
	//获取楼宇列表: tip1-仅一个楼宇则自动填充 tip2-多个楼宇则判断是否扫码或者缓存进入
	getBuildingList() {
		//恢复初始态
		this.setData({
			buildingList: [],
			buildingIndex: null,
			buildingAdminId: null,
			buildingName: 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('visitorAdminInfo');
					app.data.visitorAdminInfo = 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) {
				console.log(buildingIndex);
				//获取企业列表
				// this.getCompanyList(); 
				//获取是否开启自定义字段
				this.getContextStatusByAdminId(this.data.buildingAdminId)
				//获取楼宇账号配置
				this.getAdminConfig()
			}
			this.setData({
				buildingList: res.data,
				buildingIndex: buildingIndex
			});
		})
	},
	// 获取账号的配置信息
	async getAdminConfig(type) {
		await getAdminConfig({
			adminId: this.data.buildingAdminId
		}).then(res => {
			//若为指定人员审核且为访客自主申请
			if (res.data.buildingCheckType == 2 && this.data.type == 1) {
				this.getCompanyList()
			}
			this.setData({
				needPhone: res.data.visitorAppPhone,
				needPhoto: res.data.visitorAppPhoto,
				needRealname: res.data.visitorAppRealname,
				needLoginList: res.data.visitorAppLoginList,
				buildingCheckType: res.data.buildingCheckType,
			});
			//根据账号配置判断是否有可使用的用户信息
			this.jugdeInfo();
		})
	},
	//获取是否有自定义字段
	getContextStatusByAdminId(orgId) {
		getContextByAdminId(orgId).then(res => {
			if (res.code == 200) {
				this.setData({
					isShowApplet: res.data,
					isFillFields: !res.data,
				})
				this.canOperation()
			} else {
				wx.showToast({
					title: res.msg,
					icon: 'none'
				})
			}
		})
	},
	// 获取用户填写的自定义字段内容
	getContextByAdminId() {
		console.log(!this.data.buildingAdminId);
		console.log(!this.data.userInfo);
		if (!this.data.buildingAdminId || !this.data.userInfo) {
			return;
		}
		selectContextByCardId(this.data.buildingAdminId, this.data.userInfo.userId).then(res => {
			console.log(res.data);
			console.log(this.data.isShowApplet);
			this.setData({
				customField: res.data
			})
		})
	},
	// 查找是否有企业，若无企业则一定无受访人
	getCompanyList() {
		wx.showLoading({
			title: '查询中...',
		});
		//清空原有的选择
		this.setData({
			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
			//企业数量为 1 自动填充
			if (res.data.length === 1) {
				companyIndex = 0;
				this.setData({
					companyAdminId: res.data[0].adminId,
					companyName: res.data[0].name
				})
			};
			this.setData({
				companyList: res.data,
				companyIndex: companyIndex,
			});
		});
	},
	// 获取组件抛出的认证状态-实名认证
	getCertificationState(e) {
		if (!e.detail) {
			wx.showToast({
				title: '认证失败了，再试一次吧~',
				icon: 'none'
			});
			return;
		}
		//是只需要认证
		if (this.data.justCertification) {
			wx.showModal({
				content: this.data.language == 'ch' ? '认证成功～' : 'Certification success',
				complete: (res) => {
					wx.navigateBack({
						delta: 1
					})
				}
			})
			return;
		}
		//不是只需要认证
		wx.showToast({
			title: '认证成功~',
			icon: 'none'
		})
		this.setData({
			isDisabled: true,
		});
		this.updateSetting()
		this.getContextStatusByAdminId(this.data.buildingAdminId)
		this.getContextByAdminId();
	},
	// 更改信息
	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;
					app.data.userInfo = null;
					app.data.visitorUserInfo = null;
					app.data.visitorExtraInfo = null;
					this.doCheckAdmin();
				}
			}
		})
	},

	// 更新个人信息
	updateSetting() {
		//是否禁用选择楼宇企业选择栏
		let disableSelectAdminInfo = app.data.visitorAdminInfo || app.data.temporaryAdminInfo;
		this.setData({
			isDisabled: app.data.visitorUserInfo ? true : false,
			disableSelectAdminInfo: disableSelectAdminInfo,
			usedAdminInfo: app.data.visitorAdminInfo || app.data.temporaryAdminInfo,
			userInfo: app.data.visitorUserInfo
		});
	},
	//获取输入or选择的内容
	getValue(e) {
		var {
			form,
			buildingCheckType
		} = this.data;
		
		switch (e.currentTarget.dataset.type) {
			case 'reason':
				this.setData({
					'form.reason': e.detail.name
				})
				break;
			case 'visiteeBuilding':
				console.log(e);
				this.setData({
					'form.visiteeBuilding': e.detail.name,
					'form.visiteeBuildingId': e.detail.adminId,
					buildingAdminId: e.detail.adminId,
					buildingName: e.detail.name,
				})
				this.getAdminConfig()
				this.getContextStatusByAdminId(e.detail.adminId)
				break;
			case "visiteeCompany":
				if (buildingCheckType == 1) {
					this.setData({
						'form.visiteeXm': e.detail.name,
						'form.userWhitelistId': e.detail.userWhitelistId,
					})
				} else {
					this.setData({
						companyIndex: e.detail.index,
						'form.visiteeCompany': e.detail.companyName,
						'form.visiteeCompanyId': e.detail.adminId,
					})
				}
				break;
			case 'visiteePhone':
				this.setData({
					'form.visiteePhone': e.detail
				})
				if (e.detail.length >= 11) {
					wx.hideKeyboard()
					this.getUserWhiteByphoneAndAdminId()
				} else {
					this.setData({
						companyList: null,
						companyIndex: 0,
						'form.visiteeXm': '',
						'form.visiteeCompany': '',
						'form.visiteeCompany': '',
						'form.userWhitelistId': ''
					});
					this.canOperation();
				}
				break;
				case 'company':
					this.setData({
						'form.company': e.detail
					})
			default:
				form[e.currentTarget.dataset.type] = e.detail
				break;
		}
		this.canOperation()
	},
	//根据受访人手机号查询受访人账号信息
	getUserWhiteByphoneAndAdminId() {
		wx.showLoading({
			title: '查询中...',
		})
		let {
			form,
		} = this.data;
		let data = {
			buildingAdminId: this.data.buildingAdminId,
			phone: form.visiteePhone
		}
		getUserWhiteByphoneAndAdminId(data).then(res => {
			wx.hideLoading()
			//未查询到对应常客信息
			if (res.code != 200) {
				wx.showToast({
					title: res.msg,
					icon: 'none'
				})
				this.setData({
					companyList: null,
					companyIndex: null,
					'form.visiteeXm': '',
					'form.visiteeCompany': '',
					'form.userWhitelistId': '',
					'form.visiteeCompanyId': '',
					customField: null
				});
				this.canOperation();
				return;
			}
			//查询到对应常客信息
			this.setData({
				companyList: res.data[0].userWhiteIntervieweeVOList,
				companyIndex: 0,
				'form.visiteeXm': res.data[0].userWhiteIntervieweeVOList[0].name,
				'form.visiteeCompany': res.data[0].userWhiteIntervieweeVOList[0].companyName,
				'form.userWhitelistId': res.data[0].userWhiteIntervieweeVOList[0].userWhitelistId,
				'form.visiteeCompanyId': res.data[0].userWhiteIntervieweeVOList[0].adminId
			});
			this.getContextByAdminId();
			this.canOperation();
		})
	},
	// 判断受邀人的手机号是否和当前用户手机号一致? ---------------todo
	matchCorrectPhone() {
		let disableComplete = false
		if (app.data.visitorUserInfo && this.data.form.correctPhone && this.data.type === 2) {
			if (app.data.visitorUserInfo.phone != this.data.form.correctPhone) {
				disableComplete = true
				wx.showModal({
					title: '提示',
					content: '你暂无权限接受此邀请哦,请检查手机号是否正确.',
					showCancel: false,
					complete: (res) => {}
				})
			}
		}
		this.setData({
			disableComplete
		})
	},
	// 获取是否可以展示信息?
	getUpdateState(e) {
		if (e.detail) {
			this.updateSetting()
		}
	},
	//提交申请
	submit() {
		const that = this;
		let {
			form,
			isFillFields,
			customField,
		} = this.data
		form.addCustomList = isFillFields ? customField : null;
		form.userId = that.data.userInfo.userId;
		form.visiteeBuildingId = that.data.buildingAdminId;
		visitorySubmit(form).then(res => {
			console.log(res);
			// 提交失败
			if (res.code != 200) {
				wx.showToast({
					title: res.msg,
					icon: 'none'
				});
				return;
			}
			//提交成功
			let visitorExtraInfo = {
				company: form.company,
				carno: form.carno
			};
			wx.setStorageSync('visitorExtraInfo', visitorExtraInfo)
			app.data.visitorExtraInfo = visitorExtraInfo
			wx.showModal({
				title: '提示',
				content: that.data.type === 1 ? '您的预约已提交，请耐心等待常客审核吧~' : '您已成功接受邀请啦,随后可在"首页-访客记录"中查看详情~',
				showCancel: false,
				success() {
					if (that.data.type === 1) {
						wx.navigateBack({
							delta: 1,
						})
					} else {
						wx.switchTab({
							url: '/pages/resitor_scence/resitor_scence',
						})
					}
				}
			})
		})
	},
	// 获取邀请函信息
	async getVisitoryByUserVisitorListDetailId(id) {
		return new Promise((reslove, reject) => {
			var {
				form
			} = this.data;
			getVisitoryByUserVisitorListDetailId({
				userVisitorListDetailId: id
			}).then(async res => {
				if (res.code != 200) {
					wx.showToast({
						title: res.msg,
						icon: 'none'
					})
					return;
				}
				app.data.temporaryAdminInfo = {
					buildingAdminId: res.data.visiteeBuildingId,
					buildingName: res.data.visiteeBuilding,
					companyAdminId: res.data.visiteeCompanyId,
					companyName: res.data.visiteeCompany,
				}
				form.userVisitorListDetailId = res.data.id
				form.correctPhone = res.data.phone
				form.visiteePhone = res.data.visiteePhone;
				form.visiteeBuilding = res.data.visiteeBuilding;
				form.visiteeBuildingId = res.data.visiteeBuildingId;
				form.visiteeCompany = res.data.visiteeCompany;
				form.visiteeCompanyId = res.data.visiteeCompanyId
				form.visiteeXm = res.data.visiteeXm;
				form.userWhitelistId = res.data.userWhitelistId;
				form.startTime = res.data.startTime;
				form.endTime = res.data.endTime;
				form.reason = res.data.reason;
				let buildingList = [{
					adminId: res.data.visiteeBuildingId,
					name: res.data.visiteeBuilding
				}];
				let companyList = [{
					adminId: res.data.visiteeCompanyId,
					companyName: res.data.visiteeCompany,
				}]
				this.reasonEcho(res.data.reason)
				this.setData({
					userInfo: app.data.visitorUserInfo,
					all_buildingList: buildingList,
					buildingIndex: 0,
					buildingAdminId: res.data.visiteeBuildingId,
					buildingName: res.data.visiteeBuilding,
					companyList: companyList,
					companyIndex: 0,
					companyAdminId: res.data.visiteeCompanyId,
					companyName: res.data.visiteeCompany,
					personTypIndex: res.data.personnelType,
					isAudit: true,
					form,
				})
				this.matchCorrectPhone();
				if (this.data.userInfo) {
					this.getContextStatusByAdminId(res.data.visiteeBuildingId)
					this.getContextByAdminId()
				}
				this.doCheckAdmin();
				return;
			})
		})
	},
	// 来访事由 - 邀请回显
	reasonEcho(name) {
		let reason = {
			name
		}
		let index = this.data.reasonList.map(item => {
			return JSON.stringify(item)
		}).indexOf(JSON.stringify(reason))
		if (index > -1) {
			this.setData({
				reasonIndex: index,
			});
		}
	},
	//步骤条判断是否完成
	canOperation() {
		let {
			stepsList,
			disableComplete,
			form,
			isFillFields,
			buildingCheckType
		} = this.data;
		stepsList[0].complete = (!disableComplete && form.company && this.data.userInfo && this.data.buildingAdminId) ? true : false;
		if (buildingCheckType == 1) {
			stepsList[1].complete = (!disableComplete && form.userWhitelistId && isFillFields) ? true : false
		} else {
			stepsList[1].complete = (!disableComplete && isFillFields) ? true : false
		}
		console.log(this.data.isShowApplet);
		this.setData({
			stepsList
		})
	},
	// 判断自定义字段是否填写完成
	isFillFields(e) {
		if (e.detail == false) {
			this.data.isFillFields = false;
		} else {
			this.data.customField = e.detail;
			this.data.isFillFields = true;
		}
		this.canOperation()
	},
	//扫码账号信息的处理
	doCheckAdmin() {
		//先渲染中英文配置
		this.setData({
			userInfo: app.data.visitorUserInfo,
			language: app.data.language,
		})
		//临时账号信息&&访客账号信息不一致
		if ((app.data.temporaryAdminInfo && app.data.visitorAdminInfo) && (app.data.temporaryAdminInfo.buildingAdminId !== app.data.visitorAdminInfo.buildingAdminId)) {
			wx.showModal({
				content: `检测到您本次扫码为"${app.data.temporaryAdminInfo.buildingName || "未知"}",与上次拜访的"${app.data.visitorAdminInfo.buildingName || "未知"}"不一致，是否按照本次的信息进行预约？`,
				cancelText: "使用上次",
				confirmText: "使用本次",
				complete: (res) => {
					console.log(res);
					if (res.cancel) {
						app.data.temporaryAdminInfo = null
					}
					if (res.confirm) {
						app.data.visitorAdminInfo = null;
						wx.removeStorageSync('visitorAdminInfo');
					};
					this.setData({
						usedAdminInfo: app.data.visitorAdminInfo || app.data.temporaryAdminInfo,
					})
					this.getBuildingList();
					this.updateSetting();
				}
			})
			//临时账号信息&&常客账号信息其中一个有，或两个没有，或两个都有，但是信息一致
		} else {
			this.setData({
				usedAdminInfo: app.data.visitorAdminInfo || app.data.temporaryAdminInfo
			})
			this.getBuildingList();
			this.updateSetting();
		};
		//填充缓存的额外信息
		if (app.data.visitorExtraInfo) {
			this.setData({
				'form.company': app.data.visitorExtraInfo.company,
				'form.carno': app.data.visitorExtraInfo.carno
			})
		}
	},
	// 获得swiper-item位置
	getSwiperPercent(e) {
		this.setData({
			swiperDx: e.detail.dx
		})
	},
	// 改变swiper
	changeSwiper(e) {
		if (e.detail.current < this.data.currentIndex || this.data.stepsList[e.detail.current].complete) {
			this.setData({
				currentIndex: e.detail.current
			})
		} else {
			this.setData({
				currentIndex: this.data.currentIndex
			})
		}
	},
	// 下一步
	next_step(e) {
		let {
			userInfo,
			isShowApplet,
		} = this.data
		this.setData({
			currentIndex: 1,
		})
		if (userInfo && userInfo.userId && !isShowApplet) {
			this.getContextStatusByAdminId(this.data.buildingAdminId)
		}
	},
	// 上一步
	previous_step(e) {
		this.setData({
			currentIndex: 0,
		})
	},
	// 判断认证信息是否可以复用 userInfo <-----> visitorUserINfo
	jugdeInfo() {
		//判断是否有访客缓存信息
		if (app.data.visitorUserInfo) {
			this.checkInfo()
			return;
		}
		//判断是否有常客信息
		if (!app.data.userInfo) {
			return;
		}
		//判断常客信息的严格等级是否大于等于登录要求 实名认证>非实名
		console.log(!(!this.data.needRealname || app.data.userInfo.needRealname));
		if (!(!this.data.needRealname || app.data.userInfo.needRealname)) {
			return;
		}
		//判断已缓存的常客认证信息是否包含登录要求
		for (let index = 0; index < this.data.needLoginList.length; index++) {
			if (app.data.userInfo.needLoginList.indexOf(this.data.needLoginList[index]) <= -1) {
				return;
			}
		};
		wx.setStorageSync('visitorUserInfo', app.data.userInfo)
		app.data.visitorUserInfo = app.data.userInfo;
		this.updateSetting()
	},
	//判断访客缓存信息是否可以使用
	checkInfo() {
		//判断访客信息的严格等级是否大于等于登录要求 实名认证>非实名
		if (!(!this.data.needRealname || app.data.visitorUserInfo.needRealname)) {
			wx.showModal({
				content: '检测到账号登录条件已经变更为实名认证模式,请重新认证并绑定',
				complete: (res) => {
					wx.removeStorageSync('visitorUserInfo');
					app.data.visitorUserInfo = null;
					this.doCheckAdmin();
				}
			})
			return;
		}
		//判断已缓存的常客认证信息是否包含登录要求
		for (let index = 0; index < this.data.needLoginList.length; index++) {
			if (app.data.visitorUserInfo.needLoginList.indexOf(this.data.needLoginList[index]) <= -1) {
				wx.showModal({
					content: '检测到账号登录条件已增加,请重新认证并绑定',
					complete: (res) => {
						wx.removeStorageSync('visitorUserInfo');
						app.data.visitorUserInfo = null;
						this.doCheckAdmin();
					}
				})
				return;
			}
		};
	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: async function (options) {
		//邀请函进入
		if ('userVisitorDetailId' in options) {
			this.getVisitoryByUserVisitorListDetailId(options.userVisitorDetailId);
			this.setData({
				type: 2,
				userVisitorDetailId: options.userVisitorDetailId
			});
			return;
		}
		//是否只需要认证标签
		if ('justCertification' in options) {
			this.setData({
				justCertification: options.justCertification === "true" ? true : false
			})
		}
		this.doCheckAdmin();
	},

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

	},

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

	},

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

	},

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

	},

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

	},

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

	},

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

	}
})