// 全科学情分析数据
import apiTools from '@/api'
import tools from '@/utils/public.js'
import filter from '@/static/filter.json' // 模拟题目数据


export default {
    state: {
        scrollTop: 0,
		paperScrollTop:0,
        questions: [],
        filterData: filter,
		campusCode:'88924E4C-F00D-4A1D-B2C3-234F930F29D4',

        // 真实数据部分
		currentExam:null,
		indexSubject:null,
        examList: null,
        subjectList: null,
        currentSubject: null,
        achievementData: null,
        scatterData: null,
        exerciseData: null,
        classExerciseData: null,
        knowledgeData: null,
        levelData: null,
        examPaper: null,
		
		curClassIndex:-1,

        exportTableData: null,
        exportTableRefs:null,
		exportTableParams:[],
		excelNums:0,
		
		// 最新学情数据
		analysisJson:null
    },
    getters: {

    },
    mutations: {
		
		resetSubjectSelect(state){
			state.indexSubject = null
			state.currentSubject = null
		},
		
		// 更新最新学情分析数据
		updateAnalysisJson(state,val){
			let pointLevelKey = []
			if(!val) return
			/* 对知识点模块和认知层次模块进行数据格式化 */
			val.subjects.forEach((subject,subjectIndex) => {
				pointLevelKey.push({
					subjectId:subject.id,
					levelKey:{
						level:val.fieldName[subjectIndex].value,
						pointList:val.fieldName[subjectIndex].value,
						per:val.fieldPer[subjectIndex].value,
						wrong:{
							datas:val.fieldwrong[subjectIndex].value,
							keys:val.wrongKey
						},
						stupercent:tools.getLevelPercent(val,subjectIndex).stuResult,
						classpercent:tools.getLevelPercent(val,subjectIndex).classResult
					},
					pointKey:{
						level:val.knowName[subjectIndex].value,
						pointList:val.knowName[subjectIndex].value,
						per:val.knowPer[subjectIndex].value,
						wrong:{
							datas:val.wrong[subjectIndex].value,
							keys:val.wrongKey
						},
						stupercent:tools.getKnowPercent(val,subjectIndex).stuResult,
						classpercent:tools.getKnowPercent(val,subjectIndex).classResult
					}
				})
			})
			val.pointLevelKey = pointLevelKey
			state.currentSubject = null
			state.indexSubject = null
			state.curClassIndex = -1
			console.log('转换后的AnalysisJson',val)
			state.analysisJson = val
		},
		
		clearAnalysis(state,val){
			state.analysisJson = val
			state.subjectList = val
			state.currentSubject = val
			state.classExerciseData = val
		},

        // 更新当前评测CODE
        updateCurExam(state, val) {
			console.log(val)
			console.log('重置分析数据！')
			// 切换评测 清空缓存的分析数据
			state.achievementData = null
			state.scatterData = null
			state.exerciseData = null
			state.knowledgeData = null
			state.levelData = null
			state.examPaper = null
            state.currentExam = val
        },
		
		// 更新当前页面表格数据
		updateExportTable(state, val) {
		    state.exportTableData = val
		},
		
		resetExportParams(state,val){
			state.exportTableParams = []
		},
		
		updateExcelNums(state,val){
			state.excelNums = val
		},
		
		// 更新当前页面表格数据
		updateExportParams(state, val) {
			if(state.exportTableParams.indexOf(val) < 0){
				state.exportTableParams.push(val)
			}
		},

        // 更新当前页面表格数据
        updateExportDisable(state, val) {
            state.exportTableRefs = val
        },

        // 更新页面滚动值
        updateScrollTop(state, val) {
            state.scrollTop = val
        },
        // 更新页面滚动值
        updatePaperScroll(state, val) {
            state.paperScrollTop = val
        },

        // 更新评测列表
        updateExamList(state, val) {
            state.examList = val
        },

        // 更新试卷数据
        updateExamPaper(state, val) {
            state.examPaper = val
        },
		
		// 更新试卷数据
		updateClassIndex(state, val) {
		    state.curClassIndex = val - 1
		},

        // 更新科目列表
        updateSubjectList(state, val) {
            state.subjectList = val
        },

        // 更新 成绩分析数据
        getAchievementData(state, data) {
            // 拿到成绩分析模块数据后 处理及格率数据格式
            let list = data.passRate
            let transferArr = []
            list.subjects.forEach((item, index) => {
                let obj = {}
                obj.name = item
                obj.class = (Number(list.class[0][0]) * 100).toFixed(0) + '%'
                obj.grade = (Number(list.grade[index]) * 100).toFixed(0) + '%'
                obj.area = '0%'
                transferArr.push(obj)
            })
            data.passRate = transferArr
            state.achievementData = data
        },

        // 更新 落点分析数据
        getScatterData(state, data) {
            let jsonData = tools.jsonTransform(data[0].scatter)
            jsonData.forEach(item => {
                item.y = (Number(item.y) * 100).toFixed(0) + ''
                //item.hardList = item.hardList.split(',')
                //item.carefulList = item.carefulList.split(',')
            })
            state.scatterData = jsonData
        },

        // 更新 试题分析数据（以试题为单位）
        getExerciseData(state, data) {
            let jsonData = tools.jsonTransform(data[1])
            // 给题目列表加入每道题每个班的得分率
            jsonData.forEach((item, index) => {
                item.Y = (Number(item.Y) * 100).toFixed(0) + ''
                for (let i = 0; i < data[0].classList.length; i++) {
                    item[data[0].classList[i]] = data[0].datas[i][index]
                }
            })
            state.exerciseData = jsonData
        },

        // 更新班级单题得分率数据（以班级为单位）
        getClassExerciseData(state, data) {
            let origin = data[0]
            let result = []
            for (let i = 0; i < origin.classList.length; i++) {
                let o = {}
                o.className = origin.classList[i]
                o.datas = origin.datas[i]
                result.push(o)
            }
            state.classExerciseData = result
        },

        // 更新知识点掌握数据
        getKnowledgeData(state, data) {
            state.knowledgeData = data
        },

        // 更新认知层次分布掌握数据
        getLevelData(state, data) {
            state.levelData = data
        },

        // 更新当前科目
        updateCurSubject(state, data) {
            let local = localStorage.getItem('cur_s')
            // 先把之前科目缓存数据清空 重新获取
            // state.scatterData = null
            // state.exerciseData = null
            if (data) {
                localStorage.setItem('cur_s', data)
                state.currentSubject = data
                state.examPaper = null
				state.scatterData = null
				state.knowledgeData = null
				state.exerciseData = null
				state.levelData = null
            } else if (!data && local) {
                state.currentSubject = local
            }
        }
    },
    actions: {
		
		// 获取最新学情数据
		getAnalysisJson(context,params){
			return new Promise((r, j) => {
			    if (context.state.analysisJson) {
			        console.log('Cache-analysisJson')
			        r(context.state.analysisJson)
			    } else {
			        apiTools.totalAnalysis.getAnalysis(params).then(res => { // api请求
						if(res.classes.length){
							context.commit('updateAnalysisJson', res) // 提交到vuex保存数据
							context.commit('updateSubjectList', res.subjects.map(i => i.name)) // 提交到vuex保存数据
							context.commit('updateCurSubject', res.subjects.map(i => i.name)[0]) // 提交到vuex保存数据
							console.log('API-analysisJson', res)
							r(res)
						}else{
							j(500)
						}
			        }).catch(err => {
			            j(err)
			        })
			    }
			})
		},

        // 异步获取 评测列表数据
        getExamList(context) {
            return new Promise((r, j) => {
                if (context.state.examList) {
                    console.log('Cache-examList')
                    r(context.state.examList)
                } else {
                    apiTools.totalAnalysis.getExamList({ code: context.state.campusCode }).then(res => { // api请求
                        let data = res[0]
                        data.name = '第二次测试'
                        res.push(data)
                        context.commit('updateExamList', data) // 提交到vuex保存数据
                        console.log('API-examList')
                        r(data)
                    }).catch(err => {
                        j(err)
                    })
                }
            })
        },

        // 异步获取 试卷数据
        getExamPaper(context) {
            return new Promise((r, j) => {
                if (context.state.examPaper) {
                    console.log('Cache-examPaper')
                    r(context.state.examPaper)
                } else {
                    apiTools.totalAnalysis.getExamPaper({ subjectCode: context.state.currentSubject, code: context.state.currentExam.examCode }).then(res => { // api请求
                        context.commit('updateExamPaper', res.result.data) // 提交到vuex保存数据
                        console.log('API-examPaper')
                        r(res.result.data)
                    }).catch(err => {
                        j(err)
                    })
                }
            })
        },

        // 异步更新雷达图数据
        updateRadarData(context) {
            context.commit('updateRadarData')
        },

        // 异步获取 成绩分析模块真实数据
        getAchievementData(context) {
            return new Promise((r, j) => {
                if (context.state.achievementData) {
                    console.log('Cache-Achievement')
                    r(context.state.achievementData)
                } else {
					console.log(context.state.currentExam)
                    apiTools.totalAnalysis.getAchievementData({ code: context.state.currentExam.examCode , schoolCode:context.state.campusCode, subjectCode:context.state.currentExam.conditions.subject }).then(res => { // api请求
                        context.commit('getAchievementData', res.result.data) // 提交到vuex保存数据
                        context.commit('updateCurSubject', res.result.data.average.datas.map(item => item.name)[2]) // 提交到vuex保存数据
                        console.log('API-Achievement')
                        r(res.result.data)
                    }).catch(err => {
                        j(err)
                    })
                }
            })
        },

        // 异步获取 落点分析模块真实数据
        getScatterData(context) {
            let params = {
				schoolCode:context.state.campusCode,
                subjectCode: context.state.currentSubject,
                code: context.state.currentExam.examCode
            }
            return new Promise((r, j) => {
                if (context.state.scatterData) {
                    console.log('Cache-Scatter')
                    r(context.state.scatterData)
                } else {
                    apiTools.totalAnalysis.getScatterData(params).then(res => { // api请求
                        console.log('落点分析 科目切换成--' + context.state.currentSubject)
                        context.commit('getScatterData', res.result.data) // 提交到vuex保存数据
                        console.log('API-Scatter ')
                        r(res.result.data)
                    }).catch(err => {
                        j(err)
                    })
                }
            })
        },

        // 异步获取 试题分析模块真实数据
        getExerciseData(context) {
            let params = {
                subjectCode: context.state.currentSubject,
                code: context.state.currentExam.examCode,
                schoolCode:context.state.campusCode
            }
            return new Promise((r, j) => {
                if (context.state.exerciseData) {
                    console.log('Cache-ExerciseData')
                    r(context.state.exerciseData)
                } else {
                    apiTools.totalAnalysis.getExerciseData(params).then(res => { // api请求
                        console.log('试题分析 科目切换成--' + context.state.currentSubject)
                        context.commit('getExerciseData', res.result.data) // 提交到vuex保存数据
                        context.commit('getClassExerciseData', res.result.data) // 提交到vuex保存数据
                        console.log('API-ExerciseData ')
                        r(res.result.data)
                    }).catch(err => {
                        j(err)
                    })
                }
            })
        },

        // 异步获取 知识点掌握模块真实数据
        getKnowledgeData(context) {
            let params = {
                // Subject: context.state.currentSubject
                subjectCode: context.state.currentSubject,
                schoolCode:context.state.campusCode,
                code: context.state.currentExam.examCode
            }
            return new Promise((r, j) => {
                if (context.state.knowledgeData) {
                    console.log('Cache-knowledgeData')
                    r(context.state.knowledgeData)
                } else {
                    apiTools.totalAnalysis.getKnowledgeData(params).then(res => { // api请求
                        console.log('知识点掌握 科目切换成--' + context.state.currentSubject)
                        context.commit('getKnowledgeData', res.result.data) // 提交到vuex保存数据
                        console.log('API-knowledgeData ')
                        r(res.result.data)
                    }).catch(err => {
                        j(err)
                    })
                }
            })
        },

        // 异步获取 认知层次分布情况模块真实数据
        getLevelData(context) {
            let params = {
                // Subject: context.state.currentSubject
                subjectCode: context.state.currentSubject,
                type: '5',
                schoolCode: context.state.campusCode,
                code: context.state.currentExam.examCode
            }
            return new Promise((r, j) => {
                if (context.state.levelData) {
                    console.log('Cache-getLevelData')
                    r(context.state.levelData)
                } else {
                    apiTools.totalAnalysis.getKnowledgeData(params).then(res => { // api请求
                        console.log('知识点掌握 科目切换成--' + context.state.currentSubject)
                        context.commit('getLevelData', res.result.data) // 提交到vuex保存数据
                        console.log('API-getLevelData ')
                        r(res.result.data)
                    }).catch(err => {
                        j(err)
                    })
                }
            })
        }
    }
}
