<template>
	<div class="sheet-wrap animated fadeIn">
		<Loading v-if="isLoading"></Loading>
		<div class="sheet-left">
			<div class="sheet-container" id="pdfDom" v-if="isRender">
				<!-- <router-view  v-if="isRouterAlive"/> -->
				<BaseSvgBg v-for="(page, pageIndex) in pages" :key="pageIndex" :ids="'svg' + pageIndex"
					:total="pages.length"></BaseSvgBg>
				<SheetBaseInfo></SheetBaseInfo>
				<!-- 绘制主区域 -->
				<div class="sheet-groups">
					<div v-for="(group,groupIndex) in groups" :key="groupIndex" class="sheet-group-item">
						<div v-if="group.type === 'objective'">
							<BaseTitleEditor :ids="'titleEditor' + groupIndex"
								:content="titleContent(groupIndex,group)"></BaseTitleEditor>
							<SheetObjective :items="items" v-show="groupItems.objectiveItems.length"
								@onRendered="onRendered"></SheetObjective>
						</div>
						<div v-else-if="group.type === 'complete'">
							<BaseTitleEditor :ids="'titleEditor' + groupIndex"
								:content="titleContent(groupIndex,group)"></BaseTitleEditor>
							<SheetComplete :items="items" v-if="groupItems.completeItems.length"></SheetComplete>
						</div>
						<div v-else>
							<BaseTitleEditor :ids="'titleEditor' + groupIndex"
								:content="titleContent(groupIndex,group)"></BaseTitleEditor>
							<SheetSubjective :items="groupItems.subjectiveItems"
								v-show="groupItems.subjectiveItems.length"></SheetSubjective>
						</div>
					</div>
				</div>

			</div>
		</div>
		<div class="sheet-right">
			<Button @click="goBack">返回上级</Button>
			<Button @click="doDownload" class="btn-download">下载PDF</Button>
			<div>
				<p class="sheet-right-title">基础设置</p>
				<div>
					<Checkbox v-model="isColumn">客观题竖向排列</Checkbox>
					<Checkbox v-model="isShowErCode">添加二维码</Checkbox>
					<Checkbox v-model="isShowLines">密封线</Checkbox>
				</div>
				<p class="sheet-right-title" v-if="!isAutoCreate">添加题型</p>
				<div style="display: flex;flex-wrap: wrap;" v-if="!isAutoCreate">
					<span class="add-block-item" @click="onAddType('0')"> + 客观题</span>
					<span class="add-block-item" @click="onAddType('1')"> + 填空题</span>
					<span class="add-block-item" @click="onAddType('2')"> + 简答题</span>
					<span class="add-block-item" @click="onAddType('3')"> + 作文（语）</span>
					<span class="add-block-item" @click="onAddType('4')"> + 作文（英）</span>
				</div>
			</div>
		</div>

		<Modal v-model="isShowAdd" class-name="add-type-modal" width="650" title="添加题型">
			<Tabs :value="activeTab" @on-click="onTabClick">
				<TabPane label="客观题" name="0"></TabPane>
				<TabPane label="填空题" name="1"></TabPane>
				<TabPane label="简答题" name="2"></TabPane>
				<TabPane label="作文（语）" name="3"></TabPane>
				<TabPane label="作文（英）" name="4"></TabPane>
			</Tabs>
			<div>
				<div class="add-type-section">
					<p class="add-type-title">题号</p>
					<div>
						<span style="margin: 0 10px;">第</span>
						<InputNumber :max="100" :min="1" v-model="addType.startIndex" @on-change="onStartChange">
						</InputNumber>
						<span style="margin: 0 10px;">题 到 第</span>
						<InputNumber :max="100" :min="1" v-model="addType.endIndex" @on-change="onEndChange">
						</InputNumber>
						<span style="margin: 0 10px;">题,每题</span>
						<InputNumber :max="100" :min="0" v-model="addType.everyScore" @on-change="renderAddItem">
						</InputNumber>
						<span style="margin: 0 10px;">分</span>
						<span v-if="activeTab === '0' || activeTab === '1'" >
							<span>每题 </span>
							<InputNumber :max="8" :min="0" v-model="addType.everyOpts" @on-change="renderAddItem">
							</InputNumber>
							<span style="margin: 0 10px;">个{{ activeTab === '0' ? '选项' : '空格' }}</span>
						</span>
						<span v-if="activeTab === '3'">
							<span>，共 </span>
							<InputNumber :max="2000" :min="100" v-model="addType.maxWords"></InputNumber>
							<span> 字 </span>
						</span>
						<span v-if="activeTab === '4'">
							<span> 共 </span>
							<InputNumber :max="30" :min="1" v-model="addType.maxLines"></InputNumber>
							<span> 行</span>
						</span>
						
					</div>
				</div>
				<p v-show="indexErr" style="color: red;">* 开始题号必须小于结束题号</p>
				<div class="add-type-section" v-if="addItems.length && isAddInfoComplete">
					<p class="add-type-title">配分</p>
					<div class="score-box">
						<div v-for="(item,index) in addItems" class="score-item">
							<span>第 {{ item.order }} 题</span>
							<div>
								<InputNumber :max="100" :min="0" v-model="item.score"></InputNumber>
								<span> 分 </span>
								<span v-if="activeTab === '0' || activeTab === '1'" style="margin-left: 10px;">
									<InputNumber :max="100" :min="0" v-model="item.opts"></InputNumber>
									<span> 个{{ activeTab === '0' ? '选项' : '空格' }}</span>
								</span>
							</div>
						</div>
					</div>
				</div>
			</div>
			<div slot="footer">
				<Button type="primary" @click="doAddType">确定</Button>
			</div>
		</Modal>
	</div>
</template>

<script>
	import BaseTitleEditor from './BaseTitleEditor'
	import Snap from "imports-loader?this=>window,fix=>module.exports=0!snapsvg/dist/snap.svg.js";
	import SheetObjective from "./SheetObjective";
	import SheetBaseInfo from "./SheetBaseInfo";
	import SheetComplete from "./SheetComplete";
	import SheetSubjective from "./SheetSubjective";
	import BaseSvgBg from "./BaseSvgBg";
	import {
		PAPER_W,
		PAPER_H,
		ANCHORPROP,
		INFO_H
	} from "@/utils/sheetConfig.js";
	export default {
		props: {
			ids: {
				type: String,
				default: "",
			},
		},
		components: {
			SheetObjective,
			SheetBaseInfo,
			SheetComplete,
			SheetSubjective,
			BaseSvgBg,
			BaseTitleEditor
		},
		data() {
			return {
				indexErr: false,
				addItems: [],
				addType: {
					startIndex: null,
					endIndex: null,
					everyScore: null,
					everyOpts: null,
					maxWords:800,
					maxLines:10
				},
				isShowAdd: false,
				isShowErCode:false,
				isShowLines:false,
				activeTab: '0',
				groups: [],
				isLoading: false,
				isColumn: false,
				isRouterAlive: true,
				isRender: true,
				pages: [],
				items: [],
				groupItems: {
					objectiveItems: [],
					completeItems: [],
					subjectiveItems: [],
				},
				subjectiveTop: 0,
				fromRouter: '',
				typeList: {
					objective: '选择题',
					complete: '填空题',
					subjective: '简答题'
				}
			};
		},
		created() {
			let routerPaper = this.$route.params.paper
			if (routerPaper) {
				this.$store.commit('clearFixArr')
				this.$store.commit('clearPage')
				this.$store.commit('clearIsNewPage')
				this.$store.commit('setPaper', routerPaper)
				if (routerPaper.item === null) {
					this.$store.commit('setCreateModal', 'diy')
				} else {
					this.items = routerPaper.item
					this.$store.commit('setCreateModal', 'auto')
				}
				localStorage.setItem('scrollDis', 0)
			} else {
				this.goBack()
			}

		},
		methods: {
			onTabClick(type){
				this.activeTab = type
			},
			onAddType(type) {
				this.isShowAdd = true
				this.activeTab = type
				this.addType = {
					startIndex: null,
					endIndex: null,
					everyScore: null,
					everyOpts: (type === '0' || type === '1') ? null : 1,
					maxWords:800,
					maxLines:10
				}
			},

			onStartChange(val) {
				this.indexErr = val > this.addType.endIndex || (!val && !this.addType.endIndex)
				this.renderAddItem()
			},

			onEndChange(val) {
				this.indexErr = val < this.addType.startIndex || (!val && !this.addType.startIndex)
				this.renderAddItem()
			},
			
			/* 点击添加题型 */
			doAddType() {
				if (this.isAddInfoComplete) {
					console.log(this.addItems)
					this.addItems.forEach(i => {
						i.option = new Array(i.opts).fill('0')
						i.blankCount = i.opts
						i.id = this.$tools.guid()
					})
					this.isShowAdd = false
					this.items = this.items.concat(this.addItems)
					this.$store.commit('setPaperItems', this.items)
					this.doRender()
				} else {
					this.$Message.warning('添加信息不能为空！')
				}
			},
			doDownload() {
				this.isLoading = true
				this.getPdf().then(res => {
					this.isLoading = false
				})
			},
			goBack() {
				this.$router.push({
					name: this.fromRouter || 'schoolBank',
					params: {
						tabName: 'paper'
					}
				})
			},
			reload() {
				this.isRouterAlive = false;
				this.$nextTick(function() {
					this.isRouterAlive = true
				})
			},
			// 客观题渲染完 来决定主观题的TOP值高度
			onRendered(val) {
				this.subjectiveTop = val + INFO_H + 200;
			},

			doRender() {
				this.groupItems = {
					objectiveItems: [],
					completeItems: [],
					subjectiveItems: [],
				}
				this.groups = []
				let objectiveTypes = ["single", "multiple", "judge"];
				this.items.forEach((i) => {
					if (objectiveTypes.includes(i.type)) {
						this.groupItems.objectiveItems.push(i);
					} else if (i.type === "complete") {
						this.groupItems.completeItems.push(i);
					} else {
						this.groupItems.subjectiveItems.push(i);
					}
				});

				if (this.groupItems.objectiveItems.length) {
					this.groups.push({
						type: 'objective',
						items: this.groupItems.objectiveItems
					})
				}
				if (this.groupItems.completeItems.length) {
					this.groups.push({
						type: 'complete',
						items: this.groupItems.completeItems
					})
				}
				if (this.groupItems.subjectiveItems.length) {
					this.groups.push({
						type: 'subjective',
						items: this.groupItems.subjectiveItems
					})
				}
				console.log(this.groupItems)
				console.log(this.groups)
			},
			/**
			 * 数字与中文转换
			 * @param num
			 */
			numberConvertToUppercase(num) {
				num = Number(num)
				var upperCaseNumber = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '百', '千', '万', '亿']
				var length = String(num).length
				if (length === 1) {
					return upperCaseNumber[num]
				} else if (length === 2) {
					if (num === 10) {
						return upperCaseNumber[num]
					} else if (num > 10 && num < 20) {
						return '十' + upperCaseNumber[String(num).charAt(1)]
					} else {
						return upperCaseNumber[String(num).charAt(0)] + '十' + upperCaseNumber[String(num).charAt(1)]
							.replace('零', '')
					}
				}
			},

			renderAddItem() {
				let addItems = []
				let addInfo = this.addType
				let len = addInfo.endIndex - addInfo.startIndex + 1
				for (let i = 0; i < len; i++) {
					addItems.push({
						id: this.$tools.guid(),
						order: addInfo.startIndex + i,
						score: addInfo.everyScore,
						opts: addInfo.everyOpts,
						blankCount: 1,
						maxWords:this.activeTab === '3' ? addInfo.maxWords : null,
						maxLines:this.activeTab === '4' ? addInfo.maxLines : null,
						type: this.activeTab === '0' ? 'single' : this.activeTab === '1' ? 'complete' : 'subjective'
					})
				}
				this.addItems = addItems
			}
		},
		mounted: function() {
			this.doRender()
			this.$EventBus.$off('deleteItem')
			this.$EventBus.$on('deleteItem',val => {
				console.log(val)
				if(val === '0'){
					this.groups = this.groups.filter(i => i.type !== 'complete')
					this.items = this.items.filter(i => i.type !== 'complete')
				}else if (val === 'objective'){
					let objectiveTypes = ["single", "multiple", "judge"];
					this.groups = this.groups.filter(i => i.type !== 'objective')
					this.items = this.items.filter(i => !objectiveTypes.includes(i.type))
				}else{
					this.groups = this.groups.filter(i => i.items.length)
				}
				this.$EventBus.$emit('doRefresh')
			})
		},
		beforeRouteEnter(to, from, next) {
			next(vm => {
				vm.fromRouter = from.name
			})
		},
		computed: {
			getPage() {
				return this.$store.state.answerSheet.pages;
			},

			isAddInfoComplete() {
				for (let key in this.addType) {
					if (this.addType[key] === null) {
						return false;
					}
				}
				return true
			},

			// 是否为根据试卷自动生成的答题卡
			isAutoCreate() {
				return this.$store.state.answerSheet.isAutoCreate
			},

			titleContent() {
				return (groupIndex, group) => {
					let totalScore = group.items.length ? group.items.map(i => i.score).reduce((a, b) => a + b) : 0
					let type = this.typeList[group.type]
					return this.numberConvertToUppercase(groupIndex + 1) + '、' + type + '（共' + group.items.length +
						'题，总计' + totalScore + '分）'
				}
			}
		},
		watch: {
			getPage: {
				handler(n, o) {
					this.pages = new Array(n).fill(0);
				},
				immediate: true
			},
			isAddInfoComplete: {
				handler(n, o) {
					if (n) {
						this.renderAddItem()
					} else {
						this.addItems = []
					}
				}
			}
		},
	};
</script>
<style scoped lang="less">
	.sheet-wrap {
		display: flex;
		justify-content: space-between;
		position: relative;
		width: 100%;

		.ivu-spin {
			background-color: #000000 !important;
		}
	}

	.add-type-modal {
		.add-type-section {
			margin: 20px 10px;
		}

		.add-type-title {
			margin: 10px 0;

			&::before {
				content: '';
				display: inline-block;
				border: 4px solid #267ce6;
				border-radius: 50%;
				margin-right: 10px;
			}
		}

		.score-box {
			padding: 5px 10px;
			background-color: #0000000d;
			border-radius: 5px;
			max-height: 300px;
			overflow-y: auto;

			.score-item {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 8px 0;
				border-bottom: 1px dashed #e4e4e4;
			}
		}

		.ivu-input-number {
			width: 50px;
		}
	}

	.sheet-groups {
		position: absolute;
		top: 350px;
		left: 0;
		width: 100%;
	}

	.sheet-right {
		width: 16%;
		margin-top: 20px;
		background-color: #fff;
		box-shadow: 0 0 5px #000000;
		position: fixed;
		top: 70px;
		right: 10px;
		height: 88vh;
		padding: 20px;

		.ivu-btn {
			width: 100%;
			height: 40px;
			background-color: #00b29a;
			color: #fff;
			border: none;
		}

		.btn-download {
			margin-top: 10px;
			background-color: #00a7ee;
		}

		.add-block-item {
			display: inline-block;
			margin: 5px;
			background: #009de8;
			color: #fff;
			padding: 6px 15px;
			border-radius: 4px;
			cursor: pointer;
		}

		&-title {
			font-size: 14px;
			font-weight: bold;
			margin: 15px 5px;

			&::before {
				content: '';
				width: 5px;
				height: 10px;
				background-color: #2181ff;
				display: inline-block;
				margin-right: 10px;
			}
		}

		.ivu-checkbox-wrapper {
			margin: 10px;
		}



	}

	.sheet-left {
		width: 70%;
	}

	.sheet-container {
		position: relative;
		width: 750px;
		height: 1060.71px;
		background: #fff;
		margin: 20px auto;
	}

	.sheet-subjective-wrap {
		position: absolute;
		top: 580px;
		left: 0;
		width: 100%;
	}
</style>
