import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
import Header from 'components/Header/Header';
import skipConfig from 'config/config.js';
import ActionConfig from 'config/actionConfig.js';
import ModalDiaLog from 'components/ModalDiaLog/ModalDiaLog';
import errorMsg from 'config/errorConfig.js';
import commonTool from 'utils/commonTool.js';
import { Storage } from 'storage';
import Ajax from 'ajax';
import IScroll from 'components/Iscroll/Iscroll';
import FilterSearch from 'components/FilterSearch/FilterSearch';
import noDataBgImg from 'style/iconImage/noDataBg.png';
import extendDownImg from 'style/iconImage/extendDown.png';
import style from '../firmOrder/QueryFirmOrder.scss';
import QueryFirmOrderDetail from '../firmOrder/QueryFirmOrderDetail';

class QueryOrderList extends Component {
  constructor(props) {
    super(props);
    const edate = new Date();
    const sdate = new Date().setDate(1);
    this.state = {
      upFinish: false,
      isInit: true,
      wrapper: {
        overflow: 'auto',
      },
      hisList: [],
      filterFlag: false,
      beginDate: new Date(sdate),
      endDate: edate,
      currencyPairs: '',
      orderStatus: '',
      showQueryList: true,
    };
    this.beginCount = 1;
    this.queryCount = 10;
    this.needReload = true;
    this.jumpOrder = this.jumpOrder.bind(this);
    this.filter = this.filter.bind(this);
    this.backFunc = this.backFunc.bind(this);
    this.backToList = this.backToList.bind(this);
    const bindFnArr = ['getHisList', 'okBtnHandle', 'cancelBtnHandle'];
    bindFnArr.forEach((x) => {
      this[x] = this[x].bind(this);
    });
  }
  componentDidMount() {
    this.getHisList();
  }
  dateFormat(date, fmt) {
    const o = {
      'm+': date.getMonth() + 1, // 当前的月份，两位数字，不足位补“0”
      'd+': date.getDate(), // 月份中的天数，两位数字，不足位补“0”
      'h+': date.getHours(), // 小时
      'i+': date.getMinutes(), // 分钟数，不足位补“0”
      's+': date.getSeconds(), // 秒
      'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
      't': date.getMilliseconds(), // 毫秒
    };
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (`${date.getFullYear()}`).substr(4 - RegExp.$1.length));
    }
    for (const k in o) {
      if (new RegExp(`(${k})`).test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : ((`00${o[k]}`).substr((`${o[k]}`).length)));
      }
    }
    return fmt;
  }
  filter() {
    commonTool.gtjaBurialPoint('293014');
    if (this.state.filterFlag == true) {
      this.setState({
        filterFlag: false,
      });
    } else {
      this.setState({
        filterFlag: true,
      });
    }
  }
  okBtnHandle(filterObj) {
    this.setState({
      filterFlag: false,
      beginDate: filterObj.beginDate,
      endDate: filterObj.endDate,
      orderStatus: filterObj.orderStatus,
      currencyPair: filterObj.currencyPair,
      hisList: [],
    });
    this.conditionChangeQuery();
  }
  cancelBtnHandle() {
    this.setState({
      filterFlag: false,
    });
  }
  conditionChangeQuery() {
    this.beginCount = 1;
    this.queryCount = 10;
    const self = this;
    setTimeout(() => {
      self.queryData();
    }, 0);
  }
  jumpOrder(orderLogData) {
    commonTool.gtjaBurialPoint('293015');
    this.setState({
      orderLogData,
      showQueryList: false,
    });
  }
  queryData() {
    const self = this;
    const param = {
      CUSTOMER_ID: Storage.getItem('customerId'),
      TRADE_ACCOUNT: Storage.getItem('tradeAccount'),
      ORDER_STATUS: this.state.orderStatus,
      START_DATE: commonTool.getFormateDate().replace(/-/g, '') * 1,
      END_DATE: commonTool.getFormateDate().replace(/-/g, '') * 1,
      CURRENCY_PAIR: this.state.currencyPair || '',
      QUERY_COUNT: this.queryCount,
      START_COUNT: this.beginCount,
      CHANNEL: ActionConfig[Storage.getItem('customerType')][0].channel,
      BOOKING_ID: skipConfig.bookingId,
    };
    const url = ActionConfig[Storage.getItem('customerType')][0].queryFxOrderTodayLog;
    Ajax(url, param).then((res) => {
      if (res.success) {
        self.querySuccess(res.data.result);
      } else {
        this.setState({
          errorFlag: true,
          errorMsg: commonTool.transformErrMsg(res.message),
        });
      }
    });
  }
  querySuccess(res) {
    const hisList = this.needReload ? [...res.datals] : [...this.state.hisList, ...res.datals];
    this.needReload = false;
    const upFinish = res.total < this.beginCount + 10;
    this.setState({ hisList, upFinish, isInit: false });
  }
  getHisList(isLoad) {
    isLoad && (this.beginCount += 10);
    this.queryData();
  }
  colorByStatus(status) {
    let color;
    switch (status) {
      case '1':
        color = 'fc309fea';
        break;
      case '2':
        color = 'fcfe8320';
        break;
      case '3':
        color = 'fc6e87a0';
        break;
      case '4':
        color = 'fc999999';
        break;
      case '5':
        color = 'fceb333b';
        break;
      default:
        color = '';
        break;
    }
    return color;
  }
  renderHistoryList() {
    const state = this.state;
    const hasMore = !this.state.upFinish;
    const priceObj = Storage.getItem('firmSpotRateData', true);
    return (<IScroll pageStart={0} loadMore={this.getHisList} hasMore={hasMore}>
      <ul className="firm-order-list">
        {
          state.hisList.map((i, index) => (
            <li key={i.SERIAL_NO} className="order-content orderContent" onClick={() => { this.jumpOrder({ ...i, AVAIL_POINT: priceObj[i.CURRENCY_PAIR].AVAIL_POINT }); }}>
              <div className="orderContent-header">
                <div className="currencyPairs">{i.CURRENCY_PAIR}</div>
                <div className="date">
                  {commonTool.formatDate(i.ORDER_DATE)}&emsp;
                  <span className={this.colorByStatus(i.ORDER_STATUS)}>
                    {commonTool.transOrdStateToChinese(i.ORDER_STATUS)}
                  </span>
                </div>
              </div>
              <div className="orderContent-info">
                <div className="coin-type">
                  <div className="label">交易币种&emsp;</div>
                  <div className="type">{i.TRADE_CCY}</div>
                </div>
                <div className="sell-or-buy">
                  <div className="label">
                    买卖方向&emsp;
                  </div>
                  <div className="sell-buy">
                    {i.BUY_OR_SELL === 'B' ? '买入' : '卖出'}
                  </div>
                </div>
                <div className="order-amount">
                  <div className="label">挂单金额&emsp;</div>
                  <div className="amount">{i.TRADE_AMT}</div>
                </div>
                <div className="order-amount">
                  {(i.ORDER_TYPE === 'PT' || i.ORDER_TYPE === 'OCO') && <div className="label">止盈汇率&emsp;</div>}
                  {i.ORDER_TYPE === 'SL' && <div className="label">止损汇率&emsp;</div>}
                  <div className="amount">{i.ORDER_RATE1.toFixed(priceObj[i.CURRENCY_PAIR].AVAIL_POINT)}</div>
                </div>
                <div className="coin-flag">
                  <div className="label">挂单类型&emsp;</div>
                  <div className="flag">
                    {commonTool.transOrdTypeToChinese(i.ORDER_TYPE)}
                  </div>
                </div>
                {i.ORDER_TYPE === 'OCO' && <div className="order-amount">
                  <div className="label">止损汇率&emsp;</div>
                  <div className="amount">{i.ORDER_RATE2.toFixed(priceObj[i.CURRENCY_PAIR].AVAIL_POINT)}</div>
                </div>}
              </div>
            </li>
          ))
        }
      </ul>
      <div className="loading">{hasMore ? '正在加载数据...' : '已显示全部数据'}</div>
    </IScroll>);
  }
  backToList(needReload) {
    this.setState({
      showQueryList: true,
    }, () => {
      if (needReload) {
        this.beginCount = 1;
        this.needReload = true;
        this.getHisList();
      }
    });
  }
  backFunc() {
    if (this.state.showQueryList) {
      history.back();
    } else {
      this.backToList();
    }
  }
  render() {
    return (
      <div>
        {
          this.state.showQueryList ?
            <div>
              <Header backIconFlag={`${!this.state.filterFlag}`} backFunc={this.backFunc}>挂单查询</Header>
              <div id="QueryOrderList">
                <div className="right-icon" onClick={this.filter}>筛选</div>
                <div id="wrapper">
                  {
                    this.state.hisList.length > 0 ?
                      this.renderHistoryList()
                      :
                      <div className="default-nodata-content">
                        <img src={noDataBgImg} />
                        <div>暂时没有相关数据...</div>
                      </div>
                  }
                </div>
                {this.state.filterFlag ? <div id="mask" className="wrapperShadow" /> : ''}
                {this.state.filterFlag ?
                  <FilterSearch
                    okBtnHandle={this.okBtnHandle}
                    cancelBtnHandle={this.cancelBtnHandle}
                    beginDate={this.state.beginDate}
                    endDate={this.state.endDate}
                    beginDateFlag={false}
                    endDateFlag={false}
                    tradeTypeFlag={false}
                    tradeStateFlag={false}
                    accountTypeFlag={false}
                  /> : ''
                }
                <ModalDiaLog
                  visible={this.state.errorFlag}
                  onClose={() => {
                    this.setState({ errorFlag: false });
                  }}
                  errMsg={this.state.errorMsg}
                />
              </div>
            </div> :
            <QueryFirmOrderDetail
              orderLogData={this.state.orderLogData}
              backToList={this.backToList}
            />
        }
      </div>
    );
  }
}

export default withRouter(QueryOrderList);
