<template>
	<div class="container">
		<div class="row">
			<div class="col-md-12">
				<div v-for="position in positions" :key="position.id">
					<h5>{{ position.name }}</h5>
					<admin-data-table
						:headers="finalTableHeaders"
						:items="finalRowsByPosition(position.id)"
						:loading="finalLoading"
						:items-per-page="10"
						:show-pagination="true"
						empty-text="Tiada keputusan"
						:exportable="true"
						:export-file-name="'keputusan-akhir-' + position.id"
					>
						<template v-slot:item-percentage="{ item }">
							{{ item.percentage }}
						</template>
					</admin-data-table>
					<hr />
				</div>
			</div>
		</div>
	</div>
</template>

<script>
export default {
	data: function () {
		return {
			nominees: [],
			results: [],
			partylists: [],
			positions: [],
			finalLoading: false,
			finalTableHeaders: [
				{ title: 'No. Anggota', key: 'no_anggota', sortable: true },
				{ title: 'Nama', key: 'name', sortable: true },
				{ title: 'Unit', key: 'unit', sortable: true },
				{ title: 'Undian', key: 'votes', sortable: true },
				{ title: 'Peratus (%)', key: 'percentage', sortable: true }
			]
		}
	},

	methods: {
		finalRowsByPosition: function (positionId) {
			var vm = this;
			var rows = [];

			// rows with votes
			this.results.forEach(function (result) {
				if (result.position_id == positionId) {
					var n = vm.getNominee(result.nominee_id) || {};
					rows.push({
						no_anggota: n.no_anggota || '',
						name: n.name || '',
						unit: n.unit || '',
						votes: result.votes || 0,
						percentage: vm.calculatePercentage(result.votes || 0, positionId)
					});
				}
			});

			// rows without votes
			this.no_votes.forEach(function (nv) {
				if (nv.position_id == positionId) {
					rows.push({
						no_anggota: nv.no_anggota || '',
						name: nv.name || '',
						unit: nv.unit || '',
						votes: 0,
						percentage: '0.00'
					});
				}
			});

			// total row (kept as a normal row so it exports too)
			rows.push({
				no_anggota: '',
				name: 'Jumlah Undian',
				unit: '',
				votes: this.calculateTotalVotes(positionId),
				percentage: ''
			});

			// Sort by votes desc, but keep total row last
			var total = rows.pop();
			rows.sort(function (a, b) {
				return (b.votes || 0) - (a.votes || 0);
			});
			rows.push(total);

			return rows;
		},

		getNominee: function (id) {
			let nominees = this.nominees;
			for (var i in nominees)
				if (id == nominees[i]['id'])
					return nominees[i];
			return {};
		},

		getPartylist: function (id) {
			let partylists = this.partylists;
			for (var i in partylists)
				if (id == partylists[i]['id'])
					return partylists[i]['name'];
			return 'No Partylist';
		},

		calculatePercentage(votes, positionId) {
			const totalVotes = this.results
				.filter(result => result.position_id === positionId)
				.reduce((total, result) => total + result.votes, 0);

			return totalVotes === 0 ? '0.00' : ((votes / totalVotes) * 100).toFixed(2);
		},

		calculateTotalVotes(positionId) {
			return this.results
				.filter(result => result.position_id === positionId)
				.reduce((total, result) => total + result.votes, 0);
		}
	},

	created: function () {
		this.util.notify('Loading please wait...', 'loading');
		var vm = this;
		this.finalLoading = true;
		axios.get(config.API + 'election/result/' + this.election_id)
			.then(response => {
				$.notifyClose();
				vm.nominees = response.data.nominee;
				vm.results = response.data.result;
				vm.partylists = response.data.partylist;
				vm.positions = response.data.position;
			})
			.catch(error => {
				$.notifyClose();
				vm.util.showResult(error, 'error');
			})
			.finally(function () {
				vm.finalLoading = false;
			})
	},

	computed: {
		election_id: function () {
			return this.$route.params.election_id;
		},

		no_votes: function () {
			let nominees = this.nominees;
			let results = this.results;
			let no_votes = [];
			for (var i in nominees) {
				var hasvote = false;
				for (var y in results) {
					if (results[y]['nominee_id'] == nominees[i]['id'])
						hasvote = true;
				}
				if (!hasvote)
					no_votes.push(nominees[i]);
			}
			return no_votes;
		}

	}
}
</script>