<template>
	<div>
		<el-row>
			<el-col :span="12" class="p20">
				<i-answer :answers="answers" @selectAnswer="selectAnswer"></i-answer>
			</el-col>


			<el-col :span="12" class="p20">
				<div class="button-box clearflex">
				  <h1> 已经选择题库</h1>
				</div>
				<div class="search-term">
				  <el-form :inline="true"  class="demo-form-inline">
						<el-form-item  label="标题" prop="phone">
						  <el-input placeholder="请输入标题" v-model="title" type="text" class="user-form-item" clearable></el-input>
						</el-form-item>
				  </el-form>
				</div>
				
				<i-group-answer :datalist="filterList()" @deleteRow="deleteRow" ></i-group-answer>
				<el-pagination
				  :current-page="page"
				  :page-size="size"
				  :page-sizes="[10, 30, 50, 100]"
				  :style="{float:'right',padding:'20px'}"
				  :total="answerList.length"
				  @current-change="handleCurrentChange"
				  @size-change="handleSizeChange"
				  layout="total, sizes, prev, pager, next, jumper"
				></el-pagination>
			</el-col>
		</el-row>


	</div>
</template>

<script>
	import {postData} from "@/api/exam.js";
	
	import IAnswer from './components/iAnswer.vue';
	import IGroupAnswer from './components/iGroupAnswer.vue';
	export default {
		name: "Api",
		data() {
			return {
				size:10,
				page:1,
				title:'',
				groupId: 0,
				answers: {},
				answerList: []
			};
		},
		components: {
			IAnswer,
			IGroupAnswer
		},
		methods: {
			getWxGroupAnswerList(groupId) {
				postData("getWxGroupAnswerList", {
					groupId
				}).then(res => {
					if (res.code == 200) {
						let answerList = res.data || [];
						let answers = {}
						answerList.forEach(item => {
							answers[item.answerId] = true;
						})
						this.answers = answers;
						this.answerList = answerList
					}
				})
			},
			selectAnswer( item, cb ){
				let param = {groupId:this.groupId, answerId: item.answerId}
				postData("AddWxGroupAnswer", param).then(res => {
					if (res.code == 200) {
						this.answers[item.answerId] = true;
						let answer = Object.assign( res.data, item )
						this.answerList.push( res.data )
						this.$message.successMsg("加入成功",1 )
						cb&&cb()
					}
				})
			},
			deleteRow( item ){
				let param = {groupId:this.groupId, answerId: item.answerId}
				postData("DelWxGroupAnswer", param).then(res => {
					if (res.code == 200) {
						this.answers[item.answerId] = false;
						this.answerList.splice( item.index, 1)
						this.$message.successMsg("加入成功",1 )
					}
				})
			},
			handleCurrentChange( page ){
				this.page = page 
			},
			handleSizeChange( size ){
				 this.size = size
			},
			filterList(){
				let title = this.title
				let nlist= this.answerList.filter(res=>{
					return res.title.indexOf( title )>-1
				})
				return nlist.slice( (this.page-1)*this.size, this.page*this.size)
			}
			
		},
		
		beforeMount() {
			let groupId = +this.$route.query.groupId || 0;
			this.groupId = groupId;		
			this.getWxGroupAnswerList(groupId);
		}
	};
</script>
