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

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

	this.$delay(function () {
		this.loadStatus()
	})

	this.loadStatus = function () {
		let serverIds = this.servers.map(function (v) {
			return v.id
		})
		this.$post(".status")
			.params({
				serverIds: serverIds
			})
			.timeout(300)
			.success(function (resp) {
				let status = resp.data.status
				this.servers.forEach(function (server) {
					if (typeof status[server.id] === "object") {
						server.status = status[server.id]
					}
				})
			})
	}

	this.deleteServer = function (serverId) {
		let that = this
		utils.confirm("确定要删除此网站吗？", function () {
			that.$post(".delete")
				.params({
					serverId: serverId
				})
				.refresh()
		})
	}

	this.updateServerOn = function (serverId) {
		let that = this
		utils.confirm("确定要启用此网站吗？", function () {
			that.$post(".updateOn")
				.params({
					serverId: serverId,
					isOn: true
				})
				.refresh()
		})
	}

	this.updateServerOff = function (serverId) {
		let that = this
		utils.confirm("确定要停用此网站吗？", function () {
			that.$post(".updateOn")
				.params({
					serverId: serverId,
					isOn: false
				})
				.refresh()
		})
	}

	this.updateServerName = function (serverId) {
		utils.popup("/servers/updateNamePopup?serverId=" + serverId, {
			callback: function () {
				utils.success("保存成功", function () {
					utils.reload()
				})
			}
		})
	}

	/**
	 * 全选
	 */
	this.checkedServerIds = []
	this.allChecked = false
	this.changeAllChecked = function (checked) {
		this.servers.forEach(server => {
			server.isChecked = checked
		})
		this.updateCheckedServers()
	}

	this.changeServerChecked = function () {
		this.updateCheckedServers()
	}

	this.updateCheckedServers = function () {
		let serverIds = []
		this.servers.forEach(server => {
			if (server.isChecked) {
				serverIds.push(server.id)
			}
		})
		this.checkedServerIds = serverIds
	}

	this.resetCheckedServers = function () {
		this.servers.forEach(server => {
			server.isChecked = false
		})
		this.allChecked = false
		this.updateCheckedServers()
	}

	this.deleteServers = function () {
		let that = this
		utils.confirm("确定要删除所选的" + (this.checkedServerIds.length) + "个网站吗？", function () {
			that.$post(".deleteServers")
				.params({
					serverIds: this.checkedServerIds
				})
				.success(function () {
					utils.reload()
				})
		})
	}
}