<template>
	<div class="hw-container">
		<Loading :top="200" bgColor="rgba(103, 103, 103, 0.27)" type="1" v-show="isLoading"></Loading>
		<div class="hw-box dark-iview-split">

			<Split v-model="split1" ref="leftSplit">
				<div slot="left" class="demo-split-pane">
					<!-- 投票活动列表 -->
					<div class="hw-col hw-list-box" v-if="!isFromRecord">
						<div class="hw-box-header">
							<span>{{ this.$t('vote.list') }}</span>
							<span>
								<Icon type="md-trash" class="to-create-icon" @click="onDeleteVote"
									style="margin-left:10px"
									v-if="voteList.length && ($access.can('admin.*|schoolAc-upd') || isPrivate)" />
								<Icon type="md-add" class="to-create-icon" @click="goToCreate"
									v-if="($access.can('admin.*|schoolAc-upd') || isPrivate)" />
							</span>
						</div>
						<vuescroll>
							<Loading :top="200" bgColor="rgba(103, 103, 103, 0.27)" type="1" v-show="isLoadList">
							</Loading>
							<div class="hw-item-wrap">
								<div v-if="voteList.length === 0">
									<EmptyData :top="50"></EmptyData>
								</div>
								<div style="width:100%" v-else>
									<div :class='["hw-item",index === activeVoteIndex ? "item-active":""]'
										v-for="(item,index) in voteList" :key="index" @click="onVoteClick(item,index)">
										<p class="hw-item-name">{{ item.name }}</p>
										<div class="hw-item-info">
											<span class="hw-item-nums">
												<Icon type="md-time" size="14" style="margin-right:5px" />
												{{ $tools.formatTime(item.startTime,'yyyy-MM-dd hh:mm') }}
											</span>
											<span class="hw-item-status"
												:style="{ background: (item.progress === 'pending' ? '#0BADD4' : item.progress === 'going' ? '#088951' : '#949594')}">{{ item.progress === 'pending' ? $t('vote.pending') : item.progress === 'going' ? $t('vote.going') : $t('vote.finish') }}</span>
										</div>
									</div>
								</div>

							</div>
						</vuescroll>
					</div>
				</div>
				<div slot="right" class="demo-split-pane">
					<Split v-model="split2">
						<div slot="left" class="demo-split-pane" ref="voteFormBox">
							<!-- 投票基础信息展示 -->
							<div class="hw-col hw-info-box">
								<div class="hw-box-header">
									<span>{{ $t('vote.voteDetails') }}</span>
									<div class="hw-box-header-tools">
										<span class="hw-box-header-tools-tool"
											v-show="currentVote.progress === 'pending'">
											<Icon type="md-create" size="18" :title="$t('vote.edit')"
												@click="onEditVote"
												v-if="($access.can('admin.*|schoolAc-upd') || isPrivate)" />
										</span>
									</div>
								</div>
								<vuescroll ref="voteFormScroll">
									<div v-show="voteList.length === 0">
										<EmptyData :top="50"></EmptyData>
									</div>
									<div class="hw-info-wrap" v-show="voteList.length !== 0">
										<BaseVoteForm :editItem="currentVote" @onAddSuccess="onAddSuccess"
											ref="voteForm" @onCancelVote="onCancelVote"></BaseVoteForm>
									</div>
								</vuescroll>
							</div>
						</div>
						<div slot="right" class="demo-split-pane">
							<!-- 投票提交数据 -->
							<div class="hw-col hw-data-box">
								<div class="hw-box-header">
									<span>{{ $t('vote.voteResult') }}</span>
									<div class="hw-box-header-tools">
										<div>
											<span class="hw-box-header-tools-tool" @click="changeTableView"
												v-show="tableData.length && currentVote.progress !== 'pending'">
												<Icon type="md-podium" />
												{{ isOptionView ? $t('vote.stuListView') : $t('vote.optionView') }}
											</span>
										</div>
										<div>
											<Button class="btn-save" v-if="isFromRecord" icon="md-arrow-round-back"
												@click="goBackRecord">{{ $t('survey.backToRecord') }}</Button>
										</div>
										
									</div>
								</div>
								<div v-if="voteList.length === 0 || hasNewAdd || currentVote.progress === 'pending'">
									<EmptyData :top="50"></EmptyData>
								</div>
								<div class="hw-data-wrap" style="height:90%" v-else>
									<vuescroll>
										<BaseVoteTable :tableDatas="tableData" v-show="isOptionView"></BaseVoteTable>
										<BaseVoteSsTable :tableDatas="studentsTable" v-show="!isOptionView">
										</BaseVoteSsTable>
										<div style="display:flex">
											<BaseVotePie pieId="votePie" :pieData="studentsTable"
												v-show="studentsTable.length"></BaseVotePie>
											<BaseVoteBar pieId="votePie2" v-if="tableData.length" :pieData="tableData">
											</BaseVoteBar>
										</div>
									</vuescroll>
								</div>
							</div>
						</div>
					</Split>
				</div>
			</Split>
		</div>
	</div>
</template>
<script>
	import BaseVoteForm from '@/components/vote/BaseVoteForm'
	import BaseVoteTable from '@/components/vote/BaseVoteTable'
	import BaseVoteSsTable from '@/components/vote/BaseVoteSsTable'
	import BaseVotePie from '@/components/vote/BaseVotePie'
	import BaseVoteBar from '@/components/vote/BaseVoteBar'
	export default {
		components: {
			BaseVoteForm,
			BaseVoteTable,
			BaseVoteBar,
			BaseVotePie,
			BaseVoteSsTable
		},
		data() {
			return {
				split1: 0.2,
				split2: 0.35,
				tabIndex: 0,
				hasNewAdd: false,
				isLoading: false,
				isLoadList: false,
				isOptionView: true,
				isEdit: false,
				editable: false,
				voteList: [],
				studentsList: [],
				studentsTable: [],
				currentVote: {},
				editItem: null,
				activeVoteIndex: 0,
				voteTableData: [],
				tableData: [],
				addHwModal: false,
				isFromRecord: false
			}
		},
		created() {},
		methods: {

			// 校本课纲与个人课纲切换
			handleTabClick(index) {
				this.tabIndex = index
				setTimeout(() => {
					this.getVoteList(index === 0 ? 'school' : 'private')
				}, 500)
			},

			goBackRecord() {
				this.$router.back(-1)
			},

			/** 新增投票 */
			goToCreate() {
				let hasNoSaveVote = this.voteList.filter(i => !i.id).length
				if (hasNoSaveVote) {
					this.$Message.warning(this.$t('vote.isExistTip'));
				} else {
					let defaultVote = {
						name: this.$t('vote.defaultName'),
						code: this.tabIndex === 0 ? this.$store.state.userInfo.schoolCode : this.$store.state.userInfo
							.TEAMModelId,
						classes: [],
						options: [{
							code: 'A',
							value: ''
						}, {
							code: 'B',
							value: ''
						}],
						publishModel: '0',
						selectMax: 1,
						endTime: new Date(new Date().toLocaleDateString()).getTime() + 2 * 24 * 60 * 60 * 1000 - 1,
						startTime:new Date().getTime(),
						description: '',
						secret: false,
						progress: 'pending'
					}
					this.voteList.unshift(defaultVote);
					this.currentVote = defaultVote;
					this.editable = true
					this.hasNewAdd = true
					this.$refs.voteForm.voteFormEdit = true
				}

				this.$nextTick(() => {
					this.$refs.voteFormBox.scrollIntoView();
				})
			},


			changeTableView() {
				this.isOptionView = !this.isOptionView
			},

			/** 获取投票列表 */
			getVoteList(type) {
				this.isLoadList = true
				let params = {
					code: this.getCurCode,
					scope: this.getCurScope
				}
				this.$api.learnActivity.FindVote(params).then(res => {
					if (!res.error && res.votes) {
						if (res.votes.length) {
							let list = res.votes.reverse()
							this.voteList = list
							let queryId = this.$route.query.acId
							if(queryId && list.filter(i => i.id === queryId).length === 0){
								this.$Modal.confirm({
									title: this.$t('survey.questionaire.confirmTitle'),
									content: this.$t('survey.noFoundAc'),
									cancelText: ' ',
									onOk: () => {
										this.goBackRecord()
									},
									onCancel: () => {}
								});
							}
							let queryVote = queryId && list.filter(i => i.id === queryId).length ? list.filter(i =>
								i.id === queryId)[0] : list[0]
							let queryIndex = queryId ? list.indexOf(queryVote) : 0
							this.isFromRecord = Boolean(queryId)
							this.onVoteClick(queryVote, queryIndex)
						} else {
							this.voteList = []
						}
						this.isLoadList = false
					} else {
						this.$Message.error(this.$t('vote.getDataFailTip'))
					}
				}).catch(err => {
					this.$Message.error(this.$t('vote.serverErrorTip'))
					this.isLoadList = false
				})
			},

			/**
			 * 投票点击事件
			 * @param item
			 * @param index
			 */
			async onVoteClick(item, index) {
				console.log(item)
				console.log(index)
				let fullItem = item.id ? await this.getVoteDetails(item) : item
				this.currentVote = fullItem
				this.activeVoteIndex = index
				if (item.id && item.progress !== 'pending') this.getVoteStudents(fullItem, fullItem.classes)
				this.$refs.voteForm.voteFormEdit = false
				this.$refs.voteFormScroll.scrollTo({
						y: 0,
					},
					200,
					"easeInQuad"
				);
				this.hasNewAdd = false
				this.isOptionView = true
			},

			/* 获取投票活动的详细数据 */
			getVoteDetails(voteItem) {
				return new Promise((r, j) => {
					this.$api.learnActivity.FindVoteById({
						id: voteItem.id,
						code: voteItem.code,
					}).then(res => {
						if (!res.error) {
							r(res.vote)
						}
					}).catch(err => {
						j(err)
					})
				})
			},

			/* 获取正在进行中的投票活动的投票数据 */
			async getVoteRecord(voteItem) {
				return new Promise(async (r, j) => {
					// 如果是进行中的活动 则从cosmos获取实时作答数据
					if (voteItem.progress === 'going') {
						this.$api.learnActivity.FindVoteRecord({
							id: voteItem.id,
							code: voteItem.code,
						}).then(res => {
							if (!res.error) {
								r(res)
							}
						}).catch(err => {
							j(err)
						})
					} else { // 如果是已结束的活动 则从blob读取作答数据 
						try {
							let curItemRecord = await this.getBlobJsonFile(voteItem.scope, voteItem
								.recordUrl)
							r(curItemRecord)
						} catch (e) {
							j(e)
						}
					}

				})
			},

			/* 根据已结束的RecordUrl来获取投票结果数据 */
			getBlobJsonFile(scope, url) {
				return new Promise(async (resolve, reject) => {
					let blobHost = scope === 'private' ? JSON.parse(decodeURIComponent(localStorage
						.user_profile, "utf-8")).blob_uri : JSON.parse(decodeURIComponent(localStorage
						.school_profile, "utf-8")).blob_uri
					// 根据试卷的Blob地址 去读取JSON文件
					let sasString = scope === 'private' ? await this.$tools.getPrivateSas() : await this.$tools
						.getSchoolSas()
					try {
						let itemJson = JSON.parse(await this.$tools.getFile(blobHost + url + sasString.sas))
						resolve(itemJson)
					} catch (e) {
						reject(e)
					}
				})
			},


			/* 取消编辑投票（无ID状态） */
			onCancelVote() {
				this.voteList.splice(this.voteList.indexOf(this.currentVote), 1)
				if (this.voteList.length > 0) {
					this.onVoteClick(this.voteList[0], 0)
				} else {
					this.voteList = [];
					this.currentVote = {}
					this.activeVoteIndex = 0;
				}
			},

			/** 删除当前投票 */
			onDeleteVote() {
				this.$Modal.confirm({
					title: this.$t('vote.deleteVote'),
					content: this.$t('vote.deleteConfirmTip'),
					onOk: () => {
						this.isLoading = true
						if (this.currentVote.id) {
							this.$api.learnActivity.DeleteVote({
								id: this.currentVote.id,
								code: this.currentVote.code,
								scope: this.getCurScope
							}).then(res => {
								if (!res.error && res.flag) {
									console.log(this.voteList.indexOf(this.currentVote))
									this.voteList.splice(this.voteList.reverse().indexOf(this
										.currentVote), 1)
									setTimeout(() => {
										this.isLoading = false
										this.$Message.success(this.$t('vote.deleteSuc'))
										this.handleTabClick(this.$route.name === 'manageVote' ?
											0 : 1)
									}, 1000)

									// this.isLoading = false
									// this.$Message.success(this.$t('vote.deleteSuc'))
									// if (this.voteList.length) this.onVoteClick(this.voteList[0], 0)
								} else {
									this.isLoading = false
									this.$Message.error(this.$t('vote.deleteFail'))
								}
							}).catch(err => {
								this.isLoading = false
								this.$Message.error(this.$t('vote.deleteFail'))
							})
						} else {
							this.voteList.splice(this.voteList.indexOf(this.currentVote), 1)
							this.isLoading = false
							this.$Message.success(this.$t('vote.deleteSuc'))
							if (this.voteList.length) this.onVoteClick(this.voteList[0], 0)
						}
					}
				})
			},


			/**
			 * 获取投票关联的学生清单
			 * @param voteId 投票ID
			 */
			async getVoteStudents(voteItem) {
				this.isLoading = true
				try {
					let records = await this.getVoteRecord(voteItem)
					//  先查找 投票发布对象关联的学生清单 然后再去判断学生的作答情况
					console.log('当前投票的作答数据======', records)
					this.$api.schoolSetting.getClassroomStudent({
						school_code: this.$store.state.userInfo.schoolCode,
						ids: voteItem.classes,
						scope: voteItem.scope
					}).then(res => {
						if (!res.error && res.stus.length) {
							let list = []
							res.stus.forEach(classStus => {
								classStus.forEach(i => {
									list.push({
										id: i.id,
										name: i.name,
										no: i.no,
										classroomName: i.className
									})
								})
							})

							// 要根据作答情况 结合两张表 处理表格显示的数据 
							if (records.options.length) {
								let arr = []
								this.studentsTable = list
								records.options.forEach((item, index) => {
									arr.push({
										option: item.code ? this.$t('vote.option') + (index +
											1) : this.$t('vote.noVote'),
										key: item.code || '',
										result: new Array(item.count).fill('1')
									})
								})
								this.studentsTable.forEach(i => {
									let matchList = records.records.filter(j => j.userid === i.id)
									i.option = matchList.length ? Object.keys(matchList[0].opt).join(
										',') : null
								})
								console.log(arr)
								console.log(this.studentsTable)
								this.tableData = arr
							} else {
								this.studentsTable = []
								this.tableData = []
							}
						} else {
							this.$Message.error(this.$t('vote.getDataFailTip'))
						}
					}).catch(err => {
						this.$Message.error(this.$t('vote.getClassDataFailTip'))
					}).finally(() => {
						this.isLoading = false
					})
				} catch (e) {
					this.isLoading = false
				}

			},


			// 提取富文本内容中的文本
			getSimpleText(html) {
				var r = /<(?!img|video|audio).*?>/g;
				return html.replace(r, "");
			},

			/** 投票编辑事件 */
			onEditVote() {
				this.editItem = this.currentVote
				console.log(this.editItem)
				this.isEdit = true
				this.editable = true
				if (this.$refs.voteForm.voteFormEdit) {
					this.onVoteClick(this.currentVote, this.activeVoteIndex)
				}
				this.$refs.voteForm.voteFormEdit = !this.$refs.voteForm.voteFormEdit

			},


			/** 新增投票成功回调 */
			onAddSuccess() {
				//this.addHwModal = false
				this.handleTabClick(this.$route.name === 'manageVote' ? 0 : 1)
				this.hasNewAdd = false
			}
		},
		mounted() {
			if (this.$route.query.acId) {
				this.isFromRecord = true
				this.split1 = 0
				this.split2 = 0.3
				this.$refs.leftSplit.$el.getElementsByClassName('ivu-split-trigger-con')[0].style.display = 'none'
			}
		},
		computed: {
			getCurCode() {
				return this.$route.name === 'personalVote' ? this.$store.state.userInfo.TEAMModelId : this.$store.state
					.userInfo.schoolCode
			},
			getCurScope() {
				return this.$route.name === 'personalVote' ? 'private' : 'school'
			},
			isPrivate() {
				return this.$route.name === 'personalVote'
			}
		},
		watch: {
			$route: {
				handler: function(to, from) {
					this.handleTabClick(this.$route.name === 'manageVote' ? 0 : 1)
				},
				immediate: true
			}
		}
	}
</script>
<style lang="less" scoped>
	@import "./ManageVote.less";
</style>
<style>
	.hw-modal .ivu-modal-content {
		background: #454545;
	}

	.hw-modal .ivu-modal-body {
		padding: 0;
	}

	.hw-modal .ivu-modal-header p,
	.hw-modal .ivu-modal-header-inner {
		color: #fff;
		font-size: 18px;
		font-weight: bold;
	}

	.hw-modal .ivu-modal-header {
		border-bottom: none;
	}

	.hw-modal .hw-modal-box {
		height: 600px;
		max-height: 600px;
		padding: 15px;
	}
</style>
