<template>
	<div class="system-edit-post-container">
		<el-form size="default" label-width="80px">
			<el-card shadow="hover" header="战令配置">
				<template #header>
					战令配置
					<el-button v-show="item.show === false" @click="item.show = true" class="button-caret" type="text">
						<el-icon>
							<ele-CaretBottom />
						</el-icon>
					</el-button>
					<el-button v-show="item.show === true" @click="item.show = false" class="button-caret" type="text">
						<el-icon>
							<ele-CaretTop />
						</el-icon>
					</el-button>
				</template>
				<div v-show="item.show">
					<div class="flex-warp">
						<el-form-item label="期数" prop="periodId">
							<el-select class="m-2" placeholder="选择期数" filterable v-model="props.periodId">
								<el-option v-for="item in unique(battlePassConfig)" :key="item.PeriodId" :label="item.PeriodId + '期'" :value="item.PeriodId" />
							</el-select>
						</el-form-item>
						<el-form-item label="开始时间" prop="beginTime">
							<el-date-picker type="date" size="default" v-model="props.beginTime" placeholder="开始时间" format="YYYY-MM-DD" value-format="x" />
						</el-form-item>
						<el-form-item label="结束时间" prop="endTime">
							<el-date-picker type="date" size="default" v-model="props.endTime" placeholder="结束时间" format="YYYY-MM-DD" value-format="x" />
						</el-form-item>
						<el-button size="default" :type="checkTimeColor" :disabled="query.serverIds.length == 0" class="ml10" @click="onCheckTime">
							<div v-if="checkTime === 1">
								<el-icon>
									<ele-Check />
								</el-icon>
							</div>
							<div v-else-if="checkTime === 2">
								<el-icon>
									<ele-Close />
								</el-icon>
							</div>
							检查时间
						</el-button>
						<el-button size="default" class="ml10" @click="onSubmit" :disabled="query.serverIds.length == 0 || checkTime != 1">
							<div v-if="checkTime === 1">
								<el-icon>
									<ele-Check />
								</el-icon>
							</div>
							<div v-else-if="checkTime === 2">
								<el-icon>
									<ele-Close />
								</el-icon>
							</div>
							<el-icon>
								<ele-Promotion />
							</el-icon>
							发布
						</el-button>
					</div>
					<div class="flex-warp">
						<el-form-item prop="periodId" label="显示期数">
							<el-select size="default" placeholder="请选择显示期数" filterable v-model="query.periodId" @change="getProp">
								<el-option label="全部" value="" />
								<el-option v-for="item in unique(battlePassConfig)" :key="item.PeriodId" :label="item.PeriodId + '期'" :value="item.PeriodId" />
							</el-select>
						</el-form-item>
					</div>

					<div class="flex-warp">
						<el-table
							ref="tableRef"
							:data="servers"
							:span-method="objectSpanMethod"
							style="width: 100%"
							stripe
							border
							@selection-change="handleSelectionChange"
							row-key="id"
						>
							<el-table-column prop="platform" label="平台" show-overflow-tooltip width="80">
								<template #default="scope">
									<div v-if="scope.row.sort == 0">其他</div>
									<div v-else-if="scope.row.sort == 1">ios</div>
									<div v-else-if="scope.row.sort == 2">官服</div>
									<div v-else-if="scope.row.sort == 3">渠道</div>
									<div v-else>其他</div>
								</template>
							</el-table-column>
							<el-table-column prop="area" label="区服编号" width="85">
								<template #default="scope"> {{ scope.row.area }}区</template>
							</el-table-column>
							<el-table-column prop="name" label="服务器名称" show-overflow-tooltip width="200" />
							<el-table-column prop="periodId" label="当前期数" show-overflow-tooltip width="85" />
							<el-table-column prop="state" label="状态" show-overflow-tooltip width="100" />
							<el-table-column prop="StartTime" label="开始时间" show-overflow-tooltip width="200" />
							<el-table-column prop="EndTime" label="结束时间" show-overflow-tooltip width="200" />
							<el-table-column type="selection" width="55" :selectable="selectable" />
							<el-table-column prop="" label="开关" show-overflow-tooltip width="100" />
							<el-table-column prop="" label="操作" width="100">
								<template #default="scope">
									<el-button size="default" class="ml10" @click="onUpdate(scope.row)"> 修改</el-button>
								</template>
							</el-table-column>
						</el-table>
					</div>
				</div>
			</el-card>
		</el-form>
	</div>
</template>
<script lang="ts">
import { defineComponent, onMounted, reactive, ref, toRefs, unref } from 'vue';
import { gameGMCheckBattlePassCheck, gameGMGetBattlePass, gameGMInsertBattlePass } from '/@/api/game/gameConfig';
import BattlePassConfigCategory from '/@/api/config/BattlePassConfigCategory.json';
import { ElLoading, ElMessage } from 'element-plus';
import type { TableInstance } from 'element-plus';
import { uniquePeriodId, zeroFill } from '/@/utils/utils';
import { serverList } from '/@/utils/game';

interface Props {
	id: string;
	periodId: string;
	beginTime: number;
	endTime: number;
}

interface TableDataState {
	props: Props;
	query: object;
	battlePassList: object[];
	centerDialogVisible: boolean;
	checkTime: number;
	checkTimeColor: string;
	check: boolean;
	lastDate: number;
	curDate: number;
	selectModel: string;
	battlePassConfig: object;
	servers: object;
}

interface SpanMethodProps {
	row: object;
	column: object;
	rowIndex: number;
	columnIndex: number;
}

export default defineComponent({
	name: 'systemServerBattlePassUpdate',
	setup: function () {
		const formRef = ref<HTMLElement | null>(null);
		const tableRef = ref();
		let date = new Date();
		let getBeginTime = (date: number) => {
			return new Date(date).setHours(0, 0, 0);
		};
		let getEndTime = (date: number) => {
			return new Date(date + 20 * 24 * 60 * 60 * 1000).setHours(0, 0, 0);
		};
		const state = reactive<TableDataState>({
			lastDate: 0,
			curDate: 0,
			check: false,
			item: { topShow: true, show: true, giftShow: true },
			query: {
				serverIds: [],
				periodId: '',
			},
			props: {
				id: '',
				periodId: BattlePassConfigCategory[0].PeriodId,
				beginTime: getBeginTime(date.getTime()),
				endTime: getEndTime(date.getTime()),
			},
			battlePass: [],
			battlePassConfig: BattlePassConfigCategory,
			centerDialogVisible: false,
			checkTime: 0,
			checkTimeColor: 'primary',
			selectModel: '',
			servers: [],
		});

		const onCheckTime = () => {
			if (!state.props.beginTime || !state.props.endTime) {
				ElMessage.error('活动时间未填写完整');
				return;
			}
			let now = new Date();
			if (new Date(state.props.endTime) < now) {
				ElMessage.error('结束时间小于当前时间，请检查！');
				return;
			}
			if (new Date(state.props.endTime) < new Date(state.props.beginTime)) {
				ElMessage.error('结束时间小于开始时间，请检查！');
				return;
			}
			if (state.query.serverIds.length == 0) {
				ElMessage.error('未选择服务器，请检查！');
				return;
			}
			const loading = ElLoading.service({
				lock: true,
				text: 'Loading',
				background: 'rgba(0, 0, 0, 0.7)',
			});
			console.log(state.query.serverIds);
			for (let i in state.query.serverIds) {
				let data = {
					BeginTime: state.props.beginTime,
					EndTime: state.props.endTime,
					Server: state.query.serverIds[i],
					PeriodId: state.props.periodId,
				};
				onCheck(loading, data);
			}
			if (state.checkTime != 0) {
				state.checkTime = 2;
			}
		};
		const onCheck = (loading, data) => {
			gameGMCheckBattlePassCheck(data)
				.then((res) => {
					console.log('onCheckTime:', res);
					if (!res || Number(res.code) != 0 || !res.data || res.data.total > 0) {
						loading.close();
						// state.checkTime = 2;
						state.checkTimeColor = 'danger';
						ElMessage.error('活动时间重合');
						console.log(tableRef.value);
						var value = state.servers.find((r) => r.Id == data.Server);
						tableRef.value.toggleRowSelection(value, false);
						state.query.serverIds.splice(state.query.serverIds.indexOf(data.Server), 1);
						return;
					}
					loading.close();
					state.checkTime = 1;
					state.checkTimeColor = 'primary';
					ElMessage.success('验证通过');
				})
				.catch(() => {
					loading.close();
					state.checkTimeColor = 'danger';
					console.log(tableRef);
					var value = state.servers.find((r) => r.Id == data.Server);
          tableRef.value.toggleRowSelection(value, false);
					state.query.serverIds.splice(state.query.serverIds.indexOf(data.Server), 1);
				});
		};
		const onSubmit = () => {
			const loading = ElLoading.service({
				lock: true,
				text: 'Loading',
				background: 'rgba(0, 0, 0, 0.7)',
			});
			state.centerDialogVisible = false;
			const formWrap = unref(formRef) as any;
			if (!formWrap) return;
			formWrap.validate((valid: boolean) => {
				console.log('monthly:', valid, state.props);
				if (!valid) {
					ElMessage.error('有未配置完成的部分，请检查！');
					return;
				}

				let monthly = onState();
				console.log('monthly0:', monthly);
				if (!monthly.BeginTime || !monthly.EndTime) {
					ElMessage.error('有未配置完成的部分1，请检查！');
					return;
				}

				console.log('monthly1:', monthly);
				gameGMInsertBattlePass(monthly)
					.then(() => {
						ElMessage.success('活动更新成功');
						state.check = false;
					})
					.finally(() => {
						loading.close();
					});
			});
		};
		onMounted(() => {
			state.props.id = '';
			state.rows = {};
			serverList().then((res) => {
				state.servers = res;
				for (let i in state.servers) {
					let server = state.servers[i];
					if (!state.rows[server.sort]) {
						state.rows[server.sort] = { num: 0, id: server.id };
					}
					state.rows[server.sort].num++;
					if (state.rows[server.sort].id > server.id) {
						state.rows[server.sort].id = server.id;
					}
				}
				console.log('serverList:', res);
			});
			getProp();
		});
		const onState = () => {
			let data = {
				BeginTime: state.props.beginTime,
				EndTime: state.props.endTime,
				serverIds: state.query.serverIds,
				PeriodId: state.props.periodId,
			};
			console.log('data: ', data);
			return data;
		};

		const getProp = () => {
			const loading = ElLoading.service({
				lock: true,
				text: 'Loading',
				background: 'rgba(0, 0, 0, 0.7)',
			});
			gameGMGetBattlePass({ periodId: state.query.periodId })
				.then((res) => {
					console.log('gameGMGetBattlePass: ', res);
					if (res.code == 0 && res.data && res.data.list) {
					}
				})
				.finally(() => {
					loading.close();
				});
		};

		const unique = (arr) => {
			return uniquePeriodId(arr);
		};
		const objectSpanMethod = ({ row, column, rowIndex, columnIndex }: SpanMethodProps) => {
			if (columnIndex === 0) {
				if (state.rows[row.sort].id == row.id) {
					return {
						rowspan: state.rows[row.sort].num,
						colspan: 1,
					};
				} else {
					return {
						rowspan: 0,
						colspan: 0,
					};
				}
			}
		};
		const handleSelectionChange = (selection: any[]) => {
			state.checkTime = 0;
			state.query.serverIds = selection.map((item) => item.id);
			console.log(state.query.serverId, selection);
		};
		// const getSelectionRows = (selection: any[]) => {
		// 	state.checkTime = 0;
		// 	state.query.serverIds = selection.map((item) => item.id);
		// 	console.log(state.query.serverId, selection);
		// };
		const selectable = (row) => ![].includes(row.id);
		return {
			selectable,
			handleSelectionChange,
			objectSpanMethod,
			onSubmit,
			formRef,
			unique,
			onCheckTime,
			getProp,
			zeroFill,
			...toRefs(state),
		};
	},
});
</script>

<style scoped lang="scss">
.table-item {
	margin-top: 10px;
	margin-bottom: -10px;
}

.box-card .el-card__header {
	background-color: #409eff;
	color: #fff;
}

::v-deep .el-table--striped .el-table__body tr.el-table__row--striped td {
	background: #f0ffd5;
}

.warning-row {
	background: #f0ffd5ff;
}

.white-row {
	background: #ffffff;
}

::v-deep .warning-row .el-table__body tr {
	background-color: #f0ffd5ff;
}

::v-deep .warning-row .el-table--enable-row-hover .el-table__body tr:hover > td {
	background-color: inherit;
}

::v-deep .warning-row .el-table__cell {
	background-color: #f0ffd5ff;
}
</style>
