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

class CapitalAccountsToday 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,
      accountType: '',
      beginDate: new Date(sdate),
      endDate: edate,
      showQueryList: true,
    };
    this.beginCount = 1;
    this.queryCount = 10;
    this.filter = this.filter.bind(this);
    this.jumpDetail = this.jumpDetail.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();
  }
  getHisList(isLoad) {
    isLoad && (this.beginCount += 10);
    this.queryData();
  }
  dateFormat(date, fmt) {
    const o = {
      'm+': date.getMonth() + 1,
      'd+': date.getDate(),
      'h+': date.getHours(),
      'i+': date.getMinutes(),
      's+': date.getSeconds(),
      'q+': Math.floor((date.getMonth() + 3) / 3),
      // 't': date.getMilliseconds(),
    };
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (date.getFullYear().toString()).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() {
    if (this.state.filterFlag === true) {
      this.setState({
        filterFlag: false,
      });
    } else {
      this.setState({
        filterFlag: true,
      });
    }
  }
  okBtnHandle(filterObj) {
    this.setState({
      filterFlag: false,
      accountType: filterObj.accountType,
      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'),
      BOOKING_ID: skipConfig.bookingId,
      ACCOUNT_TYPE: this.state.accountType,
      QUERY_COUNT: this.queryCount,
      START_COUNT: this.beginCount,
      START_DATE: commonTool.getFormateDate().replace(/-/g, '') * 1,
      END_DATE: commonTool.getFormateDate().replace(/-/g, '') * 1,
    };
    const url = ActionConfig[Storage.getItem('customerType')][0].queryAccoutHandleDetailToday;
    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 });
  }
  jumpDetail(data) {
    commonTool.gtjaBurialPoint('293033');
    this.setState({
      data,
      showQueryList: false,
    });
  }
  backToList() {
    this.setState({
      showQueryList: true,
    });
  }
  renderHistoryList() {
    const state = this.state;
    const hasMore = !this.state.upFinish;
    return (
      <IScroll pageStart={0} loadMore={this.getHisList} hasMore={hasMore}>
        <ul className="capitalContent-list">
          {
            state.hisList.map((i, index) => (
              <li key={index} className="capitalContent-info" onClick={this.jumpDetail.bind(this, i)}>
                <div className="capitalItemContent">
                  <div className="width100">
                    <label>{commonTool.transAccountTypeToChinese(i.ACCOUNT_IN_TYPE)}</label>
                    <span>{commonTool.formatFloatAmount(i.AMOUNT, (i.CURRENCY === 'JPY' ? 0 : 2))}</span>
                  </div>
                  <div className="width50">
                    <label>账号货币&emsp;</label>
                    <span>{i.CURRENCY}</span>
                  </div>
                  <div className="top-size width50">
                    <label>{commonTool.formatDate(i.TRADE_DATE)}</label>
                  </div>
                  <Icon type="right" size="md" color="#dddddd" />
                  {/* <label className="leftTopArea">{i.ACCOUNT_TYPE}</label>
                  <div className="capitalItemContent">
                    <div>
                      <label>账号货币&emsp;</label>
                      <span>{i.CURRENCY}</span>
                    </div>
                    <div>
                      <label>金&emsp;&emsp;额&emsp;</label>
                      <span>{i.AMOUNT}</span>
                    </div>
                    <div className="top-size">
                      <label>资金类型&emsp;</label>
                      <span className="dealtype">
                        {i.ACCOUNT_IN_TYPE}
                      </span>
                    </div> */}
                  {/* <div className="top-size">
                      <label>操作类型&emsp;</label>
                      <span>{i.ACCOUNT_TYPE}</span>
                    </div> */}
                </div>
              </li>
            ))
          }
        </ul>
        <div className="loading">{hasMore ? '正在加载数据...' : '已显示全部数据'}</div>
      </IScroll>
    );
  }
  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="MarginQueryToday">
                <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}
                    currencyPair={this.state.currencyPair}
                    productIdFlag={false}
                    tradeTypeFlag={false}
                    tradeStateFlag={false}
                    orderStatusFlag={false}
                    beginDateFlag={false}
                    endDateFlag={false}
                  /> : ''
                }
                <ModalDiaLog
                  visible={this.state.errorFlag}
                  onClose={() => {
                    this.setState({ errorFlag: false });
                  }}
                  errMsg={this.state.errorMsg}
                />
              </div>
            </div> :
            <CapitalAccountsDetail
              data={this.state.data}
              backToList={this.backToList}
            />
        }
      </div>
    );
  }
}

export default withRouter(CapitalAccountsToday);
