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

class QueryTradeList 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,
      tradeType: '',
      tradeState: '',
      currencyPair: '',
      showQueryList: true,
    };
    this.beginCount = 1;
    this.queryCount = 10;
    this.jumpTrade = this.jumpTrade.bind(this);
    this.filter = this.filter.bind(this);
    this.backToList = this.backToList.bind(this);
    this.backFunc = this.backFunc.bind(this);
    const bindFnArr = ['getHisList', 'okBtnHandle', 'cancelBtnHandle'];
    bindFnArr.forEach((x) => {
      this[x] = this[x].bind(this);
    });
  }
  componentDidMount() {
    this.getHisList();
  }
  getHisList(isLoad) {
    isLoad && (this.beginCount += 10);
    this.queryData();
  }
  filter() {
    commonTool.gtjaBurialPoint('293012');
    if (this.state.filterFlag === true) {
      this.setState({
        filterFlag: false,
      });
    } else {
      this.setState({
        filterFlag: true,
      });
    }
  }
  okBtnHandle(filterObj) {
    this.setState({
      filterFlag: false,
      tradeType: filterObj.tradeType,
      tradeState: filterObj.tradeState,
      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);
  }
  queryData() {
    const self = this;
    const param = {
      CUSTOMER_ID: Storage.getItem('customerId'),
      TRADE_ACCOUNT: Storage.getItem('tradeAccount'),
      START_DATE: commonTool.getFormateDate().replace(/-/g, '') * 1,
      END_DATE: commonTool.getFormateDate().replace(/-/g, '') * 1,
      CURRENCY_PAIR: this.state.currencyPair,
      TRADE_MODE: this.state.tradeType,
      TRADE_STATE: this.state.tradeState,
      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].queryFxTradeTodayLog;
    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.state.hisList, ...res.datals];
    const upFinish = res.total < this.beginCount + 10;
    this.setState({ hisList, upFinish, isInit: false });
  }
  jumpTrade(tradeLogData) {
    commonTool.gtjaBurialPoint('293011');
    this.setState({
      tradeLogData,
      showQueryList: false,
    });
  }

  backToList() {
    this.setState({
      showQueryList: true,
    });
  }

  backFunc() {
    if (this.state.showQueryList) {
      window.history.back();
    } else {
      this.backToList();
    }
  }

  renderHistoryList() {
    const state = this.state;
    const hasMore = !this.state.upFinish;
    // const showPremise = ({ TRADE_MODE, TRADE_STATE }) => {
    //   return !(TRADE_MODE === '5' && TRADE_STATE === '2'); // 手工录入失败不展示
    // };
    const priceObj = Storage.getItem('firmSpotRateData', true);
    return (
      <IScroll pageStart={0} loadMore={this.getHisList} hasMore={hasMore}>
        <ul className="firm-trade-list">
          {
            state.hisList.map(i => (
              <li key={i.SERIAL_NO} className="trade-content content" onClick={() => { this.jumpTrade({ ...i, AVAIL_POINT: priceObj[i.CURRENCY_PAIR].AVAIL_POINT }); }}>
                <div className="content-header">
                  <div className="currencyPairs">{i.CURRENCY_PAIR}</div>
                  <div
                    className={/1|4|5/.test(i.TRADE_MODE) ? 'fc309fea trade-mode' : 'fcfe8320 trade-mode'}
                  >&emsp;{commonTool.transTradeModeToChinese(i.TRADE_MODE)}
                  </div>
                  <div
                    className="date"
                  >{commonTool.formatDate(i.TRADE_DATE)}&emsp;{commonTool.formatTime(i.TRADE_TIME)}
                  </div>
                </div>
                <div className="content-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="amout">{i.TRADE_AMT}</div>
                  </div>
                  <div className="coin-flag">
                    <div className="label">成交价格&emsp;</div>
                    <div className="flag">{i.TRADE_RATE.toFixed(priceObj[i.CURRENCY_PAIR].AVAIL_POINT)}</div>
                  </div>
                  {/* {
                    i.TRADE_MODE === '4' && i.TRADE_STATE !== '1' && */}
                  <div className="coin-flag">
                    <div className="label">交易状态&emsp;</div>
                    <div className="flag">{commonTool.transTradeStateToChinese(i.TRADE_STATE)}</div>
                  </div>
                  {/* } */}
                </div>
              </li>
            ))
          }
        </ul>
        <div className="loading">{hasMore ? '正在加载数据...' : '已显示全部数据'}</div>
      </IScroll>
    );
  }

  render() {
    return (

      <div>
        {
          this.state.showQueryList ?
            <div>
              <Header backIconFlag={`${!this.state.filterFlag}`} backFunc={this.backFunc}>当日交易</Header>
              <div id="QueryTradeList">
                <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}
                    orderStatusFlag={false}
                    accountTypeFlag={false}
                  /> : ''
                }
                <ModalDiaLog
                  visible={this.state.errorFlag}
                  onClose={() => {
                    this.setState({ errorFlag: false });
                  }}
                  errMsg={this.state.errorMsg}
                />
              </div>
            </div>
            :
            <QueryFirmTradeDetail tradeLogData={this.state.tradeLogData} backToList={this.backToList.bind(this)} />
        }
      </div>
    );
  }
}

export default withRouter(QueryTradeList);
