import initCtx from "@/utils/ctx.js";

export default function () {
	const {utils} = initCtx(this)

	this.backPreviewURL = ""
	this.frontPreviewURL = ""
	this.isSubmitting = false

	this.realName = ""
	this.number = ""

	if (this.identity != null) {
		this.realName = this.identity.realName
		this.number = this.identity.number
	}
	this.canEdit = (this.identity == null || this.identity.status == "none" || this.identity.status == "rejected")

	this.selectFile = function (targetId) {
		let selector = document.getElementById(targetId)
		selector.click()
	}

	this.changeBackFile = function (e) {
		let files = e.target.files
		if (files.length > 0) {
			this.backPreviewURL = URL.createObjectURL(files[0])
		}
	}

	this.changeFrontFile = function (e) {
		let files = e.target.files
		if (files.length > 0) {
			this.frontPreviewURL = URL.createObjectURL(files[0])
		}
	}

	this.beforeSubmit = function () {
		this.isSubmitting = true
	}

	this.doneSubmit = function () {
		this.isSubmitting = false
	}

	this.success = function () {
		utils.success("保存成功", function () {
			utils.reload()
		})
	}

	this.submit = function () {
		if (this.identity == null) {
			utils.fail("请先保存后再提交审核")
			return
		}
		this.$post(".submit")
			.params({
				identityId: this.identity.id
			})
			.success(function () {
				utils.success("提交成功", function () {
					utils.reload()
				})
			})
	}

	this.cancel = function () {
		if (this.identity == null) {
			utils.fail("请先保存后再提交审核")
			return
		}
		utils.confirm("确定要取消提交审核吗？", function () {
			this.$post(".cancel")
				.params({
					identityId: this.identity.id
				})
				.success(function () {
					utils.success("取消成功", function () {
						utils.reload()
					})
				})
		})
	}

	this.faceQrcode = ""
	this.generatingQrcode = false
	this.generateFaceQrcode = function () {
		this.faceQrcode = ""
		this.generatingQrcode = true
		this.$post(".face.prepare")
			.params({
				identityId: this.identity.id,
				returnURL: window.location.toString()
			})
			.success(function (resp) {
				this.faceQrcode = resp.data.qrcode
				setTimeout(() => {
					const buttonRef = this.$refs.facePrimaryButtonRef
					buttonRef.$el.scrollIntoView({
						behavior: "smooth"
					})
				}, 100)
			})
			.done(function () {
				this.generatingQrcode = false
			})
	}

	this.cancelFace = function () {
		this.faceQrcode = ""
	}

	this.verifyFace = function () {
		this.$post(".face.validate")
			.params({
				identityId: this.identity.id
			})
			.success(function (resp) {
				if (resp.data.isOk) {
					utils.success("恭喜你，已完成实名认证", function () {
						window.location.reload()
					})
				} else {
					utils.success("你尚未完成实名认证")
				}
			})
	}
}