// components/face_verify/face_verify.js
import international from '../../international/appointment_scence/index'
import {
	foreignAuthentication
} from '../../utils/api/make_appointment'
import {
	cardIdExSet,
	doConfirmFaceNotifyNew, openIdSet
} from '../../utils/api/api'
const face = require('../../utils/faceCheck/faceCheck')
const {
	throttle
} = require('../../utils/throttle/throttle');
const getPhone = require('../../utils/getPhone/wx_getPhone');
var verify = require('../../utils/util/util')
import {
	getWxLogin
} from '../../utils/util/util'
const app = getApp()

Component({
	/**
	 * 组件的属性列表
	 */
	properties: {
		title: {
			type: String,
			value: '人员信息'
		},
		language: {
			type: String,
			value: 'ch'
		},
		isDisabled: {
			type: Boolean,
			value: true,
		},
		userInfo: {
			type: Object,
		},
		// 常客、访客
		userType: {
			value: null
		},
		// 登录参数列表 1姓名2身份证3手机号4卡号
		needLoginList: {
			type: Array,
			value: [],
		},
		//是否输入手机号 0-否 1-需要 
		needPhone: {
			type: Boolean,
			value: false,
		},
		//是否需要照片 0-否 1-需要
		needPhoto: {
			type: Boolean,
			value: false,
		},
		//是否需要实名 0-否 1-需要
		needRealname: {
			type: Boolean,
			value: false,
		},
		//
		pageType: {
			type: String,
			value: ''
		},
	},
	/**
	 * 组件的初始数据
	 */
	data: {
		//国际化语言包
		international: international,
		myUserInfo: null,
		username: '',
		idNumber: '',
		phone: '',
		cardIdEx: '',
		warnCardId: { //卡号校验信息
			status: false,
			errMsg: null
		},
		warnName: { //姓名校验信息
			status: false,
			errMsg: null
		},
		warnIdcard: { //身份证校验信息
			status: false,
			errMsg: null
		},
		warnPhone: { //手机号校验信息
			status: false,
			errMsg: null
		},
	},

	/**
	 * 组件的方法列表
	 */
	methods: {
		//输入姓名
		getInputName(e) {
			let {
				warnName,
				username
			} = this.data;
			username = e.detail
			if (e.detail) {
				warnName.status = true
			} else {
				warnName.status = false
				warnName.errMsg = '您输入的姓名不可以为空!'
			};
			this.setData({
				warnName,
				username
			})
		},
		//输入身份证号
		getInputIdcard(e) {
			let {
				warnIdcard,
				idNumber
			} = this.data
			idNumber = e.detail
			if (app.data.language === 'en') {
				warnIdcard.status = true;
			} else {
				let res = verify.isCardID(idNumber);
				if (res.state) {
					warnIdcard.status = true;
					wx.hideKeyboard()
				} else {
					warnIdcard.status = false
					warnIdcard.errMsg = res.data
				};
			}
			this.setData({
				warnIdcard,
				idNumber
			});
		},
		// 输入手机号
		getInputPhone(e) {
			let {
				warnPhone,
				phone
			} = this.data
			phone = e.detail
			let res = verify.isCornet(phone);
			if (res.state) {
				warnPhone.status = true;
			} else {
				warnPhone.status = false
				warnPhone.errMsg = res.data
			};
			if (phone.length >= 11) {
				wx.hideKeyboard()
			}
			this.setData({
				warnPhone,
				phone
			});
		},
		//点击获取手机号
		getPhoneNumber(e) {
			getPhone(e).then(phone => {
				if (phone) {
					this.setData({
						'warnPhone.status': true,
						phone: phone
					})
					app.data.phone = phone
				} else {
					wx.showToast({
						icon: 'none',
						title: '网络异常请重新获取哦~',
					})
				}
			}).catch((err) => {
				console.log(err)
			})
		},
		// 输入卡号
		getCardNumber(e) {
			let {
				warnCardId,
				cardIdEx
			} = this.data;
			cardIdEx = e.detail
			if (e.detail) {
				warnCardId.status = true
			} else {
				warnCardId.status = false
				warnCardId.errMsg = '卡号不可以为空!'
			};
			this.setData({
				warnCardId,
				cardIdEx
			});
		},
		// 点击认证按钮
		Certification() {
			let {
				warnPhone,
				warnIdcard,
				warnName,
				warnCardId
			} = this.data
			let allFill = this.canOperation(warnName.status, warnIdcard.status, warnPhone.status, warnCardId.status)
			// 判断信息是否填写完整
			if (!allFill) {
				wx.showToast({
					icon: 'none',
					title: '请将个人信息填写完整！',
				})
				return;
			}
			// 实名认证
			if (this.data.needRealname) {
				this.submit()
			}
			// 无需实名认证&需要抓拍
			if (!this.data.needRealname && this.data.needPhoto) {
				//抓拍人脸 flag-3
				this.data.flag = 3
				wx.navigateTo({
					url: '/pages/faceCheck/faceCheck'
				})
			}
			// 无需实名认证&无需抓拍
			if (!this.data.needRealname && !this.data.needPhoto) {
				this.doConfirmFaceNotifyNew(1)
			}
		},
		// 判断提交按钮是否禁用
		canOperation(username, idNumber, phone, cardIdEx) {
			let {
				needLoginList
			} = this.data;
			let allFill = true
			for (let index = 0; index < needLoginList.length; index++) {
				if (!Array.from(arguments)[needLoginList[index] - 1]) {
					allFill = false;
					break;
				}
			}
			return allFill
		},
		//跳转执行实名认证
		submit: throttle(function () {
			const that = this;
			let {
				username,
				idNumber,
				phone,
			} = this.data
			let orgId = app.data.adminId;
			face.intoFace_wxrlxf(username, idNumber, phone, orgId = '00').then((res) => {
				that.data.flag = 1
			}).catch(err => { })
		}, 5000),
		//验证人脸
		async doFaceCheck() {
			wx.showLoading({
				title: '信息验证中...',
			})
			let taskId = app.data.faceTaskId;
			// taskId = '00-2023041314125357889'; //本地
			// taskId = '00-993306131355291200'; //线上
			// taskId = '00-2024050112393311886' //zyh线上
			if (!taskId) return;
			let res = await face.getFace_wxrlxf('/api/next/doQueryFaceSuccess', 'get', {
				taskId: taskId
			});
			wx.hideLoading()
			if (res.data.status === true) {
				this.openIdAndCardIdSet(res.data, this.data.cardIdEx);
			} else {
				this.triggerEvent('certificationState', false)
			}
		},
		// 无需实名认证&需抓拍人脸照片 注册信息 1-不需要照片 2-需要照片
		doConfirmFaceNotifyNew(type) {
			this.data.flag = null;
			let img = '';
			if (type == 2) {
				img = app.data.catchFaceUrl || '';
				app.data.catchFaceUrl = null;
				//抓拍失败
				if (!img) {
					wx.showModal({
						content: '认证失败,再试一次吧',
						showCancel: false,
						complete: (res) => {
						}
					})
					return;
				}
			}
			let {
				idNumber,
				phone,
				username,
				cardIdEx
			} = this.data
			let data = {
				avatar: img,
				idNumber: idNumber,
				cardIdEx: cardIdEx,
				username: username,
				phone: phone,
				type: 3,
				code: app.data.wxCode
			}
			let that = this
			wx.showLoading({
				title: '信息验证中...',
			})
			doConfirmFaceNotifyNew(data).then(res => {
				wx.hideLoading()
				getWxLogin()
				// 接口请求失败
				if (res.code !== 200) {
					wx.showToast({
						title: res.mag,
						icon: 'none',
					});
					this.triggerEvent('certificationState', false)
					return;
				}
				//接口请求成功
				let userInfo = res.data
				userInfo.needLoginList = this.data.needLoginList;
				userInfo.needPhone = this.data.needPhone;
				userInfo.needPhoto = this.data.needPhoto;
				userInfo.needRealname = this.data.needRealname;
				wx.setStorageSync('language', app.data.language);
				//访客认证结果
				if (that.data.userType == '访客') {
					wx.setStorageSync('visitorUserInfo', userInfo);
					app.data.visitorUserInfo = userInfo;
				}
				//常客认证结果
				if (that.data.userType == '常客') {
					wx.setStorageSync('userInfo', userInfo);
					app.data.userInfo = userInfo;
				}
				wx.showToast({
					title: `恭喜认证成功`,
					icon: 'none'
				})
				this.triggerEvent('certificationState', true)
			})
		},
		// 实名认证时&卡号&微信 openId 绑定认证信息 userId
		openIdAndCardIdSet(userInfo, cardIdEx) {
			const that = this;
			let openId = "";
			//openId绑定
			let doOpenIdset = new Promise((reslove, reject) => {
				wx.login({
					success: res => {
						openId = res.code
						let data = {
							code: openId,
							type: 3,
							userId: userInfo.userId
						}
						openIdSet(data).then(res => {
							getWxLogin()
							res.code == 200 ? reslove() : reject();
						})
					}
				})
			});
			// cardIdEx绑定
			let doCardIdExSet = new Promise((reslove, reject) => {
				let data = {
					cardIdEx: that.data.cardIdEx,
					userId: userInfo.userId
				}
				cardIdExSet(data).then(res => {
					res.code == 200 ? reslove() : reject();
				})
			})
			//判断是否需要绑定卡号（openId 一定绑定）
			let taskList = [doOpenIdset];
			if (this.data.needLoginList.indexOf(4) > -1) {
				taskList = [doOpenIdset, doCardIdExSet];
			}
			Promise.all(taskList).then(res => {
				userInfo.openId = openId;
				userInfo.cardIdEx = cardIdEx;
				//存下登录条件
				userInfo.needLoginList = this.data.needLoginList;
				userInfo.needPhone = this.data.needPhone;
				userInfo.needPhoto = this.data.needPhoto;
				userInfo.needRealname = this.data.needRealname;
				if (this.data.userType == '访客') {
					wx.setStorageSync('visitorUserInfo', userInfo);
					app.data.visitorUserInfo = userInfo
				} else {
					wx.setStorageSync('userInfo', userInfo);
					app.data.userInfo = userInfo
				}
				this.triggerEvent('certificationState', true)
			}).catch(err => {
				wx.showToast({
					title: err.msg,
					icon: 'none'
				})
				this.triggerEvent('certificationState', false)
			})
		},
		//外宾时，执行 OCR 识别
		goOCR() {
			let {
				needPhoto,
				needRealname,
			} = this.data
			this.data.flag = 2;
			wx.navigateTo({
				url: '/pages/ocr/ocr?needPhoto=' + needPhoto + '&needRealname=' + needRealname
			})
		},
		// ocr 完成后，渲染数据
		updateOcrInfo() {
			let ocrInfo = JSON.parse(JSON.stringify(app.data.ocrInfo))
			app.data.ocrInfo = null
			let data = {
				username: ocrInfo.name,
				idNumber: ocrInfo.passportCode,
				avatar: ocrInfo.faceImage,
				countryCode: ocrInfo.countryCode,
				gender: ocrInfo.gender,
				passportUrl: ocrInfo.passportUrl,
				hztx: ocrInfo.hztx,
				birthday: ocrInfo.birthday,
				efficientTime: ocrInfo.efficientTime
			}
			this.setData({
				myUserInfo: data,
				username: ocrInfo.name,
				'warnName.status': true,
				idNumber: ocrInfo.passportCode,
				'warnIdcard.status': true,
			})
		},
		// 外宾确认或修改用户信息
		update() {
			let {
				warnPhone,
				warnIdcard,
				warnName,
				warnCardId
			} = this.data
			let allFill = this.canOperation(warnName.status, warnIdcard.status, warnPhone.status, warnCardId.status)
			//未填写完整
			if (!allFill) {
				wx.showToast({
					icon: 'none',
					title: 'Please complete your personal information!',
				})
				return;
			}
			//填写完整
			let data = {
				username: this.data.myUserInfo.username,
				idNumber: this.data.myUserInfo.idNumber,
				avatar: this.data.myUserInfo.avatar,
				phone: this.data.phone,
				cardIdEx: this.data.cardIdEx,
				countryCode: this.data.myUserInfo.countryCode,
				gender: this.data.myUserInfo.gender,
				passportUrl: this.data.myUserInfo.passportUrl,
				hztx: this.data.myUserInfo.hztx,
				birthday: this.data.myUserInfo.birthday,
				efficientTime: this.data.myUserInfo.efficientTime
			}
			wx.showLoading({
				title: '信息提交中...',
			})
			foreignAuthentication(data).then(res => {
				wx.hideLoading()
				if (res.code !== 200) {
					wx.showToast({
						icon: 'none',
						title: res.msg,
					});
					return;
				}
				let userInfo = Object.assign(res.data, data)
				this.openIdAndCardIdSet(userInfo, this.data.cardIdEx)
			})
		},
		//预览照片
		previewImg(e) {
			let currentUrl = e.currentTarget.dataset.src;
			if (!currentUrl) {
				return;
			}
			wx.previewImage({
				current: currentUrl,
				urls: [currentUrl]
			})
		}
	},

	observers: {
		'userInfo': function (userInfo) {
			let myUserInfo = userInfo || null;
			if (!userInfo) {
				return;
			}
			this.setData({
				username: myUserInfo.username || "",
				idNumber: myUserInfo.idNumber || "",
				phone: myUserInfo.phone || "",
				cardIdEx: myUserInfo.cardIdEx || "",
				myUserInfo: myUserInfo
			})
		},
	},
	lifetimes: {
		attached: function () {

		}
	},
	pageLifetimes: {
		show() {
			switch (this.data.flag) {
				//实名认证完成后操作
				case 1:
					this.doFaceCheck()
					break;
				//OCR识别完成后操作
				case 2:
					this.updateOcrInfo()
					break;
				//抓拍照片完成后操作
				case 3:
					this.doConfirmFaceNotifyNew(2)
					break;

				default:
					break;
			}
		}
	}
})