import React, { Component } from 'react';
import LeftView from './LeftView'
import axios from 'axios'
import { commentHOC } from '../../comment/CommentsHOC'
import ImageLayer from '../layers/ImageLayer'

import _ from 'lodash'

const $ = window.$;

class LeftViewContainer extends Component {

	constructor(props) {
		super(props)

		this.tabIndexChange = this.tabIndexChange.bind(this)

		this.handleDialogClose = this.handleDialogClose.bind(this)
		this.handleDialogReadAnswer = this.handleDialogReadAnswer.bind(this)
		this.showNewReply = this.showNewReply.bind(this)
		this.state = {
			tabIndex: 0,
			dialogOpen: false,
			gameAnswer: '',
			dialogContent: '',
		}
	}

	showNewReply() {

		this.setState({
			tabIndex: 3,
		});
		this.props.showNewReply();
	}

	tabIndexChange(tabIndex, notDoFetch) {
		if (this.props.loading === true) {
			return;
		}
		//issues-29402 添加是否查看作业答案的老师配置  如果设置不能查看答案就传一个dialogContent
		if (tabIndex === 2 && this.props.game.homework_common_answer_open) {
			this.setState({
				dialogContent: '禁止查看答案',
				dialogOpen: true
			})
			return
		}
		if (tabIndex === 2 && this.state.gameAnswer === '') {	// 参考答案
			// 多级答案后换了接口
			// 选择题(st === 1)还是走以前的接口
			if ((this.props.st === 0)) {
				this.fetchIfCouldGetAnswerWithoutGoldForMultiLevelAnswer()
			} else if (this.props.st === 1) {
				this.fetchIfCouldGetAnswerWithoutGoldForChoose();
			}
			return;
		}
		if (tabIndex === 3 && !notDoFetch) {	// 评论
			this.props.fetchCommentIfNotFetched()
		}
		// TODO 2 参考答案     3 评论
		this.setState({
			tabIndex
		})
	}

	shouldComponentUpdate(nextProps, nextState) {
		if (JSON.stringify(nextProps) !== JSON.stringify(this.props) || !_.isEqual(this.state, nextState)) {
			return true
		} else {
			return false
		}
	}
	componentWillReceiveProps(newProps, newContext) {
		if (!this.props.loading && newProps.loading) {
			this.setState({ tabIndex: 0 })
		}
		if (newProps.challenge && newProps.challenge.id &&
			(!this.props || !this.props.challenge.id || (newProps.challenge.id != this.props.challenge.id))) {
			// 切换关卡，清空comments
			this.props.clearCommentsInState();
			var $ = window.$;
			// 任务切换重置state      
			this.setState({
				gameAnswer: '',
				lockedAnswers: [],
				unlockedAnswers: [],
			})
			this._initMarkdown()
		}
		// 切换了实训
		if (newProps.shixun && newProps.challenge.shixun && (!this.props || (newProps.shixun.id != this.props.shixun.id))) {
			this.setState({
				gameAnswer: '',
				comments: [],
				comment_count_without_reply: 0,
				currentPage: 1,
				tabIndex: 0,
			})
		}

	}

	_initMarkdown() {
		$("#game_task_pass").delegate("img", "click", (event) => {
			const imageSrc = event.target.src

			this.setState({
				showImage: true,
				imageSrc,
			})
		});

	}
	onImageLayerClose = () => {
		this.setState({
			showImage: false,
			imageSrc: '',
		})
	}
	componentDidMount() {
		this.newMessageIntervalRet = setInterval(() => {
			const { shixun, newMessage } = this.props;
			if (shixun && shixun.id) {
				newMessage && newMessage()
			}
		}, 1000 * 60 * 1)
	}

	componentWillUnmount() {
		this.newMessageIntervalRet && clearInterval(this.newMessageIntervalRet)
		$("#game_left_contents #tab_con_4").undelegate()
	}

	handleDialogClose() {
		this.setState({
			dialogOpen: false
		})
	}

	/**
		 1、返回一个或多个都有contents答案，直接显示
		 2、返回一个没content的答案，弹出老对话框
		 3、返回多个答案，部分有contents，直接显示列表，用户进一步解锁的时候再弹新对话框
		 4、返回多个没有contents的答案，直接弹出新对话框
	 */
	fetchIfCouldGetAnswerWithoutGoldForMultiLevelAnswer() {
		var getAnswerUrl = `/tasks/${this.props.game.identifier}/get_answer_info.json`
		axios.get(getAnswerUrl, {})
			.then((response) => {
				response.data = response.data.message || response.data;
				if (response.data) {
					if (response.data.length === 0) {
						this.props.showSnackbar('本关卡未设置答案。')
						return;
					}
					let unlockedAnswers = []
					let lockedAnswers = []
					if (!response.data.length) {
						this.setState({
							dialogOpen: true,
							isMultiLevelAnswer: false,
							singleAnswerId: response.data.answer_id
						})
						return;
					}
					const newAnswers = response.data.map((item, index) => {
						return {
							id: item.answer_id,
							name: item.answer_name,
							score: item.answer_score,
							contents: item.answer_contents,
							view_time: item.view_time
						}
					})
					newAnswers.forEach((item, index) => {
						if (item.contents) {
							unlockedAnswers.push(item)
						} else {
							lockedAnswers.push(item)
						}
					})

					this.setState({
						tabIndex: 2,
						lockedAnswers,
						unlockedAnswers,
						dialogOpen: unlockedAnswers.length === 0,
						isMultiLevelAnswer: newAnswers.length > 1
					})
				}
			})
			.catch(function (error) {
				console.log(error);
			});
	}
	// 选择题查看答案
	fetchIfCouldGetAnswerWithoutGoldForChoose() {
		const url = `/tasks/${this.props.game.identifier}/get_choose_answer.json`
		axios.get(url)
			.then((response) => {

				if (response.data.status == 0) {
					this.props.showSnackbar(response.data.message)
					return;
				}
				/*
				将扣除XXX点金币，是否确认查看答案     
				已经过职业认证的教师可以免金币查看答案哟
				继续查看 立即认证（新开页）
				*/

				if (response.data.choose_answers) {
					this.showAnswer(response.data.choose_answers)
				} else if (response.data.status == 1) {
					this.setState({
						dialogOpen: true,
					})
				}
			})
			.catch(function (error) {
				console.log(error);
			});

		return;
	}
	showUnlockAnswerDialog = (anwser) => {
		this.setState({
			dialogOpen: true,
		})
	}
	showAnswer(gameAnswer) {
		this.setState({
			tabIndex: 2,
			dialogOpen: false,
			gameAnswer,
		})
	}
	handleMultiLevelAnswer = (selectID) => {
		let paramSelectID = selectID
		if (!selectID) {
			paramSelectID = this.state.lockedAnswers[0].id
		}
		const url = `/tasks/${this.props.game.identifier}/unlock_answer.json?answer_id=${paramSelectID}`
		axios.get(url)
			.then((response) => {
				if (response.data.status != -1) {
					const lockedAnswers = this.state.lockedAnswers
					const challenge_score = this.props.challenge.score
					// 前端计算扣除金币数
					let goldToMinuse = 0
					if (this.state.isMultiLevelAnswer) {
						for (let i = 0; i < lockedAnswers.length; i++) {
							let answer = lockedAnswers[i];
							goldToMinuse = goldToMinuse + answer.score * challenge_score / 100;
							if (answer.id == paramSelectID) {
								break;
							}
						}
					} else {
						goldToMinuse = challenge_score
					}

					this.props.readGameAnswer({
						grade: this.props.grade - goldToMinuse
					})

					this.fetchIfCouldGetAnswerWithoutGoldForMultiLevelAnswer()
					this.setState({
						tabIndex: 2,
						dialogOpen: false,
					})
				} else {
					this.props.showSnackbar(response.data.message)
				}
			})
			.catch(function (error) {
				console.log(error);
			});
	}
	getChooseAnswer = () => {
		const url = `/tasks/${this.props.game.identifier}/unlock_choose_answer.json`
		axios.get(url)
			.then((response) => {

				if (response.data.status == 0) {
					this.props.showSnackbar(response.data.message)
					return;
				}
				const gameAnswer = response.data.choose_answers;
				this.props.readGameAnswer({
					grade: this.props.grade - this.props.challenge.score
				})

				this.showAnswer(gameAnswer)

			})
			.catch(function (error) {
				console.log(error);
			});
	}
	handleDialogReadAnswer(selectID) {
		if (this.props.st === 1) {
			// 选择题
			this.getChooseAnswer()
		} else {
			this.handleMultiLevelAnswer(selectID || this.state.singleAnswerId)
		}
	}
	createNewComment = (page) => {
		const flag = this.props.createNewComment(page)
		if (flag === true) {
			this.tabIndexChange(3, true)
		}
	}
	//  /shixuns/mnf6b7z3/shixun_discuss?challenge_id=88
	render() {
		const { tabIndex } = this.state;
		return (
			<React.Fragment>
				<ImageLayer {...this.state} onImageLayerClose={this.onImageLayerClose}></ImageLayer>

				<LeftView {...this.props} tabIndexChange={this.tabIndexChange} {...this.state} tabIndex={tabIndex}
					handleDialogReadAnswer={this.handleDialogReadAnswer} handleDialogClose={this.handleDialogClose}

					showNewReply={this.showNewReply}
					showUnlockAnswerDialog={this.showUnlockAnswerDialog}
					createNewComment={this.createNewComment}
					dialogContent={this.state.dialogContent}
				></LeftView>
			</React.Fragment>
		);
	}
}

export default commentHOC(LeftViewContainer);
