import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import {CopyToClipboard} from 'react-copy-to-clipboard';
import AceEditor from 'react-ace';
import { Toast } from "antd-mobile"
import {HeaderBar} from '@/common';
import { browser, http, getParam, wxShare } from '@/utils';
import './index.scss';
import 'ace-builds/src-noconflict/mode-python';
import 'ace-builds/src-noconflict/theme-dracula';

class MLClass extends Component {

  constructor(props) {
    super(props);
    this.state = {
      isWechat: browser.isWeixin,
      isShare: true,
      type: '1', // 1:课后习题，2:课堂习题
      entryMode: 0, // 0：扫码页，1:落地页
      isGuide: false, // 是否展示引导
      isExecute: false,
      isCopy: false,
      command: '',
      data: {}
    }
  }

  componentDidMount() {
    this.handleFetchInfo();
    this.initPageStatus();
    this.initCommand();
  }

  initCommand = () => {
    this.setState({
      command: `${API.m}/mlShare?id=${getParam('id')}&type=${getParam('type')}&ques=${getParam('ques')}&origin=ml`
    })
  }

  initPageStatus = () => {
    if(getParam('origin') === 'barcode') {
      this.setState({
        entryMode: 0
      });
    }
    if(getParam('origin') === 'ml') {
      this.setState({
        entryMode: 1
      });
    }
    if(getParam('type') === '1') {
      this.setState({
        isShare: true
      });
    }
    if(getParam('type') === '2') {
      this.setState({
        isShare: false
      });
    }
    this.setState({
      type: getParam('ques') || '1'
    });
  }

  handleFetchInfo = () => {
    const id = getParam('id') || 10;
    http.get(`${API.home}/m/it/share/show`, {
      params: {
        id
      }
    }).then(res => {
      const { code, data } = res.data;
      if(code === 200) {
        this.setState({
          data,
        });
      }
    })
  }

  handleToSend = (params) => {
    const { history } = this.props;
    const { isShare } = this.state;
    if(browser.isWeixin) {
      history.push(`/mlShare?id=${getParam('id')}&type=${getParam('type')}&ques=${getParam('ques')}&origin=ml`);
      this.setState({
        isGuide: true
      });
      wxShare({
        title: isShare? `我已在【${params.course_name}】上运行了行代码了${params.code_lines}` : `我在${params.course_name}的${this.formatTitle(params)}遇到了困难`,
        desc: this.formatTitle(params),
        link: encodeURI(location.href),
        imgUrl: params.course_img,
      });
    }
  }

  formatTitle = (params) => {
    const { type } = this.state;
    if(type === '1') {
      return `练习-${params.ques_name}`;
    }
    if(type === '2') {
      return `课堂-${params.video_name}`;
    }
  }

  copyToSuccess = () => {
    Toast.info('已复制链接，快去粘贴发给好友吧～');
    this.setState({
      isCopy: true
    });
  }

  handleToExecute = () => {
    this.setState({
      isExecute: true
    });
  }

  handleToHide = () => {
    this.setState({
      isGuide: false
    });
  }

  render() {
    const { isWechat, isShare, isExecute, entryMode, command, isCopy, isGuide, data } = this.state;
    return (
      <>
        <HeaderBar
          title='机器学习小课 第一期'
          arrow={true}
          home={true}
        />
        <PythonContent
          isWechat={isWechat}
          isShare={isShare}
          isExecute={isExecute}
          entryMode={entryMode}
          isGuide={isGuide}
          isCopy={isCopy}
          command={command}
          data={data}
          labelName={this.formatTitle(data)}
          handleToExecute={this.handleToExecute}
          handleToSend={() => this.handleToSend(data)}
          copyToSuccess={this.copyToSuccess}
          handleToHide={this.handleToHide}
        />
      </>
    );
  }
}

function SelfAceEditor(props) {
  return (
    <AceEditor 
      mode="python"
      theme="dracula"
      readOnly={true}
      showPrintMargin={false}
      value={props.code}
      style={{
        width: '100%',
        height: '100%'
      }}
    />
  )
}

function PythonContent(props) {
  const { 
    isWechat, 
    isShare, 
    isExecute, 
    entryMode, 
    isCopy, 
    command, 
    labelName,
    isGuide,
    data: { head_img, nickname, code_lines, code, result, course_name, course_id },
    handleToSend, 
    copyToSuccess, 
    handleToExecute,
    handleToHide
  } = props;
  return (
    <div className="python-container">
      {
        isGuide && 
        <div className="python-popup" onClick={handleToHide}>
          <div className="python-header">
            <p className="python-wechat__title">请点击右上角分享</p>
            <i className="iconfont"></i>
          </div>
        </div>
      }
      <div className="python-content">
        <div className="python-user">
          <i className="python-user__portrait" style={{backgroundImage: `url(${head_img})`}}></i>
          <h2 className="python-user__id">{nickname}</h2>

          {/* 分享 */}
          {
            (entryMode === 0 && isShare) &&
            <p className="python-user__desc">
              完成了
              <span>【{labelName}】</span>
            </p>
          }
          {
            (entryMode === 1 && isShare) &&
            <p className="python-user__desc">
              在
              <span>【{course_name}】</span>完成了<br />
              {labelName}
            </p>
          }

          {/* 求助 */}
          {
            (entryMode === 0 && !isShare) &&
            <p className="python-user__desc">
              在
              <span>【{labelName}】</span>
              遇到了困难
            </p>
          }
          {
            (entryMode === 1 && !isShare) &&
            <p className="python-user__desc">
              在
              <span>【{course_name}】</span>的<br />
              <span>{labelName}</span>遇到了困难
            </p>
          }
        </div>
        <h4 className="python-code__title">
          {entryMode === 1 && isShare? `这是Ta的第${code_lines}行代码` : '运行结果'}
        </h4>
        <div className="python-code__content">
          <SelfAceEditor code={entryMode === 1 && isShare? code : result} />
        </div>
        <h4 className="python-code__title">
          {entryMode === 1 && isShare? '运行结果' : '代码'}
        </h4>
        <div className="python-code__content">
          {
            entryMode === 1 && isShare
            ? <SelfAceEditor code={isExecute? result : ''} />
            : <SelfAceEditor code={code} />
          }
          {
            (entryMode === 1 && isShare && !isExecute) &&
            <button className="python-button python-button__execute" onClick={handleToExecute}>运行看看</button>
          }
        </div>
      </div>

      {
        (entryMode === 0 && isWechat) &&
        <button className="python-button python-button__study" onClick={handleToSend}>
          {isShare? '分享给好友' : '发给好友求助'}
        </button>
      }

      {
        (entryMode === 0 && !isWechat && !isCopy) &&
        <CopyToClipboard
          text={command}
          onCopy={copyToSuccess}
        >
          <button className="python-button python-button__study">
            {isShare? '分享给好友' : '发给好友求助'}
          </button>
        </CopyToClipboard>
      }

      {
        (entryMode === 0 && !isWechat && isCopy) &&
        <p className="python-button__tip">已复制链接，快去粘贴发给好友吧～</p>
      }

      {
        entryMode === 1 &&
        <Link className="python-button python-button__study" to={`/ml?id=${course_id}`}>我也要学 机器学习</Link>
      }
    </div>
  );
}

export default MLClass;