import React, { Component } from 'react';
// import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import OrderTabel from 'components/Tabel/Tabel';
import Tool from 'components/Tool/Tool';
import PriceFormat from 'components/PriceFormat/PriceFormat';
// import { Storage } from 'storage';
import commonTool from 'utils/commonTool.js';
import store from '../../store'
import './view.scss'
import {getCurrencyList} from './../../store/loginLogoutAction.js'
import { Radio,DatePicker,Select,message,Modal   } from 'antd';//,Button
const RadioGroup = Radio.Group;
const Option = Select.Option

import moment from 'moment';
import 'moment/locale/zh-cn';
moment.locale('zh-cn');
import locale from 'antd/lib/date-picker/locale/zh_CN';
// import skipConfig from 'config/config.js';
import { requestInterface } from 'utils/dom.js';
import SelectOption from 'components/selectOption/selectOption';

let currencyList =  null;
let tradeAccountList = [];
const QUERY_FAILD = '查询失败';

class View extends Component {
  constructor(props) {
    super(props);
    this.state = {
      currencyIndex:0,
      code1:'',
      code2:'',
      direct:'buy', //买卖方向
      currency:'',//交易币种
      account:'',//交易金额
      budgetAccount: 0,//余额变化值
      pip: 10,//容忍点
      expiryDate:new Date(Date.now()),//失效日期
      orderMode:'PT',//挂单方式
      orderRate1: 1,//止盈汇率
      orderRate2: 1,//止损汇率
      commonStep:1,//有效小数位，步长 
      
      type:'0',//类型
      //搜索查询
      productIdIndex:true,       //货币对标识
      tradeTypeIndex:true,       //交易类型标识
      tradeStateIndex:true,      //交易状态标识
      orderStatusIndex:false,     //挂单状态标识
      accountTypeIndex:false,     //资金类型标识
      timeSelectFlag:false,   // 是否展示时间选择标识
      queryResultNum:'',     //查询结果条数
      queryResultArr:[],     //查询结果数组
      loading:false,          //加载中
      noResult:false,        //无搜索结果
      beginDate:'',               //开始日期
      endDate:'',                 //结束日期
      currencyPair: '', //货币对选择框值
      tradeType: '',    //交易类型选择框值
      tradeState: '',   //交易状态选择框值
      orderStatus: '',  //挂单状态选择框值
      accountType: '',  //资金类型选择框值
      tableHeight:window.innerHeight-28-29-31-20,//表单高度:title,date,th,margin
    };
    this.startCount=1;          //起始查询条数
    this.queryCount=200;        //每次查询条数

    this.teReg1 = /^(([1-9]\d*)|0)(\.\d{0,2}?)?$/;
    this.teReg2 = /^(([1-9]\d*)|0)?$/; //对日金额限制
    this.orderTable = ['挂单流水号','交易货币对','交易币种','挂单金额','挂单类型','买卖方向','止盈汇率','委托时间','失效时间','挂单状态'];
  }

  componentWillReceiveProps(nextProps){
    var ths = this;
    let userInfo = nextProps.userInfo;
    // console.log(nextProps)
    if(userInfo && nextProps.priceObj){
      this.getDtate(userInfo);

      currencyList = Object.values(store.getState().loginLogout.priceObj)//Object.values(nextProps.priceObj);
      console.log(currencyList)
      this.setState({
        code1:currencyList[0].CURRENCY_PAIR.split('/')[0],
        code2:currencyList[0].CURRENCY_PAIR.split('/')[1],
        currency:currencyList[0].CURRENCY_PAIR.split('/')[0],//交易币种
        commonStep:1 / Math.pow(10,currencyList[0].AVAIL_POINT),
      },function(){
        ths.chooseMarginOrderDirectOrMode();
      })
      //查询前，将其实查询条数置为0 ,查询数组置为空
      this.startCount = 1;
      this.setState({queryResultArr:[]});
      this.QueryOrderList(nextProps.userInfo,nextProps.priceObj);
    }
  }
  componentWillMount(){
    store.subscribe(() =>
      console.log(store.getState().loginLogout)
    );
    var ths = this;
    let userInfo = this.props.userInfo;
    if(userInfo && this.props.priceObj){
      this.getDtate(userInfo);
      currencyList = Object.values(store.getState().loginLogout.priceObj)//Object.values(this.props.priceObj);
      this.setState({
        code1:currencyList[0].CURRENCY_PAIR.split('/')[0],
        code2:currencyList[0].CURRENCY_PAIR.split('/')[1],
        currency:currencyList[0].CURRENCY_PAIR.split('/')[0],//交易币种
        commonStep:1 / Math.pow(10,currencyList[0].AVAIL_POINT),
      },function(){
        ths.chooseMarginOrderDirectOrMode();
      })

      //查询前，将其实查询条数置为0 ,查询数组置为空
      this.startCount = 1;
      this.setState({queryResultArr:[]});
      this.QueryOrderList(this.props.userInfo,this.props.priceObj);
    }
    this.getSysparam();
    window.addEventListener('scroll', this.onScrollHasmore.bind(this),true);
  }
  //滚动下拉加载
  onScrollHasmore(event) {
    const clientHeight = event.target.clientHeight;
    const scrollHeight = event.target.scrollHeight;
    const scrollTop = event.target.scrollTop;
    if(clientHeight + scrollTop >= scrollHeight-50){
      if(this.startCount+this.queryCount-1 < this.state.queryResultNum){
        this.setState({
          loading:true,          //加载中
          noResult:false,        //无搜索结果
          tableHeight:window.innerHeight-28-29-31-20-30,//title,date,th,margin,loadingmore
        })
        this.startCount = this.startCount+this.queryCount;
        this.QueryOrderList(this.props.userInfo,this.props.priceObj);
      } 
    }
  }
  getDtate(userInfo){
    let ths = this;
    let accReqInfo = {
      name:'资金账号余额查询',
      data:{
        inparam:{
          'param.CUSTOMER_ID':'#{{longCustId}}',
          'param.TRADE_ACCOUNT':userInfo.longBusiId,
          'terminalinfo': '[terminalinfo]',            
        }        
      }
    };
    requestInterface(accReqInfo,userInfo).then(function(res){
      if(res.RNUM !== '-1'){
        let resList = '' 
        res.list.map((item,index)=>{
          resList+=item.outparam;
        });
        resList = JSON.parse(resList);
        if(resList.success){//数据正常返回          
          tradeAccountList = resList.data.result.datals;
          ths.caculateCharge();
          // console.log('success',resList)
        }else{//数据返回异常         
          console.log('接口返回错误',commonTool.transformErrMsg(resList.message));
        }
      }else{//接口错误       
        let resList = res.list[0];
        console.log('接口返回错误',resList.ERRMSG)
      }
    });
  }
  getSysparam(){
    let ths = this;
    let accReqInfo = {
      name:'系统参数查询接口',
      data:{
        inparam:{
          'param.CHANNEL':'5',//pc
          'param.ISPRIVATE':'FIRM_FOREX'
        }
      }
    };
    requestInterface(accReqInfo,{}).then(function(res){
      if(res.RNUM !== '-1'){
        let resList = '' 
        res.list.map((item,index)=>{
          resList+=item.outparam;
        });
        resList = JSON.parse(resList);
        if(resList.success){//数据正常返回          
          const staticParams = {
            orderExpireDate: 0,
            productParams: {},
          };
            const data = resList.data.result;
            data.productParamList.datals.forEach(({ OBJECTID, MAXPIP, DEFAULTPIP }) => {
              staticParams.productParams[OBJECTID] = {
                MAXPIP,
                DEFAULTPIP,
              };
            });
            staticParams.orderExpireDate = Number(data.intrumentSysParamList.datals.filter(i => i.NAME === 'orderExpireDate')[0].VALUE);
            ths.staticParams = staticParams;
            // console.log(staticParams,'000000')
        }else{//数据返回异常
          console.log('接口返回错误',commonTool.transformErrMsg(resList.message));
        }
      }else{//接口错误       
        let resList = res.list[0];
        console.log('接口返回错误',resList.ERRMSG)
      }
    });   
  }
  disabledDate(current) {
    //只能选中从今天起4天内的日期
    // var d = new Date(),选本周到周五
    // dd = d.getDay(),
    // friday = new Date((5 - dd)*(3600*24*1000)+d.getTime());
    // return current > moment(friday)||current< moment().subtract(1,'days');
    return current > moment().add(2,'days')||current< moment().subtract(1,'days');
  }
  //改变交易方向
  handleDirect(e){
    this.setState({
      direct:e.target.value,
    },()=>{
      this.caculateCharge();
      this.chooseMarginOrderDirectOrMode();
    })
  }
  getCurrency() {
    let cur;
    if (this.state.direct === 'buy') {
      if (this.state.currency === this.state.code1) {
        cur = this.state.code2;
      } else {
        cur = this.state.code1;
      }
    } else {
      cur = this.state.currency;
    }
    return cur;
  }
  caculateCharge() {
    const param = this.state;
    const curPriceObj = currencyList?currencyList[param.currencyIndex]:0//this.props.priceObject[param.name];
    let result;
    if (param.currency === param.code1) {
      if (param.direct === 'buy') { // 买第一货币
        result = -param.account * curPriceObj.ASK_RATE;
        this.referenceRate = curPriceObj.ASK_RATE;
      } else { // 卖第一货币
        result = param.account * curPriceObj.OFFER_RATE;
        this.referenceRate = curPriceObj.OFFER_RATE;
      }
    } else if (param.direct === 'buy') { // 买第二货币
      result = -param.account / curPriceObj.OFFER_RATE;
      this.referenceRate = curPriceObj.OFFER_RATE;
    } else { // 卖第二货币
      result = param.account / curPriceObj.ASK_RATE;
      this.referenceRate = curPriceObj.ASK_RATE;
    }
    this.setState({
      budgetAccount: result,
    });
    this.tradeAccountBalance();
  }
  //余额
  tradeAccountBalance() {
    //let tradeAccountList = Storage.getItem('tradeAccountList', true);
    let currencyAccount = {
      AVAIL_AMT: QUERY_FAILD,
    };
    tradeAccountList && tradeAccountList.map((i, index) => {
      if (i.CURRENCY === this.getCurrency()) {
        currencyAccount = i;
      }
    });
    this.setState({
      tradeAccountBalance: currencyAccount.AVAIL_AMT,
    });
  }
  //选择货币对
  changeCurrencyChecked(value,option){
    this.setState({
      currencyIndex:value,
      currency:option.props.u0,
      code1:option.props.u0,
      code2:option.props.u1,  
      direct:'buy',
      account:'',   
      expiryDate:new Date(Date.now())
    },function(){
      this.chooseMarginOrderDirectOrMode();
      this.tradeAccountBalance();
      this.caculateCharge()

    })
  }
  //交易币种
  handleCurrency(e){
    this.setState({
      currency:e.target.value,
      // uncurrency:e.target.unval,
      account: '',
    },function(){
      this.caculateCharge();
      this.chooseMarginOrderDirectOrMode();
    })
  }
  //交易金额
  handleAccount(e) {
    var inAmount = e.target.value
    e.target.value = inAmount.replace('\\.(\\d?)\\.+', '$1');
    const reg = this.state.currency!== 'JPY' ? this.teReg1 : this.teReg2;
    console.log(reg)
    if (/^0[1-9]$/.test(inAmount)) {
      inAmount = Number(inAmount);
    }
    if (inAmount && !reg.test(inAmount)) {
      if (inAmount === '.') {
        inAmount = '0.';
      } else {
        inAmount = this.state.account;
      }
    }
    this.setState({account:inAmount});
  }
  //挂单汇率
  changeRate(type,e){
    var AVAIL_POINT = currencyList[this.state.currencyIndex].AVAIL_POINT;
    if(type == 'input'){
      var num = e.target.value;
      console.log(AVAIL_POINT)
      e.target.value = num.replace('\\.(\\d?)\\.+', '$1');
      var re = `^(([1-9]\\d{0,3})|0)(\\.\\d{0,${AVAIL_POINT}}?)?$`; 
      re = new RegExp(re)
      if(re.test(num)==true||num == ''){
      }else{
        num = this.state.orderRate1;
      }
      e.target.value = num;
      this.setState({orderRate1:num})
    }else{
      this.setState((prevState, props)=>{
        var num = prevState.orderRate1;
        if(type == 'reduce'){
          num<=0?num=0: num=num*Math.pow(10,AVAIL_POINT)-1
        }else if(type == 'add'){
          num = num*Math.pow(10,AVAIL_POINT)+1;
        }
        return {orderRate1:(num/Math.pow(10,AVAIL_POINT)).toFixed(AVAIL_POINT)}
      })
    }
  }
  changeRate1(type,e){
    var AVAIL_POINT = currencyList[this.state.currencyIndex].AVAIL_POINT;
    if(type == 'input'){
      var num = e.target.value;      
      e.target.value = num.replace('\\.(\\d?)\\.+', '$1');
      var re = `^(([1-9]\\d{0,3})|0)(\\.\\d{0,${AVAIL_POINT}}?)?$`; 
      re = new RegExp(re)
      if(re.test(num)==true||num == ''){
      }else{
        num = this.state.orderRate2;
      }
      e.target.value = num;
      this.setState({orderRate2:num})
    }else{
      this.setState((prevState, props)=>{
        var num = prevState.orderRate2;
        if(type == 'reduce'){
          num<=0?num=0: num=num*Math.pow(10,AVAIL_POINT)-1
        }else if(type == 'add'){
          num = num*Math.pow(10,AVAIL_POINT)+1;
        }
        return {orderRate2:(num/Math.pow(10,AVAIL_POINT)).toFixed(AVAIL_POINT)}
      })
    }
  }
  //挂单方式
  handleOrderMode(value){
    this.setState({ orderMode: value }
     , this.chooseMarginOrderDirectOrMode
      );
  }
  //页面初始化
  chooseMarginOrderDirectOrMode() {
    console.log('初始化')
    let currencyIndex = this.state.currencyIndex;
    const buyDirect = this.state.direct;
    const buy = buyDirect === 'buy';
    const fixed = currencyList?currencyList[currencyIndex].AVAIL_POINT:0//this.props.priceObject[this.state.name].AVAIL_POINT;
    const quote = {
      ASK_RATE:currencyList?currencyList[currencyIndex].ASK_RATE:0,
      OFFER_RATE:currencyList?currencyList[currencyIndex].OFFER_RATE:0
    };//报价
    // const quote = this.props.priceObject[this.state.name];
    const offsetRate = 10;
    const offsetRateMore = offsetRate + 1;
    const fixedPrecent = Math.pow(10, fixed);
    const fixedMore = fixed;
    let defaultRate = '';
    let defaultRate2 = '';
    let accRate;
    switch (this.state.orderMode) {
      case 'PT':// 止盈
        this.refs.mgsRadioCon1.style.display = 'flex';
        this.refs.mgsRadioCon2.style.display = 'none';
        if (buy && (this.state.currency === this.state.code1)) {
          accRate = quote.ASK_RATE;
          defaultRate = commonTool.accSub(accRate, offsetRateMore / fixedPrecent);
        }
        if (buy && (this.state.currency === this.state.code2)) {
          accRate = quote.OFFER_RATE;
          defaultRate = commonTool.accAdd(accRate, offsetRateMore / fixedPrecent);
        }
        if ((!buy) && (this.state.currency === this.state.code1)) {
          accRate = quote.OFFER_RATE;
          defaultRate = commonTool.accAdd(accRate, offsetRateMore / fixedPrecent);
        }
        if ((!buy) && (this.state.currency === this.state.code2)) {
          accRate = quote.ASK_RATE;
          defaultRate = commonTool.accSub(accRate, offsetRateMore / fixedPrecent);
        }
        this.setState({ orderRate1: commonTool.roundNumber(defaultRate, fixedMore) });
        break;
      case 'SL':// 止损
        this.refs.mgsRadioCon1.style.display = 'flex';
        this.refs.mgsRadioCon2.style.display = 'none';
        if (buy && (this.state.currency === this.state.code1)) {
          accRate = quote.ASK_RATE;
          defaultRate = commonTool.accAdd(accRate, offsetRateMore / fixedPrecent);
        }
        if (buy && (this.state.currency === this.state.code2)) {
          accRate = quote.OFFER_RATE;
          defaultRate = commonTool.accSub(accRate, offsetRateMore / fixedPrecent);
        }
        if ((!buy) && (this.state.currency === this.state.code1)) {
          accRate = quote.OFFER_RATE;
          defaultRate = commonTool.accSub(accRate, offsetRateMore / fixedPrecent);
        }
        if ((!buy) && (this.state.currency === this.state.code2)) {
          accRate = quote.ASK_RATE;
          defaultRate = commonTool.accAdd(accRate, offsetRateMore / fixedPrecent);
        }
        this.setState({ orderRate1: commonTool.roundNumber(defaultRate, fixedMore) });
        break;
      case 'OCO':// 二选一
        this.refs.mgsRadioCon1.style.display = 'flex';
        this.refs.mgsRadioCon2.style.display = 'flex';
        if (buy && (this.state.currency === this.state.code1)) {
          accRate = quote.ASK_RATE;
          defaultRate = commonTool.accSub(accRate, offsetRateMore / fixedPrecent);
          defaultRate2 = commonTool.accAdd(accRate, offsetRateMore / fixedPrecent);
        }
        if (buy && (this.state.currency === this.state.code2)) {
          accRate = quote.OFFER_RATE;
          defaultRate = commonTool.accAdd(accRate, offsetRateMore / fixedPrecent);
          defaultRate2 = commonTool.accSub(accRate, offsetRateMore / fixedPrecent);
        }
        if ((!buy) && (this.state.currency === this.state.code1)) {
          accRate = quote.OFFER_RATE;
          defaultRate = commonTool.accAdd(accRate, offsetRateMore / fixedPrecent);
          defaultRate2 = commonTool.accSub(accRate, offsetRateMore / fixedPrecent);
        }
        if ((!buy) && (this.state.currency === this.state.code2)) {
          accRate = quote.ASK_RATE;
          defaultRate = commonTool.accSub(accRate, offsetRateMore / fixedPrecent);
          defaultRate2 = commonTool.accAdd(accRate, offsetRateMore / fixedPrecent);
        }
        this.setState({
          orderRate1: commonTool.roundNumber(defaultRate, fixedMore),
          orderRate2: commonTool.roundNumber(defaultRate2, fixedMore),
        });
        break;
      default:
        break;
    }
  }
  //失效日期
  changeExpiryDate(date,str){
    console.log(str)
    this.setState({
      expiryDate:str
    })
  }
  //提交订单
  doFirmOrder(event) {
    var ths = this;
    var param = this.state;
    event.preventDefault();
    if (currencyList[param.currencyIndex].PRICE_STATUS === 'N') {
      message.info('您选择的产品不在交易状态!', 1);
      return false;
    }
    if (param.account === '0' || param.account === '') {
      message.info('交易金额不能为空！', 1);
      return false;
    }
    if (param.tradeAccountBalance === QUERY_FAILD) {
      message.info('查询可用余额失败，无法发起交易！', 1);
      return false;
    }
    const preAmount = (param.currency === param.code1 ? param.code2 : param.code1);
    if (preAmount === this.getCurrency()) {
      if (Math.abs(param.budgetAccount * 1) > param.tradeAccountBalance * 1) {
        message.info('您的可用余额不足，无法发起交易！', 1);
        return false;
      }
    } else if (param.account * 1 > param.tradeAccountBalance * 1) {
      message.info('您的可用余额不足，无法发起交易！', 1);
      return false;
    }
    // 打开交易加载框
    message.loading('交易中...', 0);
    console.log(ths.props.userInfo)
    let userInfo = ths.props.userInfo;
    
    const reqParam = {
      'param.CURRENCY_PAIR': currencyList[param.currencyIndex].CURRENCY_PAIR,
      'param.BUY_OR_SELL': param.direct === 'buy' ? 'B' : 'S',
      'param.TRADE_CCY': param.currency,
      'param.TRADE_AMT': param.account * 1,
      'param.REFERENCE_RATE': ths.referenceRate,
      'param.TRADE_TYPE':'FIRM_FOREX',
      'param.CUSTOMER_ID':'#{{longCustId}}',
      'param.TRADE_ACCOUNT':userInfo.longBusiId,
      'param.CHANNEL': '5',//--------------------------
      'param.ORDER_TYPE': param.orderMode,
      'param.ORDER_RATE1': param.orderRate1 * 1,
      'param.ORDER_RATE2': param.orderRate2 * 1,
      'param.EXPIRY_DATE': (commonTool.getFormateDate(param.expiryDate).replace('-', '').replace('-', '')) * 1,
      'param.DUE_DATE': (commonTool.getFormateDate().replace('-', '').replace('-', '')) * 1,
      'param.TOLERATE_POINT':ths.staticParams.productParams[currencyList[param.currencyIndex].CURRENCY_PAIR].DEFAULTPIP,
      'param.BOOKING_ID': 'ENT00002',    
      'terminalinfo': '[terminalinfo]',
    };
    var reqInfo = {
      name:'实盘委托',
      data:{
        inparam:reqParam
      }
    }
    requestInterface(reqInfo,userInfo).then(function(res){
      message.destroy();
      if(res.RNUM !== '-1'){
        let resList = [];
        res.list.map((item,index)=>{
          resList+=item.outparam;
        })
        resList = JSON.parse(resList);
        if(resList.success){
          //数据正常返回
          Modal.success({
            title:'委托成功',
            okText:'确定',
            closable:true,
            content: ths.alertOrderMsg(resList.data.result),
            onOk() {window.location.reload()},
          });         
        }else{
          //数据返回异常
          Modal.warning({
            okText:'确定',
            title: '接口返回错误',
            content: commonTool.transformErrMsg(resList.message)
          });
        }
      }else{
        //接口错误
        let resList = res.list[0];
        Modal.warning({
          okText:'知道了',
          title: '接口返回错误',
          content: resList.ERRMSG
        });
      }
    });
  }
  //提交返回结果
  alertOrderMsg(obj) {
    return (
      <div className='order-success'>
        {/* <div>委托成功</div> */}
        <div>
          <label>流水号</label><span>{obj.SERIAL_NO}</span>
        </div>
        <div>
          <label>货币对</label><span>{obj.CURRENCY_PAIR}</span>
          </div>
        <div>
          <label>交易货币</label><span>{this.state.currency}</span>
        </div>
        <div>
          <label>买卖方向</label><span>{obj.BUY_OR_SELL === 'B' ? '买入' : '卖出'}</span>
        </div>
        <div>
          <label>交易金额</label><span>{obj.TRADE_AMT}{this.state.currency}</span>
          </div>
        <div>
          <label>委托类型</label><span>{obj.ORDER_TYPE === 'PT' ? '止盈' : (obj.ORDER_TYPE === 'SL' ? '止损' : '二选一')}</span>
        </div>
        <div>
          <label>{this.state.orderMode !== 'SL' ? '止盈汇率' : '止损汇率'}</label><span>{this.state.orderRate1}</span>
        </div>
        {this.state.orderMode === 'OCO' ?
          <div><label>止损汇率</label><span>{this.state.orderRate2}</span></div> : ''
        }
        {obj.PREF_POINT ? <div><label>优惠点数</label><span>{obj.PREF_POINT}</span></div> : ''}
        <div><label>失效日期</label><span>{commonTool.formatDate(obj.EXPIRY_DATE)}</span></div>
      </div>
    );
  }

  handleAddOrIncre() {
    let info = '';
    if (this.state.budgetAccount < 0) {
      info = '减少';
    } else if (this.state.budgetAccount > 0) {
      info = '增加';
    } else if (this.state.direct === 'buy') {
      info = '减少';
    } else {
      info = '增加';
    }
    return info;
  }
  //当日挂单查询
  QueryOrderList(userInfo,priceObj){
    var reqInfo = {
      name:'实盘委托当日查询',
      data:{
        inparam:{
          'param.CUSTOMER_ID':'#{{longCustId}}',
          'param.TRADE_ACCOUNT':parseInt(userInfo.longBusiId),
          "param.ORDER_STATUS":this.state.orderStatus,    //挂单状态
          "param.START_DATE":commonTool.getFormateDate().replace(/-/g, '') * 1,
          "param.END_DATE":commonTool.getFormateDate().replace(/-/g, '') * 1,
          "param.CURRENCY_PAIR":this.state.currencyPair,       //货币对
          "param.QUERY_COUNT":200,
          "param.START_COUNT":1,
          "param.CHANNEL":"5",
          "param.BOOKING_ID":"ENT00002",
          'terminalinfo': '[terminalinfo]',
        }
      }
    };
    const self = this;
    self.setState({
      loading:true
    })
    requestInterface(reqInfo,userInfo).then(function(res){
      if(res.RNUM >= 0){
        let resData=''
        res.list.map((item,index)=>{
          resData+=item.outparam;
        })
        resData = JSON.parse(resData);
        if(resData.success){
          //数据返回有结果
          if(resData.data.result.total>0){ //搜索总结果多于0
            let queryResultArr=[];
            if(resData.data.result.datals.length>0){//本次搜索结果
              resData.data.result.datals.map((item,index)=>{
                let dataItem=[];
                let rate = [];
                  if(item.ORDER_TYPE === 'PT'){
                    rate.push(
                      <span key={item.ORDER_TIME}>止盈：{item.ORDER_RATE1.toFixed(priceObj[item.CURRENCY_PAIR].AVAIL_POINT)}</span>
                    )
                  }else if(item.ORDER_TYPE === 'SL'){
                    rate.push(
                      <span key={item.ORDER_TIME}>止损：{item.ORDER_RATE1.toFixed(priceObj[item.CURRENCY_PAIR].AVAIL_POINT)}</span>
                    )
                  }else if(item.ORDER_TYPE === 'OCO'){
                    rate.push(
                      <span key={item.ORDER_TIME}>
                        止盈：{item.ORDER_RATE1.toFixed(priceObj[item.CURRENCY_PAIR].AVAIL_POINT)}
                        <br />
                        止损：{item.ORDER_RATE2.toFixed(priceObj[item.CURRENCY_PAIR].AVAIL_POINT)}
                      </span>
                    )
                  }
                dataItem=[
                        item.SERIAL_NO,       //挂单流水号
                        item.CURRENCY_PAIR,   //交易货币对
                        item.TRADE_CCY,        //交易币种
                        item.TRADE_AMT,      //挂单金额
                        item.BUY_OR_SELL === 'B' ? '买入' : '卖出', //买卖方向
                        commonTool.transOrdTypeToChinese(item.ORDER_TYPE),     //挂单类型
                        rate,//止盈汇率
                        commonTool.formatDate(item.ORDER_DATE)+' ' +commonTool.formatTime(item.ORDER_TIME),//委托时间
                        commonTool.formatDate(item.EXPIRY_DATE),//失效时间
                        commonTool.transOrdStateToChinese(item.ORDER_STATUS)//挂单状态
                      ];
                queryResultArr.push(dataItem);
              })
              queryResultArr = self.state.queryResultArr.concat(queryResultArr);
              self.setState({
                queryResultNum:resData.data.result.total,
                queryResultArr:queryResultArr,
                loading:false,
                noResult:false,
              });
            }
          }else{
            self.setState({
              queryResultNum:resData.data.result.total,
              queryResultArr:[],
              loading:false,
              noResult:true,
            });
          }        
        }else{
          //数据返回异常
          //console.log(commonTool.transformErrMsg(resData.message));
          self.setState({
            queryResultNum:0,
            queryResultArr:[],
            loading:false,
            noResult:true,
          });
          Modal.warning({
            okText:'知道了',
            title: '接口返回错误',
            content: commonTool.transformErrMsg(resData.message)
          });
        }
      }else{
        //接口错误
        let resList = res.list[0];
        self.setState({
          queryResultNum:0,
          queryResultArr:[],
          loading:false,
          noResult:true,
        });
        Modal.warning({
          okText:'知道了',
          title: '接口返回错误',
          content: resList.ERRMSG
        });
      }  
    });
  }
  okBtnHandle(filterObj) {
    console.log(filterObj);
    this.setState({
      beginDate:filterObj.beginDate,            //开始日期
      endDate:filterObj.endDate,                //结束日期
      currencyPair: filterObj.currencyPair,     //货币对选择框值
      tradeType: filterObj.tradeTypeValue,           //交易类型选择框值
      tradeState: filterObj.tradeStateValue,         //交易状态选择框值
      orderStatus: filterObj.orderStatusValue,       //挂单状态选择框值
      accountType: filterObj.accountTypeValue,       //资金类型选择框值
    },() => {
      this.startCount = 1;
      this.setState({queryResultArr:[]});
      this.QueryOrderList(this.props.userInfo,this.props.priceObj);
    });
    // this.conditionChangeQuery();
  }
  render() {
    let ths = this;
    let param = ths.state;   
    let currencyIndex = param.currencyIndex
    let notTradeCurrency = param.currency === param.code1 ? param.code2 : param.code1;
    let fixedDec = notTradeCurrency === 'JPY' ? 0 : '';
    let budgetAccount = commonTool.formatFloatAmount(Math.abs(Number(param.budgetAccount)), fixedDec, true);
    let currencyOpt = [];
    let currObjList = [];
    if(currencyList){
      currencyList.map(function(item,index){
        currencyOpt.push(
          <Option key={index} u0={item.CURRENCY_PAIR.split('/')[0]} u1={item.CURRENCY_PAIR.split('/')[1]} value={index}>
            {commonTool.transEngToChin(item.CURRENCY_PAIR.split('/')[0])+'/'+commonTool.transEngToChin(item.CURRENCY_PAIR.split('/')[1])}                          
          </Option>
        )
        currObjList.push(
          <li key={item.CURRENCY_PAIR}>
             <span>{commonTool.transEngToChin(item.CURRENCY_PAIR.split('/')[0])+'/'+commonTool.transEngToChin(item.CURRENCY_PAIR.split('/')[1])}
             {item.CURRENCY_PAIR}
             </span>
            <PriceFormat              
             className={commonTool.priceColorByStatus(item, 'sell')}priceObj={item} price ={item.OFFER_RATE} />
            <PriceFormat className={commonTool.priceColorByStatus(item, 'buy')} priceObj={item} price ={item.ASK_RATE} />
          </li>
        )
      })
    }

    let {queryResultNum,queryResultArr,loading,noResult,productIdIndex,tradeTypeIndex,tradeStateIndex,orderStatusIndex,accountTypeIndex,timeSelectFlag} = this.state;
    return (
      <div className='pendging-order'>
        <aside className='aside'>
          <ul>
            <li className='title'>
              挂单交易
            </li>
            <li>
              <span>货币对</span>
              {
                currencyList?
                <div>
                  <div className='fleft'>
                    <Select size='small' notFoundContent='暂无数据' value={param.currencyIndex} onChange={this.changeCurrencyChecked.bind(this)}>
                      {currencyOpt}
                    </Select>
                    <i>{currencyList[currencyIndex].CURRENCY_PAIR}</i>  
                  </div>                
                  <p className='fright'>
                    <PriceFormat  
                    className={commonTool.priceColorByStatus(currencyList[currencyIndex], 'sell')}
                    priceObj={currencyList[currencyIndex]} price = {currencyList?currencyList[currencyIndex].OFFER_RATE:''}/>
                    {/* 卖出价 买入价 */}
                    <PriceFormat
                    className={commonTool.priceColorByStatus(currencyList[currencyIndex], 'buy')}
                    priceObj={currencyList[currencyIndex]} price = {currencyList?currencyList[currencyIndex].ASK_RATE:''}/>
                  </p>
                </div>  
              :''
              }                                                         
            </li>
            <li>
              <span>买卖方向</span>
              <div>
                <RadioGroup size='small' defaultValue={this.state.direct} onChange={this.handleDirect.bind(this)}>
                  <Radio value={'buy'}>买入</Radio>
                  <Radio value={'sell'}>卖出</Radio>
                </RadioGroup>
              </div>
            </li>
            <li>
              <span>交易币种</span>
              <div>
                {
                  currencyList?
                  <RadioGroup size='small' value={this.state.currency} onChange={this.handleCurrency.bind(this)}>
                    <Radio unval={param.code2} value={param.code1}>{param.code1}</Radio>
                    <Radio unval={param.code1} value={param.code2}>{param.code2}</Radio>
                  </RadioGroup>
                  :''
                }
              </div>
            </li>
            <li>
              <span>交易金额</span>
              <div className='paydate'>
                <input type='number' min="0" placeholder={commonTool.formatFloatAmount(param.tradeAccountBalance * 1)+this.getCurrency()}
                  step="1" value={param.account} onChange={this.handleAccount.bind(this)}
                  onBlur={this.caculateCharge.bind(this)}
                />
                <i>{param.currency === param.code1 ? param.code1 : param.code2}</i>
                
                {/* <p>可用<span> {commonTool.formatFloatAmount(param.tradeAccountBalance * 1)} </span>{this.getCurrency()}</p> */}
              </div>
            </li>
            <li>
              <span>交付日</span>
              <div className='paydate'>
                  <DatePicker locale={locale} disabled value={moment(currencyList?currencyList[currencyIndex].VALUE_DATE+'':new Date())} />
                <p>预计
                  {this.state.currency === this.state.code1 ? this.state.code2 : this.state.code1}
                  余额
                  {this.handleAddOrIncre()}
                  <span>{ budgetAccount}</span>
                </p>
              </div>
            </li>
            <li ref="mgsRadioCon1">
                <span>{param.orderMode !== 'OCO' ? '挂单汇率' : '止盈汇率'}</span>
                <div className='rate'>
                <span onClick={this.changeRate.bind(this,'reduce')}>-</span>
                <input type='number' value={this.state.orderRate1} min="0" max='9999' step={param.commonStep}  onChange={this.changeRate.bind(this,'input')}/>
                <span onClick={this.changeRate.bind(this,'add')}>+</span>
              </div>   
          </li>
          <li style={{display:'none'}} ref="mgsRadioCon2">
            <span>止损汇率</span>
            <div className='rate'>
              <span onClick={this.changeRate1.bind(this,'reduce')}>-</span>
              <input type='number' 
              value={this.state.orderRate2} min="0" max='9999' step={param.commonStep}  onChange={this.changeRate1.bind(this,'input')}/>
              <span onClick={this.changeRate1.bind(this,'add')}>+</span>
            </div>               
          </li>
            <li>
              <span>挂单方式</span>
              <div>
                <Select size='small' defaultValue='PT' value={param.orderMode} onChange={this.handleOrderMode.bind(this)}>
                  <Option value="PT">止盈</Option>
                  <Option value="SL">止损</Option>
                  <Option value='OCO'>二选一</Option>
                </Select>
              </div>
            </li>
            <li>
              <span>失效日期</span>
              <div>
                <DatePicker locale={locale} disabledDate={this.disabledDate.bind(this)} defaultValue={moment(param.expiryDate)} onChange={this.changeExpiryDate.bind(this)} allowClear={false} />
              </div>
            </li>
            <li>
              <span onClick={this.doFirmOrder.bind(this)} className='confirmbtn'>确定</span>
            </li>
          </ul> 
          <ul>
            <li className='title'>
              <span>货币对</span><span>卖出价</span><span>买入价</span>
              <i className='refresh' onClick={()=>{
                store.dispatch(getCurrencyList(ths.props.userInfo))
              }}></i>
            </li>
            {currencyList?currObjList:<p className='nodata'>暂时没有相关数据</p>}
           
          </ul>
        </aside>
        <div className='order-list'>  
          <div className="right-top">
            <Tool title='当日挂单查询' refresh={()=>this.setState({queryResultArr:[]},this.QueryOrderList(this.props.userInfo,this.props.priceObj))} list = {this.orderTable} userInfo={this.props.userInfo} queryResultNum={queryResultNum} data={queryResultArr}/>
            <div className='choose'>
              <SelectOption okBtnHandle={this.okBtnHandle.bind(this)} selectIndexArr = {[productIdIndex,tradeTypeIndex,tradeStateIndex,orderStatusIndex,accountTypeIndex,timeSelectFlag]}></SelectOption> 
            </div>       
          </div>
          <OrderTabel userInfo = {this.props.userInfo} match={ths.props.match} list = {this.orderTable} data={queryResultArr} loading={loading} noResult={noResult} height={this.state.tableHeight} cancelFxOrderIndex={true}></OrderTabel> 
        </div>                 
      </div>
    );
  }
}

const mapStateToProps = (state,ownProps) => {
  // console.log(ownProps)
  const { loginLogout } = state;
  return {
    loginState: loginLogout.loginState,
    userInfo: loginLogout.userInfo,
    priceObj:loginLogout.priceObj,
    list:currencyList,
  };
};
export default connect(mapStateToProps)(View);
