<template>
	<div>
		<div style="display: flex;flex-direction: column;">
			<span style="margin: 20px 2px;">选择活动类型</span>
			<Select v-model="acType">
				<Option :value="0">作业活动</Option>
				<Option :value="1">投票活动</Option>
				<Option :value="2">问卷活动</Option>
				<Option :value="3">评测活动</Option>
				<Option :value="4">编序式学习</Option>
				<Option :value="5">学习单元</Option>
			</Select>
		</div>
		<div style="display: flex;flex-direction: column;">
			<span style="margin: 20px 2px;">输入活动ID</span>
			<Input v-model="acId" placeholder=""></Input>
		</div>
		<div style="margin-top: 30px;">
			<Button type="success" style="width:100%" @click="onMock" :loading="isLoading">生成</Button>
		</div>
	</div>
</template>

<script>
	import Mock from 'mockjs'
	export default {
		name: "BaseMock",
		data() {
			return {
				isLoading: false,
				acType: 0,
                acId: '5ed79799-4e2d-471e-a484-deedb81a8ad7'
			};
		}, 
		created() {},
		methods: {
			onMock() {
				if (this.acId) {
					this.isLoading = true
					switch (this.acType) {
						case 0:
							this.doMockHomeWork(this.acId)
							break
						case 1:
							this.doMockVote(this.acId)
							break
						case 2:
							this.doMockQuestionnaire(this.acId)
							break
						case 3:
							this.doMockEvaluation(this.acId)
							break
                        case 4:
							this.doMockSelfLearning(this.acId)
                            break	
                        case 5:
							this.doMockSelfLearning(this.acId)
							break	
						default:
							break;
					}
				} else {
					this.$Message.warning('请输入活动ID！')
				}
			},

			/* 生成评测活动的学生模拟作答数据 */
			async doMockEvaluation(acId) {
				console.log(acId)
				let classCodeArr = await this.getExamClass(acId)
				let studentList = await this.getStudentList(classCodeArr)
				let paper = await this.getExamPaper(acId)
				console.log(console.log(paper))
				let items = paper.item
				let paperId = paper.id
				let result = []
				studentList.forEach(s => {
					result.push({
						id:paperId,
						code:s.code,
						examCode:acId,
						status:1,
						mark:0,
						answers:[]
					})
				})
				items.forEach((item,index) => {
					result.forEach((i) => {
						if(item.type === 'Complete'){
							this.randomAnswer(item).forEach(j => {
								i.answers.push({
									num:i.answers.length,
									group:index,
									type:item.type,
									ans:[j]
								})
							})
						}else{
							i.answers.push({
								num:i.answers.length,
								group:index,
								type:item.type,
								ans:this.randomAnswer(item)
							})
						}
					})
				})

				 //保存模拟数据
				this.$api.learnActivity.UpsertAllRecord(result).then(res => {
					if (!res.error && res.result.data) {
						this.$Message.success('保存成功！')
						this.$emit('onSuccess')
					} else {
						this.$Message.error('保存失败！')
					}
					this.isLoading = false
				})
			},

			/* 生成作业活动学生作答数据 */
			async doMockHomeWork(acId) {
				let result = []
				// 拿到班级Code去换取学生名单
				let classCodeArr = await this.getHomeWorkClass(acId)
				let arr = await this.getStudentList(classCodeArr)
				// 遍历随机赋值作答数据
				arr.forEach(i => {
					result.push({
						id: acId,
						code: i.code,
						score: Mock.mock({"number|1-100": 100}).number,
						content: [{
							answers: Mock.mock('@cparagraph(2)'),
							resource: []
						}],
						submit: true,
						submitTime: new Date(Mock.mock('@datetime')).getTime()
					})
				})
				// 保存模拟数据
				this.$api.learnActivity.SaveHwRecords(result).then(res => {
					if (!res.error && res.result.data) {
						this.$Message.success('保存成功！')
						this.$emit('onSuccess')
					} else {
						this.$Message.error('保存失败！')
					}
					this.isLoading = false
				})
			},

			/* 生成自主学习学生作答数据 */
			async doMockSelfLearning(acId) {
                let result = []
                let acInfo = null
                if (this.acType == 4) {
                    acInfo = await this.findOrderLearn()
                    if (acInfo) {
                        let taskes = await this.findTask()
                        let classes = taskes.map((item) => {
                            return item.code
                        })
                        let students = await this.getStudentList(classes)
                        for (let item of students) {
                            let rdItem = {
                                id: this.acId,
                                code: item.code,
                                steps: []
                            }
                            let compSteps = this.$jsFn.getBtwRandom(0, (acInfo[0].steps.length + 1))
                            for (let index = 0; index < compSteps; index++) {
                                let aswItem = {
                                    index: parseInt(index),
									count:this.$jsFn.getBtwRandom(1,4),
									score:this.$jsFn.getBtwRandom(50,100),
                                    answer: []
                                }
                                acInfo[0].steps[index].item.forEach((question, i) => {
                                    let stItem = {
                                        index: i,
                                        ans: this.randomAnswer(question),
										//count: this.$jsFn.getBtwRandom(0,5)
                                    }
                                    aswItem.answer.push(stItem)
                                })
                                rdItem.steps.push(aswItem)
                            }
                            result.push(rdItem)
                        }
                        this.$api.learnActivity.upsertRecord(result).then(
                            (res) => {
                                if (!res.error && res.result.data) {
                                    this.$Message.success('学习数据模拟成功！')
                                } else {
									this.$Message.error('学习数据模拟失败！')
                                }
                            },
                            (err) => {
								this.$Message.error('学习数据模拟失败！')
                            }
                        )
                        
                    }
                } else if (this.acType == 5) {
                    acInfo = await this.findUnit()
                    let taskes = await this.findTask()
                    let classes = taskes.map((item) => {
                        return item.code
                    })
                    let students = await this.getStudentList(classes)
                    for (let item of students) {
                        let radom = this.$jsFn.getBtwRandom(0, 2)
                        if (radom) {
                            let rdItem = {
                                id: this.acId,
                                code: item.code,
                                steps: []
                            }
                            let aswItem = {
                                index: 0,
                                answer: []
                            }
                            acInfo[0].item.forEach((question, i) => {
                                let stItem = {
                                    index: i,
                                    ans: this.randomAnswer(question),
                                    count: this.$jsFn.getBtwRandom(0, 5)
                                }
                                aswItem.answer.push(stItem)
                            })
                            rdItem.steps.push(aswItem)
                            result.push(rdItem)
                        }
                    }
                    console.log(result)
                    this.$api.learnActivity.upsertRecord(result).then(
                        (res) => {
                            if (!res.error && res.result.data) {
                                this.$Message.success('学习数据模拟成功！')
                            } else {
                                this.$Message.error('学习数据模拟失败！')
                            }
                        },
                        (err) => {
                            this.$Message.error('学习数据模拟失败！')
                        }
                    )
                }
                this.isLoading = false
			},
			
			/* 生成投票活动学生作答数据 */
			async doMockVote(acId) {
				let result = []
				// 拿到班级Code去换取学生名单
				let voteItem = await this.getVoteInfo(acId)
				let classCodeArr = voteItem.target.map(i => i.classroomCode)
				let arr = await this.getStudentList(classCodeArr)
				console.log(arr)
				// 遍历随机赋值作答数据
				arr.forEach(i => {
					result.push({
						id: acId,
						code: i.id,
						name:i.name,
						classroom:{
							name:i.classroomName , 
							code:i.id
						},
						option:voteItem.option[Math.floor(Math.random() * voteItem.option.length)].code,
						submit: true,
						submitTime: new Date(Mock.mock('@datetime')).getTime()
					})
				})
				console.log(result)
				// 保存模拟数据
				this.$api.learnActivity.SaveVoteRecords(result).then(res => {
					if (!res.error && res) {
						this.$Message.success('保存成功！')
						this.$emit('onSuccess')
					} else {
						this.$Message.error('保存失败！')
					}
					this.isLoading = false
				})
			},
			
			/* 生成问卷活动学生作答数据 */
			async doMockQuestionnaire(acId) {
				let result = []
				// 拿到班级Code去换取学生名单
				let qnItem = await this.getQuestionnaireInfo(acId)
				let classCodeArr = qnItem.target.map(i => i.classroomCode)
				let arr = await this.getStudentList(classCodeArr)
				console.log(arr)
				// 遍历随机赋值作答数据
				arr.forEach(i => {
					result.push({
						id: acId,
						code: i.code,
						classroom:{
							name:qnItem.target.filter(j => j.classroomCode === i.id)[0].classroomName , 
							code:i.id
						},
						submit: true,
						submitTime: new Date(Mock.mock('@datetime')).getTime(),
						answers:[]
					})
				})
				
				qnItem.items.forEach((item,index) => {
					result.forEach((i) => {
						i.answers.push({
							order:i.answers.length,
							answer:this.randomQnAnswer(item)
						})
					})
				})
				
				// 保存模拟数据
				this.$api.questionnaire.UpsertRecord(result).then(res => {
					if (!res.error && res.result.data) {
						this.$Message.success('保存成功！')
						this.$emit('onSuccess')
					} else {
						this.$Message.error('保存失败！')
					}
					this.isLoading = false
				})
			},

			/* 获取当前活动下的发布对象CODE */
			async getHomeWorkClass(id) {
				return new Promise((r, j) => {
					this.$api.learnActivity.FindHomeWork({
						id: id
					}).then(res => {
						if (!res.error && res.result.data) {
							r(res.result.data[0].target.map(i => i.classroomCode))
						} else {
							j(500)
						}
					})
				})
			},
			
			/* 获取当前活动下的发布对象CODE */
			async getVoteInfo(id) {
				return new Promise((r, j) => {
					this.$api.learnActivity.FindVote({
						code:this.$store.state.userInfo.TEAMModelId,
						id: id
					}).then(async res => {
						if (!res.error && res.votes) {
							let privateSas = await this.$tools.getPrivateSas()
							let schoolSas = await this.$tools.getSchoolSas()
							let i = res.votes[0]
							if (i.url) {
								let sasString = i.code === this.$store.state.userInfo.TEAMModelId ? privateSas : schoolSas 
								let jsonInfo = await this.$tools.getFile(i.url + sasString.sas)
								let jsonData = JSON.parse(jsonInfo)
								jsonData.id = i.id
								jsonData.fileName = i.url.split('/')[i.url.split('/').length - 1].split('.json')[0]
								r(jsonData)
								console.log(jsonData)
							}else{
								r(i)
							}
						} else {
							j(500)
						}
					})
				})
			},
			
			/* 获取当前活动下的发布对象CODE */
			async getQuestionnaireInfo(id) {
				return new Promise(async (r, j) => {
					let privateSas = await this.$tools.getPrivateSas()
					let schoolSas = await this.$tools.getSchoolSas()
					this.$api.questionnaire.FindSurveys({
						id: id
					}).then(async res => {
						if (!res.error && res.result.data) {
								let i = res.result.data[0]
								if (i.url) {
									let sasString = i.code === this.$store.state.userInfo.TEAMModelId ? privateSas : schoolSas 
									let jsonInfo = await this.$tools.getFile(i.url + sasString.sas)
									let jsonData = JSON.parse(jsonInfo)
									jsonData.id = i.id
									jsonData.fileName = i.url.split('/')[i.url.split('/').length - 1].split('.json')[0]
									r(jsonData)
								}else{
									r(i)
								}
						} else {
							j(500)
						}
					})
				})
			},

			/* 获取班级下面所有的学生清单 */
			async getStudentList(classCodeList) {
				console.log(classCodeList)
				return new Promise((r, j) => {
					this.$api.courseMgmt.getClassroomStudent({
						classroomCode: classCodeList,
						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
									})
								})
							})
							if (this.acType === 3) {
								r(list)
							} else {
								r(list)
							}
						} else {
							j(500)
						}
					})
				})
			},
            //查询学习任务
            async findTask() {
                return new Promise((r, j) => {
                    this.$api.learnActivity.findTask({
                        id: this.acId
                    }).then(
                        (res) => {
                            if (!res.error && res.result.data) {
								r(res.result.data)
                            } else {
                                j(500)
                            }
                        },
                        (err) => {
                            j(500)
                        }
                    )
                })
            },
			/**
             * 查询编序式教材列表
             * */
            async findOrderLearn() {
                return new Promise((r, j) => {
                    let requestData = {
                        id: this.acId
                    }
                    this.$api.learnActivity.FindOrderLearn(requestData).then(
                        res => {
                            if (!res.error && res.result.data) {
                                r(res.result.data)
                            } else {
                                j(500)
                            }
                        },
                        err => {
							j(500)
                        }
                    )
                })
            },
            /**
             * 查询最小单元列表
             * */
            async findUnit() {
                return new Promise((r, j) => {
                    let requestData = {
                        id: this.acId
                    }
                    this.$api.learnActivity.FindUnit(requestData).then(
                        res => {
                            if (!res.error && res.result.data) {
                                r(res.result.data)
                            } else {
                                j(500)
                            }
                        },
                        err => {
							j(500)
                        }
                    )
                })
            },
			/* 获取评测施测班级 */
			getExamClass(id) {
				return new Promise((r, j) => {
					this.$api.learnActivity.FindExamInfo({
						id: id
					}).then(res => {
						console.log('学生班级')
						console.log(res.result.data)
						if (!res.error && res.result.data) {
							r(res.result.data[0].target)
						} else {
							j(500)
						}
					})
				})
			},
			
			/* 获取评测试卷信息 */
			getExamPaper(id) {
				return new Promise((r, j) => {
					this.$api.learnActivity.FindExamPaper({
						code: id
					}).then(res => {
						if (!res.error && res.result.data) {
							r(res.result.data[1])
						} else {
							j(500)
						}
					})
				})
			},
			
			/* 根据题型生成随机答案 */
            randomAnswer(item) {
				switch (item.type) {
					case 'Single':
						return [item.option[Math.floor(Math.random() * item.option.length)].code]
						break;
					case 'Multiple':
						return [item.option[Math.floor(Math.random() * item.option.length)].code]
						break;
					case 'Judge':
						let arr = ['A','B'] 
						return [arr[Math.floor(Math.random() * 2)]]
						break;
					case 'Complete':
						let ans = item.answer.map(i => i = Mock.mock('@cparagraph(2)'))
						return ans
						break;	
					default:
						return [Mock.mock('@cparagraph(2)')]
						break;
				}
			},
			/* 根据题型生成随机答案 */
			randomQnAnswer(item) {
				switch (item.type) {
					case 'Single':
						return [item.options[Math.floor(Math.random() * item.options.length)].code]
						break;
					case 'Multiple':
						return [item.options[Math.floor(Math.random() * item.options.length)].code]
						break;
					case 'Judge':
						let arr = ['A','B'] 
						return [arr[Math.floor(Math.random() * 2)]]
						break;
					default:
						return [Mock.mock('@cparagraph(2)')]
						break;
				}
			},
		},
		mounted() {}
	};
</script>
