import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
import IScroll from 'components/Iscroll/Iscroll';
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 './CapitalAccounts.scss';
import CapitalAccountsDetail from './CapitalAccountsDetail';

class CapitalAccounts extends Component {
  constructor(props) {
    super(props);
    const edate = new Date(new Date() - 86400000);
    const sdate = new Date(new Date() - (86400000 * 30));
    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);
    const bindFnArr = ['getHisList', 'okBtnHandle', 'cancelBtnHandle', 'backToList'];
    bindFnArr.forEach((x) => {
      this[x] = this[x].bind(this);
    });
    window.backFunc = () => {
      if (this.state.showQueryList) {
        history.back();
      } else {
        this.backToList();
      }
    };
  }
  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() {
    commonTool.gtjaBurialPoint('293023');
    if (this.state.filterFlag === true) {
      this.setState({
        filterFlag: false,
      }, () => {
        this.props.refreshBackIcon(this.state.filterFlag);
      });
    } else {
      this.setState({
        filterFlag: true,
      }, () => {
        this.props.refreshBackIcon(this.state.filterFlag);
      });
    }
  }
  okBtnHandle(filterObj) {
    this.setState({
      filterFlag: false,
      beginDate: filterObj.beginDate,
      endDate: filterObj.endDate,
      accountType: filterObj.accountType,
      hisList: [],
    }, () => {
      this.props.refreshBackIcon(this.state.filterFlag);
      this.conditionChangeQuery();
    });
  }
  cancelBtnHandle() {
    this.setState({
      filterFlag: false,
    }, () => {
      this.props.refreshBackIcon(this.state.filterFlag);
    });
  }
  conditionChangeQuery() {
    this.beginCount = 1;
    this.queryCount = 10;
    const self = this;
    setTimeout(() => {
      self.queryData();
    }, 0);
  }
  queryData() {
    const self = this;
    const beginDate = self.dateFormat(this.state.beginDate, 'yyyy-mm-dd');
    const endDate = self.dateFormat(this.state.endDate, 'yyyy-mm-dd');
    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: beginDate.replace(/-/g, '') * 1,
      END_DATE: endDate.replace(/-/g, '') * 1,
    };
    const url = ActionConfig[Storage.getItem('customerType')][0].queryAccoutHandleDetailHistory;
    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('293022');
    this.setState({
      data,
      showQueryList: false,
    });
    this.props.hideTitle();
  }
  backToList() {
    this.setState({
      showQueryList: true,
    });
    this.props.showTitle();
  }
  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>
    );
  }
  render() {
    return (
      this.state.showQueryList ?
        <div id="MarginQuery">
          <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}
            /> : ''
          }
          <ModalDiaLog
            visible={this.state.errorFlag}
            onClose={() => {
              this.setState({ errorFlag: false });
            }}
            errMsg={this.state.errorMsg}
          />
        </div> :
        <CapitalAccountsDetail
          data={this.state.data}
          backToList={this.backToList}
        />
    );
  }
}

export default withRouter(CapitalAccounts);
