import React, { Component } from 'react';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import productConfig from 'config/productConfig.js';
import commonTool from 'utils/commonTool.js';
import { Storage } from 'storage';
import PriceFormat from 'components/PriceFormat/PriceFormat';
import verToHorImg from 'style/iconImage/vertToHor.png';
import priceUpImg from 'style/iconImage/priceUp.png';
import priceDownImg from 'style/iconImage/priceDown.png';
import { Button, Icon, ActionSheet } from 'antd-mobile';
import Kchart from './Kchart/Kchart';
import style from './view.scss';
import { nativeLogin } from 'store/loginLogoutAction';

const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
let wrapProps;
if (isIPhone) {
  wrapProps = {
    onTouchStart: e => e.preventDefault(),
  };
}

class QuotationChart extends Component {
  constructor(props) {
    super(props);
    const objectId = this.props.pid.replace('|', '/');
    this.state = {
      priceObject: this.props.priceObject,
      productIdWithoutSlash: this.props.pid,
      objectId,
      selectedInstrument: this.props.selectedInstrument,
    };
    this.goBack = this.goBack.bind(this);
    this.vertToHor = this.vertToHor.bind(this);
    this.goToOrder = this.goToOrder.bind(this);
    this.handleProductId = this.handleProductId.bind(this);
    this.showProductIdOption = this.showProductIdOption.bind(this);
    window.backFunc = () => {
      this.goBack();
    };
  }
  goBack() {
    const pageId = sessionStorage.getItem('forexPageId');
    if (pageId !== 'quotationChart') {
      window.history.back();
    } else {
      window.location.href = 'gtjanormal://goback';
    }
  }
  vertToHor() {
    commonTool.gtjaBurialPoint('138011');
    window.location.href = 'gtjayyz://jumpfunc?funid=30046&pageId=horizontalChart';
  }
  goToTrade(direct) {
    commonTool.gtjaBurialPoint('138002');
    if (this.props.loginState === 'logined') {
      const path = {
        pathname: `/FirmTradeIndex/${this.state.productIdWithoutSlash}`,
        search: direct,
      };
      this.props.history.push(path);
    } else {
      const { dispatch } = this.props;
      dispatch(nativeLogin());
    }
  }
  goToOrder() {
    commonTool.gtjaBurialPoint('138007');
    if (this.props.loginState === 'logined') {
      const path = {
        pathname: `/FirmOrderIndex/${this.state.productIdWithoutSlash}`,
      };
      this.props.history.push(path);
    } else {
      const { dispatch } = this.props;
      dispatch(nativeLogin());
    }
  }
  showProductIdOption() {
    const englishButtons = Object.keys(this.props.priceObject);
    const chineseButtons = [];
    let BUTTONS = englishButtons;
    if (Storage.getItem('languageType') !== '1') {
      for (let index = 0; index < englishButtons.length; index++) {
        chineseButtons[index] = productConfig[englishButtons[index]];
      }
      chineseButtons.push('取消');
      BUTTONS = chineseButtons;
    }
    englishButtons.push('取消');
    ActionSheet.showActionSheetWithOptions({
      options: BUTTONS,
      cancelButtonIndex: BUTTONS.length - 1,
      destructiveButtonIndex: BUTTONS.length - 2,
      title: '请选择',
      maskClosable: true,
      'data-seed': 'logId',
      wrapProps,
    }, (buttonIndex) => {
      BUTTONS[buttonIndex] != '取消' && BUTTONS[buttonIndex] != '删除' && this.setState({
        productIdWithoutSlash: englishButtons[buttonIndex].replace('/', '|'),
        objectId: englishButtons[buttonIndex],
      });
    });
  }
  handleProductId(e) {
    commonTool.gtjaBurialPoint('138012');
    e.preventDefault();
    this.setState({
      productIdWithoutSlash: e.target.value.replace('/', '|'),
      objectId: e.target.value,
    });
    window.location.hash = `#/QuotationChart/firm/${e.target.value.replace('/', '|')}`;
  }
  render() {
    const objectId = this.state.objectId;
    const currentProduct = [this.props.priceObject[objectId]];
    return (
      !currentProduct[0] ?
        <div /> :
        <div id="QuotationChart">
          <div className="chart-header">
            <Icon type="left" size="lg" color="#fff" onClick={this.goBack} />
            <div className="choose-pair">
              <div className="display-pair">
                <div className="chineseName">
                  {commonTool.formateLanguage(this.state.objectId)}
                </div>
                <div className="englishName">
                  {this.state.objectId}
                </div>

              </div>
              <select value={this.state.objectId} className="select-product" onChange={this.handleProductId}>
                {
                  Object.keys(this.props.priceObject).map(i => (
                    <option key={i} value={i}>{i}</option>
                  ))
                }
              </select>
            </div>
            <img onClick={this.vertToHor} className="vert-to-hor" src={verToHorImg} />
          </div>
          <div className="quote-box" style={{ background: '#ffffff', paddingTop: '10px' }}>
            <ul id="PriceList" className="price-list">
              <li>
                <div className="coin-cp">
                  <span className="icon">
                    {currentProduct[0].POINT * 1 >= 0 ? <img src={priceUpImg} /> : <img src={priceDownImg} />}
                  </span>
                  <span className="rise-and-fall-point">{currentProduct[0].POINT}</span>
                  <span className="rise-and-fall-rate">{currentProduct[0].PREC}%</span>
                </div>
                <div className={commonTool.priceColorByStatus(currentProduct[0], 'sell')}>
                  <PriceFormat price={currentProduct[0].OFFER_RATE.toFixed(currentProduct[0].AVAIL_POINT)} />
                </div>
                <div className={commonTool.priceColorByStatus(currentProduct[0], 'buy')}>
                  <PriceFormat price={currentProduct[0].ASK_RATE.toFixed(currentProduct[0].AVAIL_POINT)} />
                </div>
              </li>
            </ul>
            <div className="line-box">
              <span className="left" />
              <span className="right" />
            </div>
            <div className="price-content">
              <div>
                <span className="left-span-item">{commonTool.formatTime(currentProduct[0].PRICE_TIME)}</span>
                <span className="left-span-item">{commonTool.formatDate(currentProduct[0].PRICE_DATE)}</span>
              </div>
              <div>
                <span>今开</span>
                <span className="price-color">{currentProduct[0].OPEN_RATE}</span>
              </div>
              <div>
                <span>最高</span>
                <span className="price-color">{currentProduct[0].MAX_RATE}</span>
              </div>
              <div>
                <span>最低</span>
                <span className="price-color">{currentProduct[0].MIN_RATE}</span>
              </div>
            </div>
          </div>
          <Kchart
            id={this.state.objectId}
            name={commonTool.formateLanguage(this.state.objectId)}
            quote={currentProduct[0]}
            show
          />
          <div className="btn-box">
            <Button type="primary" inline activeClassName="default-btn-active"
                    className="default-button-inline bceb333b" onClick={this.goToTrade.bind(this, 'buy')}>买</Button>
            <Button type="primary" inline activeClassName="default-btn-active"
                    className="default-button-inline bc309fea" onClick={this.goToTrade.bind(this, 'sell')}>卖</Button>
            <Button type="primary" inline activeClassName="default-btn-active"
                    className="default-button-inline bcff8420" onClick={this.goToOrder}>挂单</Button>
          </div>
        </div>
    );
  }
}

const mapStateToProps = (state, ownProps) => {
  console.log(state);
  console.log(ownProps);
  const { loginLogout } = state;
  const { loginState } = loginLogout;
  const instrumentStr = `${ownProps.match.params.instrument}Quotation`;
  const chartQuotation = state[instrumentStr];
  const selectedInstrument = ownProps.match.params.instrument;
  const pid = ownProps.match.params.pid;
  const {
    items: quotation,
    priceObject,
  } = chartQuotation[selectedInstrument] || {
    items: [],
    priceObject: {},
  };
  return {
    selectedInstrument,
    quotation,
    priceObject,
    pid,
    loginState,
  };
};

export default withRouter(connect(mapStateToProps)(QuotationChart));

