<template>
	<div class="hw-container">
		<Loading :top="200" bgColor="rgba(103, 103, 103, 0.27)" type="1" v-show="isLoading"></Loading>
		<div class="hw-header" style="display: none;">
			<div>
				<span :class="tabIndex == 0 ? 'tab-active' : ''" @click="handleTabClick(0)">校本投票</span>
				<span :class="tabIndex == 1 ? 'tab-active' : ''" @click="handleTabClick(1)">个人投票</span>
			</div>
		</div>
		<div class="hw-box dark-iview-split">

			<Split v-model="split1">
				<div slot="left" class="demo-split-pane">
					<!-- 投票活动列表 -->
					<div class="hw-col hw-list-box">
						<div class="hw-box-header">
							<span>投票活动列表</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) }}</span>
											<span class="hw-item-status" :style="{ background: (item.progress === 'pending' ? '#0BADD4' : item.progress === 'going' ? '#088951' : '#949594')}">{{ item.progress === 'pending' ? '待发布' : item.progress === 'going' ? '进行中' : '已结束' }}</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">
							<!-- 投票基础信息展示 -->
							<div class="hw-col hw-info-box">
								<div class="hw-box-header">
									<span>投票详情</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="编辑" @click="onEditVote" v-if="($access.can('admin.*|schoolAc-upd') || isPrivate)" /></span>
									</div>
								</div>
								<vuescroll>
									<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>投票数据</span>
									<div class="hw-box-header-tools">
										<span class="hw-box-header-tools-tool" @click="changeTableView" v-show="tableData.length && currentVote.progress !== 'pending'">
											<Icon type="md-podium" />{{ isOptionView ? '学生清单视图' : '选项清单视图' }}</span>
									</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="tableData" v-show="tableData.length"></BaseVotePie>
											<BaseVoteBar pieId="votePie2" v-show="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,
			}
		},
		methods: {

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

			/** 新增投票 */
			goToCreate() {
				let hasNoSaveVote = this.voteList.filter(i => !i.id).length
				if (hasNoSaveVote) {
					this.$Message.warning("已存在未保存的投票活动！");
				} else {
					let defaultVote = {
						name: '预设投票名称',
						code: this.tabIndex === 0 ? this.$store.state.userInfo.schoolCode : this.$store.state.userInfo.TEAMModelId,
						targetClassIds: [],
						options: [{
							code: 'A',
							value: ''
						}, {
							code: 'B',
							value: ''
						}],
						endTime: '',
						publishModel: '0',
						selectMax: 1,
						startTime: '',
						description: '',
						secret: false,
						progress: 'pending'
					}
					this.voteList.unshift(defaultVote);
					this.currentVote = defaultVote;
					this.editable = true
					this.hasNewAdd = true
					this.$refs.voteForm.voteFormEdit = true
				}
			},


			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) {
							this.voteList = res.votes.reverse()
							this.onVoteClick(res.votes[0], 0)
						} else {
							this.voteList = []
						}
						this.isLoadList = false
					} else {
						this.$Message.error('获取数据失败')
					}
				})
			},

			/**
			 * 投票点击事件
			 * @param item
			 * @param index
			 */
			onVoteClick(item, index) {
				this.currentVote = item
				this.activeVoteIndex = index
				// if (item.id) this.getVoteStudents(item.id,item.target)
				this.$refs.voteForm.voteFormEdit = false
				this.hasNewAdd = false
			},

			/* 取消编辑投票（无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: '删除投票',
					content: '<p>确认删除该投票活动？</p>',
					okText: '确认',
					cancelText: '取消',
					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) {
									this.isLoading = false
									this.$Message.success('操作成功')
									this.handleTabClick(this.$route.name === 'manageVote' ? 0 : 1)
								} else {
									this.isLoading = false
									this.$Message.error('操作失败')
								}
							}).catch(err => {
								this.isLoading = false
								this.$Message.error('删除失败')
							})
						} else {
							this.voteList.splice(this.voteList.indexOf(this.currentVote), 1)
							this.isLoading = false
							this.$Message.success('操作成功')
							if (this.voteList.length) this.onVoteClick(this.voteList[0], 0)
						}
					}
				})
			},


			/**
			 * 获取投票关联的学生清单
			 * @param voteId 投票ID
			 */
			async getVoteStudents(voteId, target) {
				this.isLoading = true
				let records = await this.getVoteRecord(voteId)
				//  先查找 投票发布对象关联的学生清单 然后再去判断学生的作答情况
				this.$api.courseMgmt.getClassroomStudent({
					classroomCode: target.map(i => i.classroomCode),
					school_code: this.$store.state.userInfo.schoolCode
				}).then(res => {
					if (!res.error && res.classrooms) {
						let list = []
						res.classrooms.forEach(classroom => {
							classroom.students.forEach(i => {
								list.push({
									id: i.id,
									name: i.name,
									no: i.no,
									classroomName: classroom.name
								})
							})
						})
						console.log(list)
						// let infoList = res.result.extend.students
						// list.forEach(i => {
						// 	i.name = infoList.filter(j => j.studentId === i.code)[0].name
						// 	i.classroomName = target.filter(k => k.classroomCode === i.id)[0].classroomName
						// })
						// 要根据作答情况 结合两张表 处理表格显示的数据 
						if (records.length) {
							let arr = []
							this.studentsTable = []
							records.forEach((item, index) => {
								arr.push({
									// option: this.getSimpleText(item.optionValue),
									option: item.optionKey ? '选项' + (index + 1) : '未投票',
									key: item.optionKey || '',
									result: item.students
								})
								this.studentsTable = this.studentsTable.concat(item.students)
							})
							console.log(this.studentsTable)
							this.studentsTable.forEach(i => {
								let matchList = list.filter(j => j.id === i.code)
								i.name = matchList.length ? matchList[0].name : '暂无数据'
							})
							console.log(arr)
							this.tableData = arr
						} else {
							this.tableData = []
						}
						this.isLoading = false
					} else {
						this.$Message.error('获取数据失败')
						this.isLoading = false
					}
				}).catch(err => {
					this.$Message.error('获取班级学生数据异常')
					this.isLoading = false
				})
			},

			/* 获取投票结果数据 */
			getVoteRecord(voteId) {
				return new Promise((r, j) => {
					this.$api.learnActivity.FindRecordByVoteId({
						id: voteId
					}).then(res => {
						if (!res.error && res.options) {
							r(res.options)
						} else {
							j(500)
						}
					})
				})
			},

			// 提取富文本内容中的文本
			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() {
			// this.handleTabClick(0)
		},
		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>
