/*
 * @Description: 学员学习
 * @Author: tangjiang
 * @Github:
 * @Date: 2019-11-23 10:53:19
 * @LastEditors  : tangjiang
 * @LastEditTime : 2020-02-10 18:24:01
 */
import './index.scss';
import React, { useEffect, useState } from 'react';
import { connect } from 'react-redux';
import SplitPane from 'react-split-pane';
import LeftPane from './leftpane';
import RightPane from './rightpane';
import { Icon, Modal } from 'antd';
import UserInfo from '../components/userInfo';
import actions from '../../../redux/actions';
import { CNotificationHOC, queryString } from 'educoder';
import { withRouter } from 'react-router';
const { confirm } = Modal;
function StudentStudy(props) {

  const [hasUpdate, setHasUpdate] = useState(true);
  const {
    hack,
    userInfo,
    restoreInitialCode,
    changeUserCodeTab,
    changeShowOrHideControl,
    searchParams,
    saveSearchParams
  } = props;

  const {
    match: { params },
    getUserProgramDetail,
    saveUserProgramIdentifier
  } = props;

  let { id, tab } = params;

  useEffect(() => {
    // 保存当前的id
    saveUserProgramIdentifier(id);
    try {
      if (id.charAt(id.length - 1) === "?") {
        id = id.substring(0, id.length - 1);
      }
    } catch (e) {

    }

    getUserProgramDetail(id);
    const $searchs = window.location.search && window.location.search.substring(1);
    if ($searchs) {
      const $params = $searchs.split('&') || [];
      let obj = Object.create(null);
      $params.forEach(item => {
        const keys = item.split('=');
        obj[keys[0]] = keys[1];
      });
      saveSearchParams({ searchParams: $searchs, curPage: obj['pages'] });
    }
    if (tab) {
      changeUserCodeTab(tab);
    }
  }, [id]);
  useEffect(() => {
    if (hack && hack.modify_code && hasUpdate) { // 代码更改，提示是否需要更新代码
      setHasUpdate(false);
      handleUpdateNotice();
    }
  }, [hack, hack.modify_code, hasUpdate]);

  const handleUpdateNotice = () => {
    props.confirm({
      title: '提示',
      content: (
        <p>
          代码文件有更新啦 <br />
          还未提交的代码，请自行保存
        </p>
      ),
      onOk() {
        restoreInitialCode(id, '更新成功');
      }
    })
  }
  // 处理编辑
  const handleClickEditor = (identifier) => {
    if (!identifier) return;
    changeShowOrHideControl(false);
    props.saveEditorCodeForDetail('');
    props.clearOjForUserReducer();
    props.history.push(`/problems/${identifier}/edit`);
  }
  // 处理退出
  const handleClickQuit = (type) => {
    // 退出时，清空内容
    props.clearOjForUserReducer();
    // 将控制台关闭
    changeShowOrHideControl(false);
    props.saveEditorCodeForDetail('');
    //这个是关闭窗口代码
    if (type === 1) {
      window.close();
    } else {
      props.history.push(`/problemset?${searchParams}`);
    }


  }

  const handlegoback = () => {
    confirm({
      title: '提示',
      content: '请确认你的答题内容已经提交？',
      onOk() {
        handleClickQuit(1)
      },
      onCancel() { },
    });
  }


  return (
    <div className={'student_study_warp'}>
      <div className={'student_study_header'}>

        <UserInfo userInfo={userInfo} />
        <div className={'study_name'}>
          <span>{hack.name}</span>
        </div>
        <div className={'study_quit'}>
          <span
            style={{ display: userInfo.hack_manager ? 'inline-block' : 'none' }}
            onClick={() => handleClickEditor(hack.identifier)}
            className={`quit-btn`}
          >
            <Icon type="form" className="quit-icon" /> 编辑
          </span>
          {props.location.search === "?type=exercises" ? <span onClick={handlegoback} className="quit-btn" >
            <Icon type="left" className="quit-icon" /> 返回试卷
          </span> : <span onClick={handleClickQuit} className="quit-btn" >
              <Icon type="poweroff" className="quit-icon" /> 退出
          </span>}
        </div>
      </div>
      <div className="split-pane-area">
        <SplitPane className="outer-split-pane" split="vertical" minSize={350} maxSize={-350} defaultSize="40%">
          <div className={'split-pane-left'}>
            <LeftPane />
          </div>
          <RightPane updateNotice={handleUpdateNotice} />
          <div />
        </SplitPane>
      </div>
    </div>
  )
}

const mapStateToProps = (state) => {
  const { userInfo } = state.userReducer;
  const { hack_identifier, user_program_identifier, hack } = state.ojForUserReducer;
  const { searchParams } = state.ojFormReducer;
  return {
    hack,
    userInfo,
    user_program_identifier,
    hack_identifier,
    searchParams
  };
};

const mapDispatchToProps = (dispatch) => ({
  // 调用开启编辑
  // startProgramQuestion: (id) => dispatch(actions.startProgramQuestion(id))
  // 调用编程题详情
  getUserProgramDetail: (id) => dispatch(actions.getUserProgramDetail(id)),
  saveUserProgramIdentifier: (id) => dispatch(actions.saveUserProgramIdentifier(id)),
  saveEditorCodeForDetail: (code) => dispatch(actions.saveEditorCodeForDetail(code)),
  // 恢复初始代码
  restoreInitialCode: (identifier, msg) => dispatch(actions.restoreInitialCode(identifier, msg)),
  changeShowOrHideControl: (flag) => dispatch(actions.changeShowOrHideControl(flag)),
  clearOjForUserReducer: () => dispatch(actions.clearOjForUserReducer()),
  changeUserCodeTab: (tab) => dispatch(actions.changeUserCodeTab(tab)),
  saveSearchParams: (params) => dispatch(actions.saveSearchParams(params))
});

export default withRouter(connect(
  mapStateToProps,
  mapDispatchToProps
)(CNotificationHOC()(StudentStudy)));


