import React, { Component } from 'react';

import { Redirect } from 'react-router';

import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";

import PropTypes from 'prop-types';

import classNames from 'classnames';

import { getImageUrl ,markdownToHTML} from 'educoder'

import { CircularProgress } from 'material-ui/Progress';

import { Modal, Spin, Tooltip ,message,Icon} from 'antd';

import 'antd/lib/pagination/style/index.css';

import '../shixunchildCss/Challenges.css'

import axios from 'axios';

import AccountProfile from"../../../user/AccountProfile";

const $ = window.$;

class Challenges extends Component {
  constructor(props) {
    super(props)
    this.state = {
      ChallengesDataList: undefined,
      operate: true,
      startbtns: false,
      sumid: "",
      sumidtype: false,
      startshixunCombattype:false,
      shixunsreplace:false,
      shixunsmessage:"",
      hidestartshixunsreplacevalue:"",
      operationstrue:false,
			isSpin:false,
    }
  }

  ChallengesList = () => {
    let id = this.props.match.params.shixunId;
    let ChallengesURL = `/shixuns/` + id + `/challenges.json`;

    axios.get(ChallengesURL).then((response) => {
      if (response.status === 200) {
        if (response.data.status === 403||response.data.status === 401||response.data.status === 500) {

        }else{
          this.setState({
            ChallengesDataList: response.data,
            sumidtype: false,
          });
        }
      }
    }).catch((error) => {
      console.log(error)
    });
  }

  componentDidMount() {
    setTimeout(this.ChallengesList(), 1000);
  }

  updatamakedown = (id) => {
    setTimeout(() => {
      var shixunDescr = window.editormd.markdownToHTML(id, {
        htmlDecode: "style,script,iframe",
        taskList: true,
        tex: true,
        flowChart: true,
        sequenceDiagram: true
      });
      $("#" + id + " p:first").addClass("ReactMarkdown");
    }, 200)
  }

  // 关卡的上移下移操作
  operations = (sumid, type) => {
    this.setState({
      operationstrue:true
    })
    let { ChallengesDataList } = this.state;
    let operationUrl;
    if (type === "up") {
      operationUrl = "/shixuns/" + ChallengesDataList.shixun_identifier + "/challenges/" + sumid + "/index_up.json";
    } else if (type === "down") {
      operationUrl = "/shixuns/" + ChallengesDataList.shixun_identifier + "/challenges/" + sumid + "/index_down.json";
    }
    if (this.state.operate) {

      this.setState({
        operate: false
      });
      axios.get(operationUrl).then((response) => {
        if (response.status === 200) {
          this.setState({
            operate: true,
            operationstrue:false
          });
          this.ChallengesList();

        }
      }).catch((error) => {
        console.log(error);
        this.setState({
          operate: true,
          operationstrue:false
        });
        this.ChallengesList()
      })
    }
  }
  delOperations = (sumid) => {
    this.setState({
      sumid: sumid,
      sumidtype: true
    })
  }

  clonedelOperationss = () => {
    this.setState({
      sumidtype: false
    })
  }
  delOperationss = () => {
    let { ChallengesDataList, sumid } = this.state;
    let operationUrl = "/shixuns/" + ChallengesDataList.shixun_identifier + "/challenges/" + sumid+".json"

    if (this.state.operate) {
      this.setState({
        operate: false,
        sumidtype: false
      })
      axios.delete(operationUrl, {
        withCredentials: true
      }).then((response) => {
        if (response.status === 200) {
          this.setState({
            operate: true,
            sumidtype: false
          });
          this.ChallengesList();
        }
        this.ChallengesList()
      }).catch((error) => {
        console.log(error);
        this.setState({
          operate: true,
          sumidtype: false
        });
        this.ChallengesList()
      })
    }
  }

	startgameid=(id)=>{

		let url = "/shixuns/" + id + "/shixun_exec.json";
		axios.get(url).then((response) => {

			if (response.data.status === -2) {
				this.setState({
					shixunsreplace:true,
					hidestartshixunsreplacevalue:response.data.message+".json"
				})
			} else if (response.data.status === -1) {
				console.log(response)
			}else if(response.data.status===-3){
				this.setState({
					shixunsmessage:response.data.message,
					startshixunCombattype:true,
				})
			} else {
				window.location.href = "/tasks/" + response.data.game_identifier;
				// window.location.href = path
				// let path="/tasks/"+response.data.game_identifier;
				// this.props.history.push(path);
			}
		}).catch((error) => {

		});


	}

	hidestartshixunsreplace=(url)=>{
		this.setState({
			isSpin:true,
		})
		axios.get(url).then((response) => {
			if(response.status===200){
				// let path="/shixuns/"+response.data.shixun_identifier+"/challenges";
				// this.props.history.push(path);
				message.success('重置成功，正在进入实训！');
				this.startgameid(response.data.shixun_identifier);
				this.setState({
					shixunsreplace:false,
					isSpin:false,
				})

				// message.success('重置成功，正在进入实训！');
				// this.startshixunCombat();
			}}
		).catch((error) => {

		});

	}

  //编辑实训题目选择题
	EditTraining=(type, ids, path)=>{
		let { ChallengesDataList } = this.state;
		window.location.href = "/shixuns/" + ChallengesDataList.shixun_identifier + "/challenges/" + ids + path;
	}

  //开始实战按钮
  startshixunCombat = (type, ids, id) => {

		if(this.props.checkIfLogin()===false){
			this.props.showLoginDialog()
			return
		}


		if(this.props.current_user&&this.props.current_user.profile_completed===false){
			this.setState({
				AccountProfiletype:true
			})
			return
		}


		let { ChallengesDataList } = this.state;
			// let id = this.props.match.params.shixunId;
				this.setState({
					startbtns: true
				})
				let url = "/shixuns/" + ChallengesDataList.shixun_identifier + "/shixun_exec.json?challenge_id="+id;
				axios.get(url).then((response) => {

					if (response.data.status === -2) {
						this.setState({
							startbtns:false,
							shixunsreplace:true,
							hidestartshixunsreplacevalue:response.data.message+".json"
						})
					} else if (response.data.status === -1) {
						this.setState({
							startbtns: false
						})
						console.log(response)
					}else if(response.data.status===-3){
						this.setState({
							shixunsmessage:response.data.message,
							startshixunCombattype:true,
							startbtns:false
						})
					} else {
						window.location.href = "/tasks/" + response.data.game_identifier;
						// window.location.href = path
						// let path="/tasks/"+response.data.game_identifier;
						// this.props.history.push(path);
					}
				}).catch((error) => {

				});


		// if(path===null){
		// }else{
		// 	if (type > 4 || type === false) {
		// 		window.location.href = path;
		// 	} else {
		//
		// 	}
		// }


  }
  hidestartshixunCombattype=()=>{
    this.setState({
      startshixunCombattype:false
    })
  }

	hideAccountProfile=()=>{
		this.setState({
			AccountProfiletype:false
		})
	}

  render() {
    let { ChallengesDataList, startbtns, sumidtype ,startshixunCombattype,shixunsreplace,shixunsmessage,hidestartshixunsreplacevalue,operationstrue,AccountProfiletype} = this.state;
    let { loadingContent } = this.props;
    if (ChallengesDataList != undefined) {
      this.updatamakedown("ReactMarkdown")
    }
    let id = this.props.match.params.shixunId;
		const antIcon = <Icon type="loading" style={{ fontSize: 24 }} spin />;
    return (
      <React.Fragment>
				{AccountProfiletype===true?<AccountProfile
					hideAccountProfile={()=>this.hideAccountProfile()}
					{...this.props}
					{...this.state}
				/>:""}

        {loadingContent ?
          <CircularProgress size={40} thickness={3} style={{
            marginLeft: 'auto',
            marginRight: 'auto',
            marginTop: '200px',
            display: 'block'
          }} /> :

          <div className="mt30 pl20 pr20">

            <p className="clearfix mb30">
              <span className="font-16 fl">简介</span>
							<Tooltip placement="bottom" title={"编辑"}>
              <a style={{ display: this.props.identity < 5 && ChallengesDataList&&ChallengesDataList.shixun_status < 3 ? "block" : 'none' }}
                 href={"/shixuns/" + id + "/settings?edit=1"} className="ring-green fr">
                <img src={getImageUrl("images/educoder/icon/edit.svg")} className="fl mt3 ml2" />
              </a>
							</Tooltip>
            </p>

            <div className="justify break_full_word new_li "
                 id="challenge_editorMd_description">
              <p id="ReactMarkdown" style={{overflow:'hidden'}}>
                {ChallengesDataList === undefined ? "" :ChallengesDataList&&ChallengesDataList.description===null?"":
									<div className={"markdown-body"} dangerouslySetInnerHTML={{__html: markdownToHTML(ChallengesDataList.description).replace(/▁/g,"▁▁▁")}}></div>
                }
              </p>

              {/*
                   <span className="markdown-body" dangerouslySetInnerHTML={{__html: markdownToHTML(question_title)}}
        style={{ display: 'inline-block', width:'100%' , margin: '10px 0px 15px' }}></span>
              */}
            </div>

            <p className="clearfix mb10 mt20">
              <span className="font-16 fl">全部任务</span>
              {this.props.identity < 5 && ChallengesDataList&&ChallengesDataList.shixun_status=== 0 ?
                <Link to={"/shixuns/" + id + "/challenges/new"}
                      className="white-btn edu-greenline-btn fr"
                  // data-tip-down="新增代码编辑类型任务"
                >
                  <Tooltip placement="bottom" title={"新增代码编辑类型任务"}>
                    <img src={getImageUrl("images/educoder/icon/addsmallgreen.svg")}
                         className="fl mr5 mt6" />
                    实践任务
                  </Tooltip>

                </Link> : ""
              }
              {this.props.identity < 5 && ChallengesDataList&&ChallengesDataList.shixun_status=== 0 ?
                <Link to={"/shixuns/" + id + "/challenges/newquestion"}
                      className="white-btn edu-greenline-btn fr mr20"
                  // data-tip-down="新增选择题类型任务"
                >
                  <Tooltip placement="bottom" title={"新增选择题类型任务"}>
                    <img src={getImageUrl("images/educoder/icon/addsmallgreen.svg")}
                         className="fl mr5 mt5" />
                    选择题任务
                  </Tooltip>
                </Link> : ""
              }
            </p>

            <div className="alltask">
              {ChallengesDataList === undefined ? <div className="alltask">
                <div className="edu-tab-con-box clearfix edu-txt-center">
                  <img className="edu-nodata-img mb20"
                       src={getImageUrl("images/educoder/nodata.png")} />
                  <p className="edu-nodata-p mb20">暂时还没有相关数据哦！</p>
                </div>
              </div> : ChallengesDataList.challenge_list === undefined ?
                <div className="alltask">
                  <div className="edu-tab-con-box clearfix edu-txt-center">
                    <img className="edu-nodata-img mb20"
                         src={getImageUrl("images/educoder/nodata.png")} />
                    <p className="edu-nodata-p mb20">暂时还没有相关数据哦！</p>
                  </div>
                </div>
                : ChallengesDataList.challenge_list.length === 0 ?
                  <div className="alltask">
                    <div className="edu-tab-con-box clearfix edu-txt-center">
                      <img className="edu-nodata-img mb20"
                           src={getImageUrl("images/educoder/nodata.png")} />
                      <p className="edu-nodata-p mb20">暂时还没有相关数据哦！</p>
                    </div>
                  </div>
                  : ChallengesDataList.challenge_list.map((item, key) => {

                    let newstatus = 2;
                    if(ChallengesDataList.challenge_list[key - 1]!=undefined){
                      newstatus=ChallengesDataList.challenge_list[key - 1].status;
                    }
                    return (
                      <div className="task-item" key={key} id={"shixun_index_" + item.position}>

                        <div className="clearfix mb20">
                            <span className="fl ring-blue mr10 mt8">
                              {item.st === 0 ?
																<Tooltip placement="bottom" title={"实训任务"}>
                                <img src={getImageUrl("images/educoder/icon/code.svg")} className="fl mt2 ml2" />
																</Tooltip>
                                :
																<Tooltip placement="bottom" title={"选择题任务"}>
                                <img src={getImageUrl("images/educoder/icon/choose.svg")} className="fl mt2 ml3" />
																</Tooltip>
                              }
                            </span>
                          <span className="mr15 font-16 fl">第{key+1}关</span>

                          {this.props.identity<5?
                            item.st === 1 ?
                              <a onClick={() => this.EditTraining(this.props.identity, item.challenge_id, "/editquestion")}
                                 className="font-16 color05101a">{item.name}</a>
                              :
                              <a onClick={() => this.EditTraining(this.props.identity, item.challenge_id, "/editcheckpoint")}
                                 className="font-16 color05101a">{item.name}</a>:<span
                              // onClick={() => this.startshixunCombat(this.props.identity, item.challenge_id, "/editcheckpoint")}
                              className="font-16 color05101a">{item.name}</span>
                          }

                          <Modal
                            keyboard={false}
                            visible={startbtns}
                            closable={false}
                            footer={null}
                            className="startbtnModal"
                          >
                            <Spin size="large" />
                          </Modal>
                          <span className="fr mt8">


                              {item.delete_url != undefined &&
                              <Tooltip placement="bottom" title={"删除"}>
                                <a onClick={() => this.delOperations(item.challenge_id)}
                                   style={{ display:this.props.user.admin===true?"block":this.props.identity < 5 && ChallengesDataList.shixun_status === 0 ? "block" : 'none' }}
                                   className="fl ring-op-green mr25">
                                  <img src={getImageUrl("images/educoder/icon/close.svg")}
                                       className="fl mt5 ml5" />
                                </a>
                              </Tooltip>
                              }


                            {item.up_url != undefined &&
                            <Tooltip placement="bottom" title={"向上移动"}>
                              <a onClick={operationstrue===true?"":() => this.operations(item.challenge_id, "up")}
                                 style={{ display:this.props.user.admin===true?"block":this.props.identity < 5 && ChallengesDataList.shixun_status === 0 ? "block" : 'none' }}
                                 className="fl ring-op-green mr25">
                                <img src={getImageUrl("images/educoder/icon/moveup.svg")}
                                     className="fl mt2 ml4" />
                              </a>
                            </Tooltip>
                            }
                            {item.down_url != undefined &&
                            <Tooltip placement="bottom" title={"向下移动"}>
                              <a onClick={operationstrue===true?"":() => this.operations(item.challenge_id, "down")}
                                 style={{ display: this.props.user.admin===true?"block":this.props.identity < 5 && ChallengesDataList.shixun_status=== 0 ? "block" : 'none' }}
                                 className="fl ring-op-green mr25">
                                <img src={getImageUrl("images/educoder/icon/movedown.svg")} className="fl mt2 ml4" />
                              </a>
                            </Tooltip>

                            }

                            {
                              item.st === 1 ?
                                <Tooltip placement="bottom" title={"编辑"}>
                                  <a
                                    style={{ display:this.props.user.admin===true?"block":this.props.identity < 5 && ChallengesDataList.shixun_status< 3 ? "block" : 'none' }}
                                    href={"/shixuns/" + ChallengesDataList.shixun_identifier + "/challenges/" + item.challenge_id + "/editquestion"}
                                    className="fl ring-green">
                                    <img src={getImageUrl("images/educoder/icon/edit.svg")}
                                         className="fl mt3 ml2" />
                                  </a>
                                </Tooltip>
                                :
                                <Tooltip placement="bottom" title={"编辑"}>
                                  <a
                                    style={{ display:this.props.user.admin===true?"block":this.props.identity < 5 && ChallengesDataList.shixun_status < 3 ? "block" : 'none' }}
                                    href={"/shixuns/" + ChallengesDataList.shixun_identifier + "/challenges/" + item.challenge_id + "/editcheckpoint"}
                                    className="fl ring-green">
                                    <img src={getImageUrl("images/educoder/icon/edit.svg")}
                                         className="fl mt3 ml2" />
                                  </a>
                                </Tooltip>

                            }

                            </span>
                        </div>
                        <div className="clearfix pl28">
													<span className="task-colspan"><span className={"color-orange"}>{item.passed_count}</span>&nbsp;人完成挑战</span>
                          <span
                            className="task-colspan"><span className={"color-orange"}>{item.playing_count}</span>&nbsp;人正在挑战</span>
													<span className="task-colspan"><span>完成挑战可获得经验值&nbsp;<span className={"color-orange"}>{item.score}</span></span></span>


                          {/*判断比较复杂 有排第一不能是灰色按钮*/}
                          {item.status === 2 ?
                            <a className={"edu-default-btn edu-blueline-btn fr Finish_button mtf3"}
															 onClick={()=>this.startshixunCombat(false,undefined, item.challenge_id)}
                               // onClick={() => this.startshixunCombat(false)}
															 title={"查看挑战关卡"}
                            >已完成</a> : ""
                          }

                          {
                            ChallengesDataList.allow_skip === true && item.status === 1?
                              <a className={"edu-default-btn edu-blueback-btn fr Finish_button"}
																 title={"直接挑战"}
                                 style={{marginTop: '-2px'}}
																 onClick={()=>this.startshixunCombat(false,undefined, item.challenge_id)}
                                 // onClick={() => this.startshixunCombat(false)}
                              >直接挑战</a> : ""
                          }


													{
														ChallengesDataList.allow_skip === false ? item.status === 1?
															<Tooltip placement="bottom" title={"直接挑战"}>
																<a className={"edu-default-btn edu-blueback-btn fr Finish_button"}
																	 onClick={()=>this.startshixunCombat(false,undefined, item.challenge_id)}
																	 style={{marginTop: '-2px'}}>直接挑战</a>
															</Tooltip>:"":""

													}



                          {
                           item.status === 0 ?
                              <Tooltip placement="bottom" title={"请先完成前序关卡"}>
                                <a className={"edu-default-btn edu-greyback-btn fr Finish_button"}
                                   // onClick={this.props.identity<5&&item.open_game!=""?()=>this.startshixunCombat(false,undefined, item.challenge_id):""}
                                   style={{marginTop: '-2px'}}>直接挑战</a>
                              </Tooltip>:""
                          }



                        </div>
                      </div>
                    )
                  })}
            </div>
            <Modal
              keyboard={false}
              title="提示"
              visible={sumidtype}
              closable={false}
              footer={null}
            >
              <div className="task-popup-content">
                <p className="task-popup-text-center font-16">
                  <span className="font-17 mt10">是否删除该关卡？</span>
                </p>
                <p className="task-popup-text-center font-16 mt30">
                  <a className="pop_close task-btn mr20"
                     onClick={() => this.clonedelOperationss()}
                  >取消</a>
                  <a onClick={() => this.delOperationss()}
                     className="task-btn task-btn-orange ">确定</a>

                </p>
              </div>

            </Modal>

            <Modal
              keyboard={false}
              title="提示"
              visible={startshixunCombattype}
              closable={false}
              footer={null}
            >
              <div className="task-popup-content">
                <p className="task-popup-text-center font-16 pb20">本实训的开启时间：{shixunsmessage} <br/>开启时间之前不能挑战 </p>
              </div>
              <div className="task-popup-submit clearfix">
                {/*<a onClick={this.hidestartshixunCombattype} className="task-btn fl">取消</a>*/}
                <a className="task-btn task-btn-orange fr mr51" onClick={this.hidestartshixunCombattype}>知道了啦</a>
              </div>
              {/*<p className="inviteTipbtn with100 fl">*/}
              {/*<a onClick={this.hidestartshixunCombattype}>知道了</a>*/}
              {/*</p>*/}
            </Modal>

            <Modal
              keyboard={false}
              title="提示"
              visible={shixunsreplace}
              closable={false}
              footer={null}
            >
							<Spin indicator={antIcon} spinning={this.state.isSpin}>
								<div className="task-popup-content">
									<p className="task-popup-text-center font-16 pb20">实训已经更新了，正在为您重置!</p>
								</div>
								<div className="task-popup-submit clearfix">
									<a className="task-btn task-btn-orange fr mr51"
										 onClick={() => this.hidestartshixunsreplace(hidestartshixunsreplacevalue)}>知道了</a>
								</div>
							</Spin>
            </Modal>
          </div>
        }
      </React.Fragment>

    )
  }
}

export default Challenges;
    // {
		// 				ChallengesDataList.allow_skip === false ? item.status === 1 && newstatus === 2 ?
		// 					<Tooltip placement="bottom" title={"直接挑战"}>
		// 						<a className={"edu-default-btn edu-blueback-btn fr Finish_button"}
		// 							 onClick={()=>this.startshixunCombat(false,undefined, item.challenge_id)}
		// 						style={{marginTop: '-2px'}}>直接挑战</a>
		// 					</Tooltip>
		//
		// 					: item.status === 1 && newstatus === 1 ?
		// 						<Tooltip placement="bottom" title={"直接挑战"}>
		// 							<a className={"edu-default-btn edu-blueback-btn fr Finish_button"}
		// 								 onClick={()=>this.startshixunCombat(false,undefined, item.challenge_id)}
		// 								 style={{marginTop: '-2px'}}>直接挑战</a>
		// 						</Tooltip> : "" : ""
		//
		// 			}