import React, { Component } from 'react';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import { DatePicker, List } from 'antd-mobile';
import ModalDiaLog from 'components/ModalDiaLog/ModalDiaLog';
import extendDownImg from 'style/iconImage/extendDown.png';
import './FilterSearch.scss';

class FilterSearch extends Component {
  constructor(props) {
    super(props);
    this.state = {
      beginDate: this.props.beginDate,
      endDate: this.props.endDate,
      currencyPair: this.props.currencyPair || '',
      tradeType: '',
      tradeState: '',
      orderStatus: '',
      accountType: '',
      modalFlag: false,
      errorStr: '开始日期不能大于结束日期',
    };
    // 筛选组件展示类型，无自定义默认显示
    this.beginDateFlag = (this.props.beginDateFlag === undefined ? true : this.props.beginDateFlag);// 开始日期显示标识
    this.endDateFlag = (this.props.endDateFlag === undefined ? true : this.props.endDateFlag);// 开始日期显示标识
    this.productIdFlag = (this.props.productIdFlag === undefined ? true : this.props.productIdFlag);// 货币对显示标识
    this.tradeTypeFlag = (this.props.tradeTypeFlag === undefined ? true : this.props.tradeTypeFlag);// 交易类型显示标识
    this.tradeStateFlag = (this.props.tradeStateFlag === undefined ? true : this.props.tradeStateFlag);// 交易状态显示标识
    this.orderStatusFlag = (this.props.orderStatusFlag === undefined ? true : this.props.orderStatusFlag);// 挂单状态显示标识
    this.accountTypeFlag = (this.props.accountTypeFlag === undefined ? true : this.props.accountTypeFlag);// 资金类型显示标识
    const bindFnArr = ['okBtnHandle', 'cancelBtnHandle', 'changeBeginDate', 'changeEndDate', 'changeCurrencyPair', 'resetBtnHandle', 'showLog', 'closeLog', 'changeTradeType', 'changeTradeState', 'changeOrderStatus', 'changeAccountType'];
    bindFnArr.forEach((x) => {
      this[x] = this[x].bind(this);
    });
  }

  shouldComponentUpdate(nextProps, nextState) {
    const state = this.state;
    return state.beginDate !== nextState.beginDate || state.endDate !== nextState.endDate || state.currencyPair !== nextState.currencyPair || state.tradeType !== nextState.tradeType || state.tradeState !== nextState.tradeState || state.orderStatus !== nextState.orderStatus || state.accountType !== nextState.accountType || state.modalFlag !== nextState.modalFlag || state.errorStr !== nextState.errorStr;
  }

  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()}`).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;
  }
  checkDate(value, flag) {
    if (flag === 1) {
      let days = this.state.endDate.getTime() - value.getTime();
      days = parseInt(days / (1000 * 60 * 60 * 24), 10);
      if (days > 30) {
        this.setState({
          modalFlag: true,
          errorStr: '查询时间跨度不能超过30天',
        });
        return true;
      }
      const endDate = this.dateFormat(this.state.endDate, 'yyyy-mm-dd').replace(/-/g, '');
      value = this.dateFormat(value, 'yyyy-mm-dd').replace(/-/g, '');
      if (value > endDate) {
        this.setState({
          modalFlag: true,
          errorStr: '开始日期不能大于结束日期',
        });
        return true;
      }
    } else {
      let days = value.getTime() - this.state.beginDate.getTime();
      days = parseInt(days / (1000 * 60 * 60 * 24), 10);
      if (days > 30) {
        this.setState({
          modalFlag: true,
          errorStr: '查询时间跨度不能超过30天',
        });
        return true;
      }
      const beginDate = this.dateFormat(this.state.beginDate, 'yyyy-mm-dd').replace(/-/g, '');
      value = this.dateFormat(value, 'yyyy-mm-dd').replace(/-/g, '');
      if (value < beginDate) {
        this.setState({
          modalFlag: true,
          errorStr: '开始日期不能大于结束日期',
        });
        return true;
      }
    }
  }
  changeBeginDate(value) {
    console.error('子组件开始日期改变');
    this.setState({
      beginDate: value,
    });
  }
  changeEndDate(value) {
    console.error('子组件结束日期改变');
    this.setState({
      endDate: value,
    });
  }
  changeCurrencyPair(e) {
    this.setState({
      currencyPair: e.target.value,
    });
  }
  changeTradeType(e) {
    this.setState({
      tradeType: e.target.value,
    });
  }
  changeTradeState(e) {
    this.setState({
      tradeState: e.target.value,
    });
  }
  changeOrderStatus(e) {
    this.setState({
      orderStatus: e.target.value,
    });
  }
  changeAccountType(e) {
    this.setState({
      accountType: e.target.value,
    });
  }

  resetBtnHandle() {
    const edate = new Date();
    const sdate = new Date().setDate(1);
    const beginDate = new Date(sdate);
    const endDate = edate;
    this.setState({
      beginDate,
      endDate,
      currencyPair: '',
      tradeType: '',
      tradeState: '',
      orderStatus: '',
      accountType: '',
    });
  }
  okBtnHandle() {
    if (this.checkDate(this.state.beginDate, 1)) {
      return false;
    }
    if (this.checkDate(this.state.endDate, 2)) {
      return false;
    }
    const filterObj = {
      beginDate: this.state.beginDate,
      endDate: this.state.endDate,
      currencyPair: this.state.currencyPair,
      tradeType: this.state.tradeType,
      tradeState: this.state.tradeState,
      orderStatus: this.state.orderStatus,
      accountType: this.state.accountType,
    };
    // console.error('beginDate' + beginDate + 'endDate' + endDate + 'currencyPair' + currencyPair);
    this.props.okBtnHandle(filterObj);
  }
  cancelBtnHandle() {
    this.props.cancelBtnHandle();
  }
  convertToDateObject(str) {
    const date = new Date(str);
    return date;
  }
  showLog() {
    this.setState({
      modalFlag: true,
    });
  }
  closeLog() {
    this.setState({
      modalFlag: false,
    });
  }
  render() {
    const yesterday = new Date(new Date() - 86400000);
    return (
      <div className="FilterSearch">
        <ul>
          {this.beginDateFlag && <li>
            <label>开始日期</label>
            <div className="beginDate">
              <DatePicker
                mode="date"
                title="选择开始日期"
                extra="Optional"
                maxDate={yesterday}
                value={this.convertToDateObject(this.state.beginDate)}
                onChange={this.changeBeginDate}
              >
                <List.Item arrow="horizontal" />
              </DatePicker>
            </div>
          </li>}
          {this.endDateFlag && <li>
            <label>结束日期</label>
            <div className="endDate">
              <DatePicker
                mode="date"
                title="选择结束日期"
                extra="Optional"
                maxDate={yesterday}
                value={this.convertToDateObject(this.state.endDate)}
                onChange={this.changeEndDate}
              >
                <List.Item arrow="horizontal" />
              </DatePicker>
            </div>
          </li>}
          {this.productIdFlag && <li>
            <label>货币对</label>
            <select value={this.state.currencyPair} id="currencyPairs" onChange={this.changeCurrencyPair}>
              <option value="">请选择</option>
              {
                this.props.allCode.split(',').map(i => (
                  <option key={i} value={i}>{i}</option>
                ))
              }
            </select>
            <span className="select-down" />
          </li>}
          {this.tradeTypeFlag && <li>
            <label>交易类型</label>
            <select value={this.state.tradeType} onChange={this.changeTradeType}>
              <option value="">请选择</option>
              <option value="1">市价</option>
              <option value="3">挂单</option>
            </select>
            <span className="select-down" />
          </li>}
          {this.tradeStateFlag && <li>
            <label>交易状态</label>
            <select value={this.state.tradeState} onChange={this.changeTradeState}>
              <option value="">请选择</option>
              <option value="1">成功</option>
              <option value="2">失败</option>
              <option value="0">审批中</option>
            </select>
            <span className="select-down" />
                                  </li>}
          {this.orderStatusFlag && <li>
            <label>挂单状态</label>
            <select value={this.state.orderStatus} onChange={this.changeOrderStatus}>
              <option value="">请选择</option>
              <option value="2">已成交</option>
              <option value="1">待成交</option>
              <option value="3">已撤销</option>
              <option value="4">已失效</option>
              <option value="5">交易无效</option>
            </select>
            <span className="select-down" />
          </li>}
          {this.accountTypeFlag && <li>
            <label>资金类型</label>
            <select value={this.state.accountType} onChange={this.changeAccountType}>
              <option value="">请选择</option>
              <option value="1">入金</option>
              <option value="2">出金扣账</option>
              <option value="3">扣账</option>
              <option value="4">入账</option>
              <option value="5">结息</option>
              <option value="6">红冲</option>
              <option value="7">蓝补</option>
              <option value="8">冻结</option>
              <option value="9">冻结取消</option>
              <option value="10">解冻</option>
              <option value="11">解冻取消</option>
              <option value="12">资金禁取</option>
              <option value="13">司法冻结</option>
              <option value="14">司法冻结取消</option>
              <option value="17">司法扣划</option>
            </select>
            <span className="select-down" />
          </li>}
        </ul>
        <div className="buttonArea">
          <div className="reset" onClick={this.resetBtnHandle}>重置</div>
          <div className="okOrCancelBtn">
            <div className="cancelBtn" onClick={this.cancelBtnHandle}>取消</div>
            <div className="okBtn" onClick={this.okBtnHandle}>确认</div>
          </div>
        </div>
        <ModalDiaLog
          visible={this.state.modalFlag}
          onShow={this.showLog}
          onClose={this.closeLog}
          errMsg={this.state.errorStr}
        />
      </div>
    );
  }
}

const mapStateToProps = (state) => {
  const { firmQuotation } = state;
  const { priceObject } = firmQuotation.firm || {
    priceObject: {},
  };
  return {
    allCode: Object
      .keys(priceObject)
      .join(','),
  };
};

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