<template>
	<div class="qn-container">
		<Loading :top="200" bgColor="rgba(103, 103, 103, 0.27)" type="1" v-show="isLoading"></Loading>
		<div class="qn-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="qn-box dark-iview-split">
			<Split v-model="split1">
				<div slot="left" class="demo-split-pane">
					<!-- 问卷活动列表 -->
					<div class="qn-col qn-list-box">
						<div class="qn-box-header">
							<span>问卷列表</span>
							<div>
								<Icon type="md-trash" class="to-create-icon" @click="onDeleteQn" style="margin-left: 10px" v-if="qnList.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)" />
							</div>
						</div>
						<vuescroll>
							<Loading :top="200" bgColor="rgba(103, 103, 103, 0.27)" type="1" v-show="isLoadList"></Loading>
							<div class="qn-item-wrap">
								<div v-if="qnList.length === 0">
									<EmptyData :top="50"></EmptyData>
								</div>
								<div style="width: 100%" v-else>
									<div :class="['qn-item',index === activeQnIndex ? 'item-active' : '']" v-for="(item, index) in qnList" :key="index"
									 @click="onQnClick(item, index)">
										<p class="qn-item-name">{{ item.name }}</p>
										<div class="qn-item-info">
											<span class="qn-item-nums">
												<Icon type="md-time" size="14" style="margin-right: 5px" />{{ $tools.formatTime(item.startTime) }}</span>
											<span class="qn-item-status" :style="{ background: item.progress === 'pending' ? '#0BADD4'  : item.progress === 'going' ? '#12a568' : '#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="qn-col qn-info-box">
								<div class="qn-box-header">
									<span>问卷详情</span>
									<div class="qn-box-header-tools">
										<!-- <span class="qn-box-header-tools-tool" v-show="currentQn.status !== 300 && qnList.length">
											<Icon type="md-create" size="18" title="编辑" @click="onEditQn" /></span> -->
										<span class="qn-box-header-tools-tool" v-show="currentQn.progress === 'going' && qnList.length">
											<Icon type="md-undo" size="18" title="取消发布" @click="onCancelQn" style="margin-left: 8px" v-if="($access.can('admin.*|schoolAc-upd') || isPrivate)" /></span>
									</div>
								</div>
								<vuescroll ref="qnDetailsScroll">
									<div class="qn-info-wrap">
										<div v-show="qnList.length === 0">
											<EmptyData :top="50"></EmptyData>
										</div>
										<BaseQnForm :editItem="currentQn" @onAddSuccess="onAddSuccess" ref="qnForm" v-show="qnList.length"></BaseQnForm>
									</div>
								</vuescroll>
							</div>
						</div>
						<div slot="right" class="demo-split-pane">
							<!-- 问卷提交数据 -->
							<div class="qn-col qn-data-box">
								<div class="qn-box-header">
									<span>问卷数据</span>
									<div class="qn-box-header-tools" v-show="!isEmptyData">
										<div class="qn-box-header-tools-tool" style="margin-right: 25px" v-show="currentQn.progress !== 'finish' && editable">
											<Icon type="md-list-box" color="#dcdcdc" />
											<Dropdown @on-click="onAddItem">
												<Button>
													新增题目
													<Icon type="ios-arrow-down"></Icon>
												</Button>
												<DropdownMenu slot="list">
													<DropdownItem name="single">单选题</DropdownItem>
													<DropdownItem name="multiple">多选题</DropdownItem>
													<DropdownItem name="judge">判断题</DropdownItem>
												</DropdownMenu>
											</Dropdown>
										</div>
										<!-- 						<div class="qn-box-header-tools-tool" style="margin-right: 25px;" @click="onShowAllAnalysis" v-show="currentQn.progress === 'finish' || currentQn.progress === 0">
											<Icon type="md-podium" color="#dcdcdc" />
											<span>查看统计数据</span>
										</div> -->
										<div class="qn-box-header-tools-tool" @click="onEditQn" v-show="currentQn.progress === 'pending' && qnList.length && !editable && ($access.can('admin.*|schoolAc-upd') || isPrivate)">
											<Icon type="md-create" color="#209460" />
											<span>编辑问卷</span>
										</div>
							
										<div class="qn-box-header-tools-tool" v-show="editable" style="margin-right: 20px">
											<Button class="btn-save" icon="md-folder" :loading="isBtnLoading" @click="onSaveQn">保存问卷</Button>
										</div>
							
										<div class="qn-box-header-tools-tool" @click="onCancelEditQn" v-show="editable">
											<Icon type="md-create" color="#209460" />
											<span>取消编辑</span>
										</div>
									</div>
								</div>
								<vuescroll>
									<div class="qn-data-wrap">
										<BaseQuestionnaire :editItem="currentQn" :isEdit="editable" ref="qnPaper" v-if="!isEmptyData"></BaseQuestionnaire>
									</div>
								</vuescroll>
							</div>
						</div>
					</Split>
				</div>
			</Split>
		</div>
	</div>
</template>
<script>
	import BaseQuestionnaire from "@/components/questionnaire/BaseQuestionnaire.vue";
	import BaseQnForm from "@/components/questionnaire/BaseQnForm.vue";
	export default {
		components: {
			BaseQuestionnaire,
			BaseQnForm,
		},
		data() {
			return {
				split1: 0.2,
				split2: 0.35,
				tabIndex: 0,
				isEmptyData: true,
				isLoading: false,
				isLoadList: false,
				isBtnLoading: false,
				isEdit: false,
				editable: false,
				qnList: [],
				studentsList: [],
				currentQn: {
					progress: "pending",
				},
				currentRecord: null,
				editItem: {},
				activeQnIndex: null,
				addQnModal: false,
			};
		},
		created() {},
		methods: {
			// 校本课纲与个人课纲切换
			handleTabClick(index) {
				this.tabIndex = index;
				this.getQnList(index === 0 ? "school" : "private");
			},

			/** 新增问卷 */
			goToCreate() {
				let hasNoSaveQn = this.qnList.filter(i => !i.id).length
				if (hasNoSaveQn) {
					this.$Message.warning("已存在未保存的问卷！");
				} else {
					let defaultQn = {
						name: "预设问卷名称",
						targetClassIds: [],
						endTime: "",
						startTime: "",
						description: "",
						rangeTime: [],
						isReset: [],
						progress: "pending",
						other: [],
					};

					this.qnList.unshift(defaultQn);
					this.currentQn = defaultQn;
					this.activeQnIndex = 0;
					this.editable = true;
					this.isEmptyData = false;
					this.$refs.qnForm.qnFormEdit = true;
				}
			},

			/** 删除当前问卷 */
			onDeleteQn() {
				this.$Modal.confirm({
					title: "删除问卷",
					content: "<p>确认删除该问卷？</p>",
					okText: "确认",
					cancelText: "取消",
					onOk: () => {
						this.isLoading = true;

						if (this.currentQn.id) {
							this.$api.questionnaire
								.DeleteSurvey({
									id: this.currentQn.id,
									code: this.currentQn.code,
									scope: this.getCurScope,
								})
								.then((res) => {
									if (!res.error) {
										this.isLoading = false;
										this.$Message.success("操作成功");
										this.handleTabClick(
											this.$route.name === "manageQuestionnaire" ? 0 : 1
										);
									} else {
										this.isLoading = false;
										this.$Message.success("操作失败");
									}
								});
						} else {
							this.qnList.splice(this.qnList.indexOf(this.currentQn), 1);
							this.isLoading = false;
							this.$Message.success("操作成功");
							if (this.qnList.length) this.onQnClick(this.qnList[0], 0);
						}
					},
				});
			},

			/** 获取问卷列表 */
			getQnList(type) {
				this.isLoadList = true;
				let params = {
					code: this.getCurCode,
					scope: this.getCurScope,
				};
				this.$api.questionnaire.FindSurveysSummary(params).then(async (res) => {
					if (!res.error && res.surveys) {
						let list = res.surveys.reverse();
						this.qnList = list;
						if (list.length) {
							this.onQnClick(list[0], 0);
							this.isEmptyData = false;
						} else {
							this.isEmptyData = true;
						}
						this.isLoadList = false;
					} else {
						this.$Message.error("获取数据失败");
					}
				});
			},

			/** 获取问卷列表 */
			async getQnDetails(qnId) {
				return new Promise(async (r, j) => {
					this.$api.questionnaire
						.FindSurveys({
							id: qnId,
							code: this.getCurCode,
							scope: this.getCurScope,
						})
						.then(async (res) => {
							if (!res.error && res.surveys) {
								r(res.surveys[0]);
							} else {
								this.$Message.error("获取数据失败");
							}
						});
				});
			},

			/**
			 * 问卷点击事件
			 * @param item
			 * @param index
			 */
			async onQnClick(item, index) {
				if (this.activeQnIndex === index && this.currentQn.id && this.currentQn.id === item.id) return
				console.log(item, index);
				/* 判断是否有新增但是无效的ITEM  如果有 则清空 需要重新添加 */
				let hasNewQn = this.qnList.filter((i) => !i.id).length;
				if (hasNewQn) {
					this.qnList
						.filter((i) => !i.id)
						.forEach((item) => {
							this.qnList.splice(this.qnList.indexOf(item), 1);
						});
				}
				// 如果当前点击活动是已结束 则获取问卷的作答数据
				this.currentRecord =
					item.status === 300 && item.id ? await this.getQnRecord(item.id) : null;
				this.currentQn = item.id ?
					await this.getQnDetails(item.id) :
					this.currentQn;
				this.currentQn.status = item.status;
				console.log("获取问卷数据");
				console.log(this.currentQn);
				this.currentRecord && this.makeItemResult(this.currentRecord);
				this.activeQnIndex = hasNewQn ? this.qnList.indexOf(item) : index;
				this.$refs.qnForm.qnFormEdit = false;
				this.editable = false;
			},

			/* 保存问卷操作 */
			async onSaveQn() {
				console.log(this.$refs.qnForm.qnFormEdit);
				let isQnFormEdit = this.$refs.qnForm.qnFormEdit; // 判断当前表单是否为编辑状态
				let qnBaseInfo = isQnFormEdit ?
					await this.$refs.qnForm.handleSubmit("qnForm") :
					this.currentQn;
				let qnItems = this.$refs.qnPaper.items || [];
				// 获取到基础信息 以及 题目数据 拼接保存
				qnBaseInfo.questions = qnItems;
				this.isBtnLoading = true;
				this.saveorUpdataQn({
						survey: qnBaseInfo,
						reset: false,
					})
					.then((res) => {
						this.$Message.success("操作成功");
						this.$refs.qnForm.qnFormEdit = false;
						this.editable = false;
						this.isLoading = false;
						this.isBtnLoading = false;
						this.onAddSuccess();
					})
					.catch((error) => {
						this.$Message.error(`操作失败，错误信息为${error}`);
						this.$refs.qnForm.qnFormEdit = false;
						this.isLoading = false;
						this.isBtnLoading = false;
					});
			},

			onShowAllAnalysis() {
				this.$refs.qnPaper.onShowAllAnalysis();
			},

			onAddItem(name) {
				this.$refs.qnPaper.onMenuClick(name);
			},

			async getQnRecord(id) {
				return new Promise((r, j) => {
					this.$api.questionnaire
						.FindRecordSurvey({
							id: id,
						})
						.then((res) => {
							if (!res.error && res.result.data) {
								r(res.result.data);
							} else {
								j(500);
							}
						});
				});
			},

			/* 根据学生的作答记录 处理成 图表需要的记录 */
			makeItemResult(result) {
				let arr = [];
				this.currentQn.items.forEach((item, index) => {
					let obj = {};
					let resultArr = [];
					item.options.forEach((option) => {
						obj.code = this.getSimpleText(option.value);
						obj.value = this.getSelectNum(result, index, option.code);
						resultArr.push(obj);
						obj = {};
					});
					item.result = resultArr;
				});
			},

			/* 查找指定题目指定选项在作答数据里出现的次数 */
			getSelectNum(origin, itemIndex, option) {
				let num = 0;
				origin.forEach((i) => {
					if (i.answers[itemIndex].answer.includes(option)) num++;
				});
				return num;
			},

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

			/**
			 * 新增问卷或者编辑问卷
			 * @param data
			 */
			saveorUpdataQn(data) {
				return new Promise((r, j) => {
					this.$api.questionnaire.UpsertSurvey(data).then((res) => {
						if (!res.error) {
							r(res);
						} else {
							j(res.error);
						}
					});
				});
			},

			/** 问卷编辑事件 */
			onEditQn() {
				this.editItem = this.currentQn;
				this.isEdit = true;
				this.editable = true;
				this.$refs.qnForm.qnFormEdit = !this.$refs.qnForm.qnFormEdit;
			},

			onCancelEditQn() {
				if (this.currentQn.id && this.qnList.length > 0) {
					this.$refs.qnForm.qnFormEdit = false;
					// this.onQnClick(this.currentQn, this.activeQnIndex);
					this.$refs.qnForm.doRender(this.currentQn)
				} else if (!this.currentQn.id && this.qnList.length > 1) {
					this.onQnClick(this.qnList[1], 1)
				} else {
					this.qnList = [];
					this.currentQn = {
						progress: "pending",
					};
					this.activeQnIndex = 0;
					this.isEmptyData = true;
				}
				this.isBtnLoading = false;
				this.editable = false;
			},

			/* 取消发布问卷 */
			onCancelQn() {
				this.$Modal.confirm({
					title: "取消发布",
					content: "<p>确认取消发布该问卷？</p>",
					okText: "确认",
					cancelText: "取消",
					onOk: () => {
						this.isLoading = true;
						this.$api.questionnaire
							.CancelSurvey({
								surveyId: this.currentQn.id
							})
							.then((res) => {
								if (!res.error) {
									this.isLoading = false;
									this.$Message.success("操作成功");
									this.getQnList();
								} else {
									this.isLoading = false;
									this.$Message.success("操作失败");
								}
							});
					},
				});
			},

			/** 新增问卷成功回调 */
			onAddSuccess() {
				this.handleTabClick(this.$route.name === "manageQuestionnaire" ? 0 : 1);
			},

			/**
			 * 滚动条返回顶部
			 * @param refName
			 */
			backToTop(refName) {
				this.$refs[refName].scrollTo({
						y: 0,
					},
					100,
					"easeInQuad"
				);
			},
		},
		mounted() {
			// this.handleTabClick(0)
		},
		computed: {
			getCurCode() {
				return this.$route.name === "personalSurvey" ?
					this.$store.state.userInfo.TEAMModelId :
					this.$store.state.userInfo.schoolCode;
			},
			getCurScope() {
				return this.$route.name === "personalSurvey" ? "private" : "school";
			},
			isPrivate() {
				return this.$route.name === 'personalSurvey'
			}
		},
		watch: {
			$route: {
				handler: function(to, from) {
					this.handleTabClick(this.$route.name === "manageQuestionnaire" ? 0 : 1);
				},
				immediate: true,
			},
		},
	};
</script>
<style lang="less" scoped>
	@import "./ManageQuestionnaire.less";
</style>
<style>
	.qn-modal .ivu-modal-content {
		background: #454545;
	}

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

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

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

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