import React, { Component } from 'react';

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

import Loading from '../../Loading';

import Loadable from 'react-loadable';

import { TPMIndexHOC } from './TPMIndexHOC';

import { SnackbarHOC } from 'educoder';

import TPMBanner from './TPMBanner';

import axios from 'axios';

import TPMShixunDiscussContainer from './TPMShixunDiscussContainer';

import TPMRepositoryComponent from './TPMRepositoryComponent';

import TPMRepositoryCommits from './shixunchild/Repository/TPMRepositoryCommits';

import TPMsettings from './TPMsettings/TPMsettings';

import TPMChallengeComponent from './TPMChallengeContainer'
import TPMPropaedeuticsComponent from './TPMPropaedeuticsComponent'
import TPMRanking_listComponent from './TPMRanking_listContainer'
import TPMCollaboratorsComponent from './TPMCollaboratorsContainer'

import '../page/tpiPage.css'
//任务
// const TPMChallengeComponent = Loadable({
//   loader: () => import('./TPMChallengeContainer'),
//   loading: Loading,
//   })

//背景知识
// const TPMPropaedeuticsComponent = Loadable({
//   loader: () => import('./TPMPropaedeuticsComponent'),
//   loading: Loading,
//   })

//版本库
// const TPMRepositoryComponent = Loadable({
//   loader: () => import('./TPMRepositoryComponent'),
//   loading: Loading,
//   })

// const TPMRepositoryComponent = Loadable({
//   loader: () => import('./TPMRepositoryComponent'),
//   loading: Loading,
//   })

//合作
// const TPMCollaboratorsComponent = Loadable({
// loader: () => import('./TPMCollaboratorsContainer'),
// loading: Loading,
// })


//评论
// const TPMShixunDiscussComponent = Loadable({
//   loader: () => import('./TPMShixunDiscussContainer'),
//   loading: Loading,
//   })

//排行版
// const TPMRanking_listComponent = Loadable({
// loader: () => import('./TPMRanking_listContainer'),
// loading: Loading,
// })

// //编辑实训
// const TPMModifysettings = Loadable({
//   loader: () =>import('./modules/tpm/TPMsettings/TPMsettings'),
//   loading: Loading,
//   })

//新建实训
const TPMchallengesnew = Loadable({
    loader: () => import('./challengesnew/TPMchallengesnew'),
    loading: Loading,
})

//新建tab2
const TPMevaluation = Loadable({
    loader: () => import('./challengesnew/TPMevaluation'),
    loading: Loading,
})

//新建tab3答案
// const TPManswer = Loadable({
//     loader: () => import('./challengesnew/TPManswer'),
//     loading: Loading,
// })
const TPManswer = Loadable({
    loader: () => import('./challengesnew/TPManswer2'),
    loading: Loading,
})

//选择题
const TPMquestion = Loadable({
    loader: () => import('./challengesnew/TPMquestion'),
    loading: Loading,
})

//fork列表
const TPMFork_listComponent = Loadable({
    loader: () => import('./TPMFork/TPMForklist'),
    loading: Loading,
})
//背景知识修改
const TPMUpdatepropaede = Loadable({
    loader: () => import('./TPMUpdatepropaede/TPMUpdatepropaede'),
    loading: Loading,
})


const interceptorUrlArray = ['repository.json', 'commits.json', 'propaedeutics.json'
    , 'challenges.json', 'discusses.json', 'ranking_list.json', 'collaborators.json']
const cacheInterceptorUrlMap = {}
class TPMIndex extends Component {
    constructor(props) {
      super(props)
      this.state = {
          loadingContent: false,
          power: false,
          shixunsDetails: {},
          shixunId: undefined,
          star_info: [0, 0, 0, 0, 0, 0],
          star_infos: [0, 0, 0, 0, 0, 0],
          identity:undefined,
          TPMRightSectionData:undefined,
          PropaedeuticsList: undefined,
      }
    }

    componentDidMount = () => {

        let id = this.props.match.params.shixunId;

        // let collaborators = `/shixuns/` + id + `/propaedeutics.json`;
        //
        // axios.get(collaborators).then((response) => {
        //     if (response.status === 200) {
        //         if (response.data.status === 403||response.data.status === 401||response.data.status === 500) {
        //
        //         }else{
        //             this.setState({
        //                 PropaedeuticsList: response.data,
        //                 shixunId: id
        //             });
        //         }
        //
        //     }
        // }).catch((error) => {
        //     console.log(error)
        // });

        let Url = `/shixuns/` + id + `.json`;
        axios.get(Url).then((response) => {
            if (response.status === 200) {
                document.title=response.data.name;
                let newstar_info = [];
                // let start1=
                for (var i = 0; i < response.data.score_info.length; i++) {

                    if (i === 0) {
                        newstar_info.push(response.data.score_info[i])
                    } else {
                        newstar_info.push((response.data.score_info[i] / 100) * 5)
                    }
                }
                let newstar_infos = response.data.score_info;
                this.setState({
                    shixunsDetails: response.data,
                    shixunId: id,
                    star_info: newstar_info,
                    star_infos: newstar_infos,
                    power: response.data.power,
                    identity: response.data.identity,
                    propaedeutics:response.data.propaedeutics,
                    status: response.data.shixun_status,
                });
            }
        }).catch((error) => {
            this.setState({
                shixunsDetails: undefined,
                shixunId:  undefined,
                star_info:  undefined,
                star_infos:  undefined,
                power:  undefined,
                identity:  undefined,
                status: undefined,
                propaedeutics:undefined
            });
        });

        this.tpmContentRequestInterceptor = axios.interceptors.request.use((config) => {
            let url = config.url;
            // console.log('tpmContentRequestInterceptor:', url)
            for ( let i = 0; i < interceptorUrlArray.length; i++ ) {
                if (url.indexOf(interceptorUrlArray[i]) != -1) {
                    url = url.split('?')[0]
                    console.log('loadingContent, url:', url)

                    this.setState({ loadingContent: true })

                    cacheInterceptorUrlMap[url] = true
                }
            }
            return config;
        }, function (error) {
            return Promise.reject(error);
        });

        // Add a response interceptor
        this.tpmContentResponseInterceptor = axios.interceptors.response.use((response) => {
            // console.log('loadingContent finished, url:', response.config.url)
            // TODO 依赖了api这个前缀
            let url = response.config.url.split('api')[1];
            url = url.split('?')[0]
            if (cacheInterceptorUrlMap[url]) {

                this.setState({ loadingContent: false })
                delete cacheInterceptorUrlMap[response.url]
            }
            return response;
        }, function (error) {
            // Do something with response error
            return Promise.reject(error);
        });


            //右侧数据
        let shixunsDetailsURL=`/shixuns/`+id+`/show_right.json`;
        axios.get(shixunsDetailsURL).then((response)=> {
                this.setState({
                    TPMRightSectionData: response.data
                });
        })

    }
    componentWillUnmount = () => {
      axios.interceptors.request.eject(this.tpmContentRequestInterceptor);
      this.tpmContentRequestInterceptor = null;
      axios.interceptors.request.eject(this.tpmContentResponseInterceptor);
      this.tpmContentResponseInterceptor = null;
    }
    
    
    setLoadingContent = (isLoadingContent) => {
        this.setState({ loadingContent: isLoadingContent })
    }

    // TpmTPMBannertype(type){
    //
    // }

  	render() {

        return (
            <div className="newMain clearfix">

                <TPMBanner
                    {...this.props}
                    {...this.state}
                ></TPMBanner>

                  <Switch {...this.props}>
                  
                  <Route path="/shixuns/:shixunId/repository/:repoId/commits" render={
                      (props) => (<TPMRepositoryCommits {...this.props} {...this.state} {...props}
                        />)
                    }></Route>

                    <Route exact path="/shixuns/:shixunId/challenges" render={
                      (props) => (<TPMChallengeComponent {...this.props} {...this.state} {...props}
                        />)
                    }></Route>

                      <Route path="/shixuns/:shixunId/repository" render={
                          (props) => (<TPMRepositoryComponent {...this.props} {...this.state} {...props}
                          />)
                      }></Route>
                    {/* <Route exact path="/shixuns/:shixunId/propaedeutics" component={TPMPropaedeuticsComponent}></Route> */}

                    <Route exact path="/shixuns/:shixunId/propaedeutics" render={
                      (props) => (<TPMPropaedeuticsComponent {...this.props} {...this.state} {...props}
                        />)
                    }></Route>


                    <Route exact path="/shixuns/:shixunId/collaborators" render={
                      (props) => (<TPMCollaboratorsComponent {...this.props} {...this.state} {...props}
                        />)
                    }></Route>

             
                    {/* <Route exact path="/shixuns/:shixunId/repository/:shixunId/" component={TPMRepositoryComponent}></Route> */}


                    <Route path="/shixuns/:shixunId/shixun_discuss" render={
                      (props) => (<TPMShixunDiscussContainer {...this.props} {...this.state} {...props}
                        initForumState={(data)=>this.initForumState(data)}
                        setSearchValue={this.setSearchValue}
                        setHotLabelIndex={this.setHotLabelIndex}
                        />)
                    }></Route>


                    <Route path="/shixuns/:shixunId/settings" render={
                      (props) => (<TPMsettings {...this.props} {...this.state} {...props} />)
                    }></Route>


                    <Route exact path="/shixuns/:shixunId/ranking_list" render={
                      (props) => (<TPMRanking_listComponent {...this.props} {...this.state} {...props}
                        />)
                    }></Route>

                  <Route exact path="/shixuns/:shixunId/fork_list" render={
                      (props) => (<TPMFork_listComponent {...this.props} {...props}
                      />)
                  }></Route>

                  <Route exact path="/shixuns/:shixunId/update_propaedeutics" render={
                      (props) => (<TPMUpdatepropaede {...this.props} {...props}
                      />)
                  }></Route>

                  {/*评测设置*/}
                  <Route path="/shixuns/:shixunId/challenges/:checkpointId/tab=2" render={
                      (props) => (<TPMevaluation {...this.props}  {...props} {...this.state}/>)
                  }></Route>


                  {/*参考答案*/}
                  <Route path="/shixuns/:shixunId/challenges/:checkpointId/tab=3" render={
                      (props) => (<TPManswer {...this.props}  {...props} {...this.state}/>)
                  }></Route>

                  {/*新建关卡*/}
                  <Route path="/shixuns/:shixunId/challenges/new" render={
                      (props) => (<TPMchallengesnew {...this.props} {...props}  {...this.state}/>)
                  }></Route>

                  {/*编辑关卡*/}
                  <Route path="/shixuns/:shixunId/challenges/:checkpointId/editcheckpoint" render={
                      (props) => (<TPMchallengesnew {...this.props} {...props} {...this.state} />)
                  }></Route>

                  {/*新建选择题*/}
                  <Route path="/shixuns/:shixunId/challenges/newquestion" render={
                      (props) => (<TPMquestion {...this.props}  {...props} {...this.state} />)
                  }></Route>

                  {/*修改选择题*/}
                  <Route path="/shixuns/:shixunId/challenges/:checkpointId/editquestion/:choose_id" render={
                      (props) => (<TPMquestion {...this.props}  {...props} {...this.state}/>)
                  }></Route>

                  {/*修改选择题*/}
                  <Route path="/shixuns/:shixunId/challenges/:checkpointId/editquestion" render={
                      (props) => (<TPMquestion {...this.props}  {...props} {...this.state}/>)
                  }></Route>

									<Route exact path="/shixuns/:shixunId" render={
											(props) => (<TPMChallengeComponent {...this.props} {...this.state} {...props}
											/>)
									}></Route>


                      {/*<Route exact path="/shixuns/:shixunId" component={TPMChallengeComponent}></Route>*/}
                  </Switch>

            </div>
	    );
  	}
}

export default SnackbarHOC() (TPMIndexHOC  ( TPMIndex ));
