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

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

	this.$delay(function () {
		this.changeUserId(this.userId)
	})

	this.deleteDomain = function (domainId) {
		let that = this
		utils.confirm("确定要删除此域名吗？", function () {
			that.$post("/ns/domains/delete")
				.params({
					domainId: domainId
				})
				.success(function () {
					utils.reload()
				})
		})
	}

	this.verifyDomain = function (domainId) {
		utils.popup("/ns/domains/domain/verifyPopup?domainId=" + domainId, {
			callback: function () {

			}
		})
	}

	this.hasGroups = false
	this.changeUserId = function (userId) {
		this.$post("/ns/domains/groups/options")
			.params({
				userId: userId
			})
			.success(function (resp) {
				this.hasGroups = resp.data.groups.length > 0
				if (this.hasGroups) {
					this.$delay(function () {
						this.$refs.groupSelector.reload(userId)
					})
				}
			})
	}

	/**
	 * 批量操作
	 */
	this.selectedAll = false
	this.hasSelectedDomains = false
	this.hasVerifyingDomains = false

	this.$delay(function () {
		this.$watch(() => this.selectedAll, () => {
			if (this.selectedAll) {
				this.hasSelectedDomains = true
				this.domains.forEach(domain => {
					domain.isChecked = true
				})
			} else {
				this.hasSelectedDomains = false
				this.domains.forEach(domain => {
					domain.isChecked = false
				})
				this.hasVerifyingDomains = false
			}
			this.hasVerifyingDomains = this.domains.$find((k, domain) => {
				return domain.status == "none"
			}) != null
		})
	})

	this.changeDomainChecked = function (domain) {
		this.hasSelectedDomains = false
		this.hasVerifyingDomains = false

		this.domains.forEach(domain => {
			if (domain.isChecked) {
				this.hasSelectedDomains = true
				if (domain.status == "none") {
					this.hasVerifyingDomains = true
				}
			}
		})
	}

	this.cancelDomains = function () {
		this.domains.forEach(domain => {
			domain.isChecked = false
		})
		this.selectedAll = false
		this.hasSelectedDomains = false
		this.hasVerifyingDomains = false
	}

	this.deleteDomains = function () {
		let domainIds = []
		this.domains.forEach(domain => {
			if (domain.isChecked) {
				domainIds.push(domain.id)
			}
		})

		if (domainIds.length == 0) {
			return
		}

		utils.confirm("确定要删除选中的域名吗？", function () {
			this.$post(".deletePage")
				.params({
					domainIds: domainIds
				})
				.success(function () {
					utils.successRefresh("删除成功")
				})
		})
	}

	this.verifyDomains = function () {
		let domainIds = []
		this.domains.forEach(domain => {
			if (domain.isChecked && domain.status == "none") {
				domainIds.push(domain.id)
			}
		})

		if (domainIds.length == 0) {
			return
		}
		utils.confirm("html:确定要批量验证选中的域名吗？<br/>在此之前请确保这些域名已经设置了NS记录。<br/>已经验证过的域名，不再重复验证。", function () {
			this.$post(".verifyPage")
				.params({
					domainIds: domainIds
				})
				.success(function () {
					utils.successRefresh("验证成功")
				})
		})
	}
}