<template>
	<div ref="body">

		<div class="prize">
			<span class="prize-text">{{ drawOption.prize_name }}</span>
		</div>
		<div class="slot counter_0">
			<b-row>
				<div>
					<i class="slot-text-dep">部門</i>
				</div>
				<div>
					<span class="slot-text">
						<i>0</i>
						<i>0</i>
						<i>0</i>
						<i>0</i>
					</span>
				</div>
				<div>
					<span class="slot-text"></span>
				</div>
			</b-row>
		</div>
		<div class="activity" :style="activitySpacing(activityName.length)">
			<span class="activity-text">
				{{ activityName }}
			</span>
		</div>
		<div>
			<button class="menu" @click="showDrawMenu()"></button>
		</div>
		<div>
			<button class="draw" @click="draw()"></button>
		</div>

		<!--Model Start-->
		<b-modal ref="draw-menu" title="獎項列表" centered no-stacking hide-footer>
			<b-card style="height:75vh;">
				<b-table responsive hover sticky-header=true :items="prizeList" bordered :fields="prizeTableFields"
					@row-clicked="click" style="max-height: 57vh; overflow: auto;">
					<template #cell(ICON)="data">
						<div class="text-center">
							<feather-icon :icon="data.value" />
						</div>
					</template>
				</b-table>
				<b-button v-ripple.400="'rgba(255, 255, 255, 0.15)'" class="mt-3" variant="outline-primary" block
					@click="showAddPrize">
					加碼
				</b-button>
			</b-card>
		</b-modal>
		<b-modal ref="draw-modal" id="draw-modal" centered title="抽獎" no-stacking hide-footer>
			<label>獎品:</label>
			<b-form-input v-model="drawOption.prize_name" :disabled=true />
			<br>
			<label>地區: </label>
			<v-select multiple v-model="drawOption.region" :options="regionOption" />
			<br>

			<b-button v-ripple.400="'rgba(255, 255, 255, 0.15)'" class="mt-3" variant="outline-secondary" block
				@click="hideModal">
				Close
			</b-button>
			<b-button v-ripple.400="'rgba(255, 255, 255, 0.15)'" class="mt-2" variant="primary" block @click="hideModal">
				Accept
			</b-button>
		</b-modal>
		<b-modal ref="draw-error" centered title="抽獎錯誤" no-stacking hide-footer>
			<b-card-text class="my-1 text-center">
				抽獎錯誤
			</b-card-text>
			<b-button v-ripple.400="'rgba(255, 255, 255, 0.15)'" class="mt-3" variant="outline-secondary" block
				@click="hideModal">
				Close
			</b-button>
		</b-modal>
		<b-modal ref="add-prize" centered title="加碼" no-stacking hide-footer>
			<label>獎品:</label>
			<b-form-input v-model="addPrizeOption.name" />
			<br>
			<label>加碼者: </label>
			<b-form-input v-model="addPrizeOption.provider" />
			<br>
			<label>數量: </label>
			<b-form-spinbutton v-model="addPrizeOption.count" min="1" />

			<b-button v-ripple.400="'rgba(255, 255, 255, 0.15)'" class="mt-3" variant="outline-secondary" block
				@click="hideModal">
				Close
			</b-button>
			<b-button v-ripple.400="'rgba(255, 255, 255, 0.15)'" class="mt-2" variant="primary" block @click="addPrize">
				Accept
			</b-button>
		</b-modal>
		<!-- modal End-->

		<div class="func-group">
			<button class="func-btn left" @click.prevent="restart"><img class="func-img" src="/restart.png"></button>
			<button class="func-btn right" @click.prevent="recieve"><img class="func-img" src="/recieve.png"></button>
		</div>
		<div class="counter">
			<div class="top">
				<span class="counter-text">已抽:{{ drawnCount }}</span>
			</div>
			<div class="bottom">
				<span class="counter-text">未抽:{{ notDrawnCount }}</span>
			</div>
		</div>
	</div>
</template>

<script>
import BCardCode from '@core/components/b-card-code/BCardCode.vue'
import { BRow, BCol, BCard, BCardText, BLink, BTable, BModal, BFormInput, BFormSpinbutton, BButton, BFormCheckbox, BFormRadio, BImg } from 'bootstrap-vue'
import Ripple from 'vue-ripple-directive'
import useJwt from '@/auth/jwt/useJwt'
import vSelect from 'vue-select'
import { VueGoodTable } from 'vue-good-table'
import 'vue-select/dist/vue-select.css';

import Pusher from 'pusher-js';

export default {
	components: {
		BRow,
		BCol,
		BCard,
		BCardText,
		BLink,
		BTable,
		BModal,
		BFormInput,
		BFormSpinbutton,
		BButton,
		BFormCheckbox,
		BFormRadio,
		BImg,
		VueGoodTable,
		vSelect,
	},
	directives: {
		Ripple,
	},
	data() {
		return {
			activityName: "亞新春酒聯歡餐會",

			activityId: this.$route.params.activity_id,
			activity: {},
			userList: [],
			departmentList: [],

			fields: ['獎項', '數量'],
			regionOption: ['北區', '中區', '南區', '來賓'],
			region: ['北區', '中區', '南區', '來賓'],
			drawMax: 1,
			drawOne: true,

			prizeName: '',
			prizeId: '',
			drawList: [],
			department_name: "",
			user_id: "",
			userID: ["", "", "", ""],
			user_name: "",

			drawnCount: 0,
			notDrawnCount: 0,
			isDrawn: false,

			// departmentList: [
			// 	"行管部庶務科",
			// 	"人力資源科",
			// 	"行管部文書科",
			// 	"南區辦事處",
			// 	"中區辦事處",
			// 	"工程管理一部",
			// 	"工程管理二部",
			// 	"發展與企畫部",
			// 	"工程製圖科",
			// 	"工務部",
			// 	"大地工程部",
			// 	"財務部",
			// 	"運輸土木部",
			// 	"城鄉發展部",
			// 	"軌道工程部",
			// 	"董事長室",
			// 	"總經理室",
			// 	"企業發展中心",
			// 	"成本中心",
			// 	"資訊中心",
			// 	"環境水務部",
			// 	"環境永續部",
			// 	"機電工程部",
			// 	"結構工程部",
			// 	"工程設計群",
			// 	"工程監理群",
			// 	"總管理處",
			// 	"建築及設施群",
			// 	"數位發展部",
			// 	"淡海輕軌專案",
			// 	"安坑輕軌專案",
			// 	"先進技術中心",
			// 	"塭仔圳專案",
			// 	"萬大市場專案",
			// 	"來賓"
			// ],
			messages: [],
			prizeList: [],

			prizeTableFields: ['name', 'provider', 'count'],
			recipientsTableFields: ['prize_name', 'user_id', 'user_name', 'created_at'],
			regionOption: ['北區', '中區', '南區', '來賓'],

			drawOption: {
				activity_id: this.$route.params.activity_id,
				prize_id: '0',
				prize_name: '',
				region: ['北區', '中區', '南區', '來賓'],
				draw_one: true,
			},
			addPrizeOption: {
				activity_id: this.$route.params.activity_id,
				name: '',
				provider: '',
				count: 1,
			},
		}
	},
	created() {

		// Pusher.logToConsole = true;

		var pusher = new Pusher('9fb7f6f0141efc7e1293', {
			cluster: 'ap3'
		});

		var channel = pusher.subscribe('my-channel');
		channel.bind('set-event', (data) => {
			let message = data.message
			console.log(message);


			if (message == "updateData") {
				this.updateDataset()
			} else if (message && message.prize_id) {
				this.clearResult()
				this.drawOption = message;
				this.drawList = [];
				this.count();
			}
		});

		useJwt.postData('/api/activity/show', { activity_id: this.activityId }).then(res => {
			this.activity = res.data;
			this.activityName = res.data.activity_name
			if (this.activityName.includes("年度")) {
				this.activityName = '亞新' + this.activityName.split('年度')[1];
			}
		});

		useJwt.postData('/api/check_in/index_by_activity', { activity_id: this.activityId }).then(res => {
			this.userList = res.data;
		});

		useJwt.postData('/api/prize/index_by_activity', { activity_id: this.$route.params.activity_id }).then(res => {
			this.prizeList = res.data;
		});

		useJwt.postData('/api/department/index').then(res => {
			this.departmentList = Object.values(res.data);
		});

		this.bodyListener = (e) => {
			if ((e.keyCode === 13 || e.keyCode === 32) && e.target === document.body) {
				console.log("enter");
				this.draw();
			}
		}
		document.body.addEventListener('keyup', this.bodyListener, false)
	},
	methods: {
		dateFormat(date) {
			var d = new Date(date);
			return d.getFullYear()
				+ '/' + (d.getMonth() + 1).toString().padStart(2, '0')
				+ '/' + d.getDay().toString().padStart(2, '0')
				+ '/' + d.getHours().toString().padStart(2, '0')
				+ ':' + d.getMinutes().toString().padStart(2, '0')
				+ ':' + d.getSeconds().toString().padStart(2, '0');
		},
		counterId(id) {
			return "counter_" + id;
		},
		showDraw() {
			this.$refs['draw-modal'].show();
		},
		showDrawMenu() {
			this.clearResult()
			this.$refs['draw-menu'].show();
		},
		showAddPrize() {
			this.$refs['add-prize'].show();
		},
		showDrawError() {
			this.$refs['draw-error'].show();
		},
		hideModal() {
			this.$refs['draw-modal'].hide();
			this.$refs['draw-error'].hide();
			this.$refs['add-prize'].hide();
			this.updateDataset();
		},
		updateDataset() {
			useJwt.postData('/api/prize/index_by_activity', { activity_id: this.$route.params.activity_id }).then(res => {
				this.prizeList = res.data;
			});
		},
		click(params) {
			if (params.count > 0) {
				this.drawOption.prize_name = params.name;
				this.drawOption.prize_id = params.id;
				this.showDraw();
				this.count();
			} else {
				this.showDrawError();
			}
		},
		draw() {
			if (!this.isDrawn) {
				this.isDrawn = true;
				useJwt.postData('/api/draw/draw', this.drawOption).then(res => {
					if (res.data[0]["user_id"]) {
						this.drawList = res.data;
						if (this.drawList.length == 1) {
							this.department_name = this.drawList[0].department_name;
							this.user_id = this.drawList[0].user_id;
							this.user_name = this.drawList[0].user_name;
						}
						setTimeout(() => {
							this.animate();
						}, 500);
					} else {
						this.showDrawError();
						console.log("draw error: " + res.data);
					}
				});
			}

		},
		recieve(e) {
			e.currentTarget.blur();
			if (this.isDrawn && this.isAnimated) {
				var idList = [];
				this.drawList.forEach(element => {
					idList.push(element.user_id);
				});
				useJwt.postData('/api/draw/store', {
					users: idList,
					prize_id: this.drawOption.prize_id,
				}).then(res => {
					if (res.data) {
						console.log("store success");
					} else {
						console.log("store error");
					}
					this.count();
					this.clearResult();
				});
			}
		},
		restart(e) {
			e.currentTarget.blur();
			if (this.isDrawn && this.isAnimated) {
				var idList = [];
				this.drawList.forEach(element => {
					idList.push(element.user_id);
				});
				useJwt.postData('/api/draw/donate', { users: idList }).then(res => {
					if (res.data) {
						console.log("donate success");
					} else {
						console.log("donate error");
					}
					this.clearResult();
				});
			}
		},
		addPrize() {
			useJwt.postData('/api/prize/store', this.addPrizeOption).then(res => {
				if (res.data) {
					console.log("add prize success");
				} else {
					console.log("add prize error");
				}
				this.hideModal();
			});
		},
		animate() {
			var departmentList = this.departmentList;
			var numbers = "0123456789"
			var string = numbers;

			this.drawList.forEach((element, index) => {
				var departmentName = element.department_name;
				var deps = document.querySelectorAll("div.slot.counter_" + index + " > div > div:nth-child(1) > i")
				var allCounters = document.querySelectorAll("div.slot.counter_" + index + " > div > div:nth-child(2) > span > i");

				deps.forEach((el) => {
					var duration = 1000;
					var interval = setInterval(() => {

						el.innerText = departmentList[Math.floor(Math.random() * departmentList.length)];
						duration = duration - 50;
						if (duration <= 0) {
							clearInterval(interval);
							el.innerText = departmentName;
							this.department_name = departmentName;
						}
					}, 50);
				});
				allCounters.forEach((el, i) => {
					var duration = 500 + i * 1000;
					var interval = setInterval(e => {
						el.innerText = string.charAt(Math.random() * string.length);
						duration = duration - 50;
						if (duration <= 0) {
							clearInterval(interval);
							el.innerText = element.user_id[i];
							if (i == 3) {
								document.querySelector("div.slot.counter_" + index + " > div > div:nth-child(3) > span").innerText = element.user_name;
								this.user_id = element.user_id;
								this.isAnimated = true;
							}
						}
					}, 50);
				});
			});
		},
		clearResult() {
			document.querySelector("div.slot.counter_0 > div > div:nth-child(1) > i").innerText = "部門";
			document.querySelectorAll("div.slot.counter_0 > div > div:nth-child(2) > span > i")[0].innerText = "0";
			document.querySelectorAll("div.slot.counter_0 > div > div:nth-child(2) > span > i")[1].innerText = "0";
			document.querySelectorAll("div.slot.counter_0 > div > div:nth-child(2) > span > i")[2].innerText = "0";
			document.querySelectorAll("div.slot.counter_0 > div > div:nth-child(2) > span > i")[3].innerText = "0";
			document.querySelector("div.slot.counter_0 > div > div:nth-child(3) > span").innerText = "";
			this.isDrawn = false;
			this.isAnimated = false;
		},
		count() {
			useJwt.postData('/api/prize/count_by_prize', { prize_id: this.drawOption.prize_id }).then(res => {
				this.drawnCount = res.data.drawnCount;
				this.notDrawnCount = res.data.notDrawnCount;
			});
		},
		activitySpacing(length) {
			return 'letter-spacing: ' + (725 - (length * 75)) / (length - 1) + 'px;';
		},
	},
	watch: {
		prizeId: function (newValue) {
			this.count();
		}
	}
}
</script>

<style lang="scss">
@import '~@resources/scss/vue/libs/vue-select.scss';

@font-face {
	font-family: '新微軟正黑體';
	unicode-range: U+7db0, U+78A7, U+7B75;
	font-style: normal;
	font-weight: bold;
	src: local(MS Gothic), local(Yu Gothic);
}

@font-face {
	font-family: '新微軟正黑體';
	unicode-range: U+7db0, U+78A7, U+7B75;
	font-style: normal;
	font-weight: normal;
	src: local(微軟正黑體), local(Microsoft JhengHei);
}


@font-face {
	font-family: '全真海報體';
	src: url('/fonts/AVPOPV.woff') format("woff"),
		url('/fonts/AVPOPV.ttf') format("truetype"),
		url('/fonts/AVPOPV.eot') format("embedded-opentype");
}

html,
body {
	width: 100%;
}

body {
	background-color: white;
	background-image: url('/MAA03.jpg');
	background-size: 100%;
	background-repeat: no-repeat;
	background-position: left top;
	font-family: 'Open Sans', Verdana, Geneva, "新微軟正黑體", 'Microsoft JhengHei', "微軟正黑體", sans-serif,'全真海報體';
}


.arrow-right {
	right: 0;
	position: absolute;
	cursor: pointer;
}

.arrow-left {
	left: 0;
	position: absolute;
	cursor: pointer;
}

body::-webkit-scrollbar {
	display: none;
}

.slot {
	width: 970px;
	height: 250px;
	position: absolute;
	top: 425px;
	color: black;
	left: 380px;
}

.slot-text-dep {
	display: flex;
	justify-content: center;
	align-items: center;
	height: 260px;
	width: 330px;
	font-size: 46px;
	-webkit-text-stroke: 1px white;
	font-weight: bold;
}

.slot-text {
	display: flex;
	justify-content: center;
	align-items: center;
	height: 260px;
	width: 330px;
	font-size: 80px;
	-webkit-text-stroke: 1px white;
	font-weight: bold;
}

.prize {
	position: absolute;
	left: 390px;
	top: 280px;
	width: 950px;
}

.prize-text {
	display: flex;
	justify-content: center;
	align-items: center;
	height: 120px;
	-webkit-text-stroke: 2px white;
	font-weight: bold;
	color: #966A13;
	font-size: 73px;
	text-shadow:
		5px 5px 0 #222222,
		-1px -1px 0 #222222,
		1px -1px 0 #222222,
		-1px 1px 0 #222222,
		1px 1px 0 #222222;
	letter-spacing: -2px;
}

.activity {
	position: absolute;
	left: 1702px;
	top: 255px;
	width: 30px;
	height: 780px;
}

.activity-text {
	font-family: '全真海報體';
	display: flex;
	justify-content: center;
	align-items: center;
	-webkit-text-stroke: 2px #F4C951;
	-webkit-writing-mode: vertical-lr;
	writing-mode: vertical-lr;
	// font-weight: bold;
	color: #000;
	font-size: 75px;
	// text-shadow:
	// 	5px 5px 0 #222222,
	// 	-1px -1px 0 #222222,
	// 	1px -1px 0 #222222,
	// 	-1px 1px 0 #222222,
	// 	1px 1px 0 #222222;
}

.menu {
	width: 191px;
	height: 179px;
	background-color: rgba(0, 0, 0, 0);
	position: absolute;
	right: 67px;
	top: 12px;
	border: 0px;
}

.draw {
	width: 123px;
	height: 123px;
	background-color: rgba(0, 0, 0, 0);
	position: absolute;
	right: 330px;
	top: 288px;
	border: 0px;
}

.func-group {
	position: absolute;
	bottom: 95px;
	left: 460px;
	width: 800px;
}

.func-btn {
	background-color: #0000 !important;
	border-color: #0000 !important;
}

.func-img {
	width: 250px;

}

.counter {
	position: absolute;
	top: 75px;
	left: 100px;
}

.counter-text {
	font-size: 56px;
	color: #000;
	font-weight: bold;
	-webkit-text-stroke: 1px white;
}

.draw-img {
	width: 159px;
	position: absolute;
	top: 256px;
	left: 260px;
}

.top {
	float: top;
}

.bottom {
	float: bottom;
}

.right {
	float: right;
}

.left {
	float: left;
}
</style>
