/*
 * @Description: 新建或编辑任务
 * @Author: tangjiang
 * @Date: 2019-11-15 16:38:34
 * @Last Modified by: tangjiang
 * @Last Modified time: 2019-11-19 23:23:41
 */
import './index.scss';
import React, { useEffect } from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import SplitPane from 'react-split-pane';
import { Button } from 'antd';
import LeftPane from './leftpane';
import RightPane from './rightpane';
import { withRouter } from 'react-router';
import { toStore, CNotificationHOC, queryString } from 'educoder';
import UserInfo from '../components/userInfo';
import actions from '../../../redux/actions';

const NewOrEditTask = (props) => {
  const {
    publishLoading,
    handlePublish,
    identifier,
    isPublish,
    userInfo,
    submitLoading,
    changeSubmitLoadingStatus,
    changePublishLoadingStatus,
    startProgramQuestion,
    getUserInfoForNew,
    handleCancelPublish,
    validateOjForm,
    getQuestion,
    saveSearchParams,
    setOjInitialValue,
  } = props;

  const handleSubmitForm = () => {
    changeSubmitLoadingStatus(true);
    if (props.identifier) {
      props.handleUpdateOjForm(props);
    } else {
      props.handleFormSubmit(props); // 提交表单
    }
  };

  const id = props.match.params.id;
  useEffect(() => {
    // 获取用户信息
    getUserInfoForNew();
    props.saveOJFormId(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];
      });
      // 保存初始值
      if (obj['newoj']) {
        const tags = obj['tag_discipline_id'];
        const tag_arrs = (tags && tags.split(',').map(tag => +tag)) || [];
        setOjInitialValue({
          difficult: obj['difficult'],
          sub_discipline_id: obj['sub_discipline_id'],
          tag_discipline_id: tag_arrs
        });
      }
      saveSearchParams({ searchParams: $searchs, curPage: obj['pages'] });
    }
    // 获取课程列表
    getQuestion({
      source: 'question'
    });
    if (id) { // id号即 identifier
      props.getOJFormById(id);
    }
  }, [id])

  // 模拟挑战
  const imitationChallenge = () => {
    // 先调用保存, 再调用 start 接口, 成功后跳转到模拟页面
    // identifier && startProgramQuestion(identifier, props);
    identifier && validateOjForm(props, 'challenge', () => {
      startProgramQuestion(identifier, props);
    });
  }
  // 开始挑战
  const startChallenge = () => {
    // 调用 start 接口, 成功后跳转到开启实战
    identifier && validateOjForm(props, 'challenge', () => {
      startProgramQuestion(identifier, props);
    });
  }

  // 取消
  const newhandleClickCancel = () => {
    // 清空当前输入值并跳转至列表页
    props.clearOJFormStore();
    // 清空描述信息
    toStore('oj_description', '');
    if (props.location.search) {
      if (props.location.pathname === `/problems/new`) {
        props.history.push(`/problemset`);
      } else {
        props.history.push(`/problemset?${props.searchParams}`);
      }
      // let newurl=props.location.search.split('?');
      // props.history.push(newurl[1]);
    } else {
      props.history.push(`/problemset?${props.searchParams}`);
    }

  }

  // 取消
  const handleClickCancel = () => {
    // 清空当前输入值并跳转至列表页
    props.clearOJFormStore();
    // 清空描述信息
    toStore('oj_description', '');
    props.history.push(`/problemset?${props.searchParams}`);
  }

  // 返回试卷
  // const gotoshijuan = (classrooms,exercises) => {
  //   // // 清空当前输入值并跳转至列表页
  //   // props.clearOJFormStore();
  //   // // 清空描述信息
  //   // toStore('oj_description', '');
  //   // props.history.push(` classrooms/${classrooms}/exercises/${exercises}/edit`);
  // }

  // 发布
  const handleClickPublish = () => {
    props.confirm({
      title: '提示',
      content: (<p>发布后即可应用到自己管理的课堂<br /> 是否确认发布?</p>),
      onOk() {
        changePublishLoadingStatus(true);
        props.handlePublish(props, 'publish');
      }
    });
  }
  // 撤销发布
  const handleClickCancelPublish = () => {
    props.confirm({
      title: '提示',
      content: ((<p>是否确认撤销发布?</p>)),
      onOk() {
        changePublishLoadingStatus(true);
        handleCancelPublish(props, identifier);
      }
    });
  }

  // 取消保存/取消按钮
  const renderSaveOrCancel = () => {
    return (
      <React.Fragment>
        <Button
          onClick={newhandleClickCancel}
          style={{ background: '#666666', color: '#fff', border: 'none' }}
        >取消</Button>
        <Button
          type="primary"
          loading={submitLoading}
          onClick={handleSubmitForm}
        >保存</Button>
      </React.Fragment>
    );
  }
  // 发布/模拟挑战
  const renderPubOrFight = () => {
    const pubButton = isPublish
      ? (<Button
        style={{ background: 'rgba(102,102,102,1)', border: 'none' }}
        type="primary"
        loading={publishLoading}
        onClick={handleClickCancelPublish}
      >撤销发布</Button>)
      : (<Button
        type="primary"
        loading={publishLoading}
        onClick={handleClickPublish}
      >立即发布</Button>);
    // 未发布: 模拟挑战 已发布: 开始挑战
    const challengeBtn = isPublish ? (
      <Button type="primary" onClick={startChallenge}>开始挑战</Button>
    ) : (
        <Button type="primary" onClick={imitationChallenge}>模拟挑战</Button>
      );

    if (isPublish) {
      return (
        <React.Fragment>
          {pubButton}
          <Button
            type="primary"
            loading={submitLoading}
            onClick={handleSubmitForm}
          >保存</Button>
          {challengeBtn}
        </React.Fragment>
      );
    } else {
      return (
        <React.Fragment>
          <Button
            type="primary"
            loading={submitLoading}
            onClick={handleSubmitForm}
          >保存</Button>
          {pubButton}
          {challengeBtn}
        </React.Fragment>
      );
    }

  }

  // 渲染退出
  const renderQuit = () => {

    try {

      if (queryString.parse(props.location.search) === {} || queryString.parse(props.location.search) === "{}") {
        return identifier ? (
          <Button type="link"
            icon={"poweroff"}
            className='quite_btn'
            onClick={handleClickCancel}
          >{"退出"}</Button>
        ) : ''
      } else {
        let searchlist = queryString.parse(props.location.search)
        if (searchlist.classrooms) {
          return identifier ? (
            <Link className={"xiaoshou"} to={`/classrooms/${searchlist.classrooms}/exercises/${searchlist.exercises}/edit`}>
              <Button type="link"
                icon={"left"}
                className='quite_btn'
              // onClick={()=>gotoshijuan(searchlist.classrooms,searchlist.exercises)}
              >{"返回试卷"}</Button>
            </Link>
          ) : ''
        } else {
          return identifier ? (
            <Button type="link"
              icon={"poweroff"}
              className='quite_btn'
              onClick={handleClickCancel}
            >{"退出"}</Button>
          ) : ''
        }
      }
    } catch (e) {
      return identifier ? (
        <Button type="link"
          icon={"poweroff"}
          className='quite_btn'
          onClick={handleClickCancel}
        >{"退出"}</Button>
      ) : ''
    }

  }
  // console.log(props.location.search)
  return (
    <div className={'new_add_task_wrap'}>
      <div className={'task_header'}>
        <UserInfo userInfo={userInfo} />
        <p className={'header_title'}>{props.name || ''}</p>
        {renderQuit()}
      </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>
          <SplitPane split="vertical" defaultSize="100%" allowResize={false}>
            <RightPane onSubmitForm={handleSubmitForm} />
          </SplitPane>
        </SplitPane>
      </div>
      <div className='new_add_task_ctl'>
        {
          /* 录入时: 取消 保存 */
          /* 保存未发布: 立即发布 模拟挑战  */
        }
        {!identifier ? renderSaveOrCancel() : renderPubOrFight()}
      </div>
    </div>
  )
}

const mapStateToProps = (state) => {
  const { ojForm, identifier, testCases, isPublish, searchParams, courseQuestions } = state.ojFormReducer;
  const { publishLoading, submitLoading } = state.commonReducer;
  const { userInfo } = state.userReducer;
  return {
    name: ojForm.name,
    identifier,
    testCases,
    isPublish, // 是否已发布
    publishLoading,
    submitLoading,
    userInfo,
    searchParams,
    courseQuestions
  }
};

const mapDispatchToProps = (dispatch) => ({
  // 保存提交的代码值
  saveOjFormCode: (value) => dispatch(actions.saveOjFormCode(value)),
  // 表单提交时，调用表单验证功能
  handleFormSubmit: (props) => dispatch(actions.validateOjForm(props)),
  // 发布表单
  handlePublish: (props, type) => dispatch(actions.validateOjForm(props, type)),
  // 撤销发布
  handleCancelPublish: (props, identifier) => dispatch(actions.handleClickCancelPublish(props, identifier)),
  // 更新OJForm
  handleUpdateOjForm: (props) => dispatch(actions.validateOjForm(props)),
  // 根据id号获取表单信息
  getOJFormById: (id) => dispatch(actions.getOJFormById(id)),
  // 保存 OJ form id值
  saveOJFormId: (id) => dispatch(actions.saveOJFormId(id)),
  // 清空测试用例的集合
  clearOJFormStore: () => dispatch(actions.clearOJFormStore()),
  // 按钮状态
  changeSubmitLoadingStatus: (flag) => dispatch(actions.changeSubmitLoadingStatus(flag)),
  // 发布按钮状态
  changePublishLoadingStatus: (flag) => dispatch(actions.changePublishLoadingStatus(flag)),
  // 测试用例及验证
  updateTestAndValidate: (obj) => dispatch(actions.updateTestAndValidate(obj)),
  // 开启模拟挑战
  startProgramQuestion: (id, props) => dispatch(actions.startProgramQuestion(id, props)),
  // 新建时获取信息
  getUserInfoForNew: () => dispatch(actions.getUserInfoForNew()),
  validateOjForm: (props, type, cb) => dispatch(actions.validateOjForm(props, type, cb)),
  getQuestion: (params) => dispatch(actions.getQuestion(params)),
  saveSearchParams: (params) => dispatch(actions.saveSearchParams(params)),
  setOjInitialValue: (params) => dispatch(actions.setOjInitialValue(params))
});

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