import React, { Component } from 'react';
import { connect } from 'react-redux';
import Tool from 'components/Tool/Tool';
import OrderTable from 'components/Tabel/Tabel'
import SelectOption from 'components/selectOption/selectOption';
import commonTool from 'utils/commonTool.js';
import './view.scss'
import { Radio,DatePicker,Table,Slider,Select , Modal } from 'antd';
import locale from 'antd/lib/date-picker/locale/zh_CN';
import moment from 'moment';
import 'moment/locale/zh-cn';
import { requestInterface } from 'utils/dom.js';
import USDImage from 'style/images/USD.png';
import AUDImage from 'style/images/AUD.png';
import CADImage from 'style/images/CAD.png';
import CHFImage from 'style/images/CHF.png';
import CNYImage from 'style/images/CNY.png';
import EURImage from 'style/images/EUR.png';
import GBPImage from 'style/images/GBP.png';
import HKDImage from 'style/images/HKD.png';
import JPYImage from 'style/images/JPY.png';
import KRWImage from 'style/images/KRW.png';
import NZDImage from 'style/images/NZD.png';
moment.locale('zh-cn');
const RadioGroup = Radio.Group;
const Option = Select.Option;
let userInfoAll;
class QueryEntrust extends Component {
  constructor(props) {
    super(props);
    const edate = new Date(new Date() - 86400000);
    const sdate = new Date(new Date() - (86400000 * 30));
    this.state = {
      subTitle:'',           //表单查询子标题
      selectarr:[],          //选择框
      contentArr:[],         //选择内容
      productIdIndex:false,       //货币对
      tradeTypeIndex:false,       //交易类型
      tradeStateIndex:false,      //交易状态
      orderStatusIndex:false,     //挂单状态
      accountTypeIndex:false,     //资金类型
      orderTable:[],         //展示条目
      timeSelectFlag:true,   // 是否展示时间选择
      beginDate:new Date(sdate),               //开始日期
      endDate:edate,                 //结束日期
      currencyPair: '', //货币对选择框值
      tradeType: '',    //交易类型选择框值
      tradeState: '',   //交易状态选择框值
      orderStatus: '',  //挂单状态选择框值
      accountType: '',  //资金类型选择框值
      queryResultNum:'',     //查询结果条数
      queryResultArr:[],     //查询结果数组
      loading:false,          //加载中
      noResult:false,        //无搜索结果
      tableHeight:window.innerHeight-28-29-31-20,//表单高度:title,date,th,margin
      cancelFxOrderIndex:false, //撤单操作
    }
    this.startCount=1;          //起始查询条数
    this.queryCount=200;        //每次查询条数
    
  }
  componentWillReceiveProps (nextProps){
    let urlParams = nextProps.match.params;
    let userInfo = nextProps.userInfo;
    this.transParamsToTitle(urlParams.queryText);
    if(userInfo && nextProps.priceObj){
      this.startCount = 1;
      this.setState({queryResultArr:[]});
      this.transParamsToQuery(urlParams.queryText,nextProps.userInfo,nextProps.priceObj);
      // window.addEventListener('scroll', this.onScrollHasmore.bind(this),true);
    }
  }
  componentWillMount() {
    let urlParams = this.props.match.params;
    this.transParamsToTitle(urlParams.queryText);
    if(this.props.userInfo && this.props.priceObj){
      this.startCount = 1;
      this.setState({queryResultArr:[]});
      this.transParamsToQuery(urlParams.queryText,this.props.userInfo,this.props.priceObj);
    }
    window.addEventListener('scroll', this.onScrollHasmore.bind(this),true);
  }
  componentDidMount() {
  }
  //滚动下拉加载
  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.transParamsToQuery(this.props.match.params.queryText,this.props.userInfo,this.props.priceObj);
      } 
    }
  }
  //根据url所传参数渲染不同内容
  transParamsToTitle(params) {
    let str;
    let arr;
    switch (params) {
      case 'QueryFirmTrade':
        str = '历史交易查询'; //暂时与历史成交相同
        arr = ['交易流水号','交易货币对','交易币种','交易金额','买卖方向','成交价格','交易方式','交付日期','交易时间','交易状态'];
        this.setState({
          subTitle:str,
          orderTable:arr,
          productIdIndex:true,       //货币对
          tradeTypeIndex:true,       //交易类型
          tradeStateIndex:true,      //交易状态
          orderStatusIndex:false,     //挂单状态
          accountTypeIndex:false,     //资金类型
          timeSelectFlag:true,
          cancelFxOrderIndex:false,    //不允许出现撤单操作
        })
        break;
      case 'QueryFirmOrder':
        str = '历史挂单查询';
        arr = ['挂单流水号','交易货币对','交易币种','挂单金额','挂单类型','买卖方向','止盈汇率','委托时间','失效时间','挂单状态'];
        this.setState({
          subTitle:str,
          productIdIndex:true,       //货币对
          tradeTypeIndex:false,       //交易类型
          tradeStateIndex:false,      //交易状态
          orderStatusIndex:true,     //挂单状态
          accountTypeIndex:false,     //资金类型
          orderTable:arr,
          timeSelectFlag:true,
          cancelFxOrderIndex:true,    //允许出现撤单操作
        })
        break;
      case 'CapitalAccounts':
        str = '资金流水查询';
        arr = ['资金账号','资金类型','账号货币','金额','操作时间','清算日期'];
        this.setState({
          subTitle:str,
          orderTable:arr,
          productIdIndex:false,       //货币对
          tradeTypeIndex:false,       //交易类型
          tradeStateIndex:false,      //交易状态
          orderStatusIndex:false,     //挂单状态
          accountTypeIndex:true,     //资金类型
          timeSelectFlag:true,
          cancelFxOrderIndex:false,    //不允许出现撤单操作
        })
        break;
      case 'QueryTradeList':
        str = '当日交易查询';
        arr = ['交易流水号','交易货币对','交易币种','交易金额','买卖方向','成交价格','交易方式','交付日期','交易时间','交易状态'];
        this.setState({
          subTitle:str,
          orderTable:arr,
          productIdIndex:true,       //货币对
          tradeTypeIndex:true,       //交易类型
          tradeStateIndex:true,      //交易状态
          orderStatusIndex:false,     //挂单状态
          accountTypeIndex:false,     //资金类型
          timeSelectFlag:false,
          cancelFxOrderIndex:false,    //不允许出现撤单操作
        })
        break;
      case 'QueryOrderList':
        str = '当日挂单查询';
        arr = ['挂单流水号','交易货币对','交易币种','挂单金额','挂单类型','买卖方向','止盈汇率','委托时间','失效时间','挂单状态'];
        this.setState({
          subTitle:str,
          orderTable:arr,
          productIdIndex:true,       //货币对
          tradeTypeIndex:false,       //交易类型
          tradeStateIndex:false,      //交易状态
          orderStatusIndex:true,     //挂单状态
          accountTypeIndex:false,     //资金类型
          timeSelectFlag:false,
          cancelFxOrderIndex:true,    //允许出现撤单操作
        })
        break;
      case 'CapitalAccountsToday':
        str = '当日资金流水查询';
        arr = ['资金账号','资金类型','账号货币','金额','操作时间','清算日期'];
        this.setState({
          subTitle:str,
          orderTable:arr,
          productIdIndex:false,       //货币对
          tradeTypeIndex:false,       //交易类型
          tradeStateIndex:false,      //交易状态
          orderStatusIndex:false,     //挂单状态
          accountTypeIndex:true,     //资金类型
          timeSelectFlag:false,
          cancelFxOrderIndex:false,    //不允许出现撤单操作
        })
        break;
      case 'BalanceQuery':
        str = '账户余额查询';
        arr = ['账号货币','余额','客户权益','应付金额','可提金额'];
        this.setState({
          subTitle:str,
          orderTable:arr,
          productIdIndex:false,       //货币对
          tradeTypeIndex:false,       //交易类型
          tradeStateIndex:false,      //交易状态
          orderStatusIndex:false,     //挂单状态
          accountTypeIndex:false,     //资金类型
          timeSelectFlag:false,
          cancelFxOrderIndex:false,    //不允许出现撤单操作
        })
        break;
      default:
        str = '历史交易查询';
        arr = ['交易流水号','交易货币对','交易币种','交易金额','买卖方向','成交价格','交易方式','交付日期','交易时间','交易状态','优惠点数'];
        this.setState({
          subTitle:str,
          orderTable:arr,
          productIdIndex:true,       //货币对
          tradeTypeIndex:true,       //交易类型
          tradeStateIndex:true,      //交易状态
          orderStatusIndex:false,     //挂单状态
          accountTypeIndex:false,     //资金类型
          timeSelectFlag:true,
          cancelFxOrderIndex:false,    //不允许出现撤单操作
        })
        break;
    }
  }
  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;
  }
  setImageByCur(cur) {
    let imgUrl;
    switch (cur) {
      case 'USD':
        imgUrl = USDImage;
        break;
      case 'AUD':
        imgUrl = AUDImage;
        break;
      case 'CAD':
        imgUrl = CADImage;
        break;
      case 'CHF':
        imgUrl = CHFImage;
        break;
      case 'CNY':
        imgUrl = CNYImage;
        break;
      case 'EUR':
        imgUrl = EURImage;
        break;
      case 'GBP':
        imgUrl = GBPImage;
        break;
      case 'HKD':
        imgUrl = HKDImage;
        break;
      case 'JPY':
        imgUrl = JPYImage;
        break;
      case 'KRW':
        imgUrl = KRWImage;
        break;
      case 'NZD':
        imgUrl = NZDImage;
        break;
      default:
        imgUrl = '';
        break;
    }
    return imgUrl;
  }
  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:[]});
      let urlParams = this.props.match.params;
      this.transParamsToQuery(urlParams.queryText,this.props.userInfo,this.props.priceObj);
    });
    // this.conditionChangeQuery();
    
  }
  //根据url所传参数搜索不同内容
  transParamsToQuery(params,userInfo,priceObj) {
    switch (params) {
      case 'QueryFirmTrade':
        this.QueryFirmTrade(userInfo,priceObj);
        break;
      case 'QueryFirmOrder':
        this.QueryFirmOrder(userInfo,priceObj);
        break;
      case 'CapitalAccounts':
        this.CapitalAccounts(userInfo,priceObj);
        break;
      case 'QueryTradeList':
        this.QueryTradeList(userInfo,priceObj);
        break;
      case 'QueryOrderList':
        this.QueryOrderList(userInfo,priceObj);
        break;
      case 'CapitalAccountsToday':
        this.CapitalAccountsToday(userInfo,priceObj);
        break;
      case 'BalanceQuery':
        this.BalanceQuery(userInfo,priceObj);
        break;
      default:
        this.QueryFirmTrade(userInfo,priceObj);
        break;
    }
  }
  //历史交易查询
  QueryFirmTrade(userInfo,priceObj){
    //console.log(userInfo,this.state.beginDate)
    const self = this;
    const beginDate = self.dateFormat(this.state.beginDate, 'yyyy-mm-dd');
    const endDate = self.dateFormat(this.state.endDate, 'yyyy-mm-dd');
    var reqInfo = {
      name:'实盘交易历史查询',
      data:{
        inparam:{
          'param.CUSTOMER_ID': '#{{longCustId}}',
          'param.TRADE_ACCOUNT': parseInt(userInfo.longBusiId),
          'param.START_DATE': beginDate.replace(/-/g, '') * 1,
          'param.END_DATE': endDate.replace(/-/g, '') * 1,
          'param.CURRENCY_PAIR': this.state.currencyPair || '',  //货币对
          'param.QUERY_COUNT': this.queryCount,
          'param.START_COUNT': this.startCount,
          'param.TRADE_MODE': this.state.tradeType, //交易类型
          'param.TRADE_STATE': this.state.tradeState, //交易类型
          'param.CHANNEL': '5',
          'param.BOOKING_ID': "ENT00002",
          'terminalinfo': '[terminalinfo]',
        }
      }
    };
    self.setState({loading:true})
    requestInterface(reqInfo,userInfo).then(function(res){
      if(res.RNUM !== '-1'){
        //console.log(res);
        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=[];
                dataItem=[
                          item.SERIAL_NO,       //交易流水号
                          item.CURRENCY_PAIR,   //交易货币对
                          item.TRADE_CCY,        //交易币种
                          item.TRADE_AMT,      //交易金额
                          item.BUY_OR_SELL === 'B' ? '买入' : '卖出', //买卖方向
                          item.TRADE_RATE.toFixed(priceObj[item.CURRENCY_PAIR].AVAIL_POINT),     //成交价格
                          commonTool.transTradeModeToChinese(item.TRADE_MODE), //交易方式
                          commonTool.formatDate(item.VALUE_DATE),//交付日期
                          commonTool.formatDate(item.TRADE_DATE)+' '+commonTool.formatTime(item.TRADE_TIME),//交易时间
                          commonTool.transTradeStateToChinese(item.TRADE_STATE)//交易状态
                        ];
                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
        });
      }  
    });
  }
  //历史挂单查询
  QueryFirmOrder(userInfo,priceObj){
    const self = this;
    const beginDate = self.dateFormat(this.state.beginDate, 'yyyy-mm-dd');
    const endDate = self.dateFormat(this.state.endDate, 'yyyy-mm-dd');
    var reqInfo = {
      name:'实盘委托历史查询',
      data:{
        inparam:{
          'param.CUSTOMER_ID': '#{{longCustId}}',
          'param.TRADE_ACCOUNT': parseInt(userInfo.longBusiId),
          'param.ORDER_STATUS': this.state.orderStatus,                 //挂单状态
          'param.START_DATE': beginDate.replace(/-/g, '') * 1,
          'param.END_DATE': endDate.replace(/-/g, '') * 1,
          'param.CURRENCY_PAIR': this.state.currencyPair || '',  //货币对
          'param.QUERY_COUNT': this.queryCount,
          'param.START_COUNT': this.startCount,
          'param.CHANNEL': '5',
          'param.BOOKING_ID': "ENT00002",
          'terminalinfo': '[terminalinfo]',
        }
      }
    };
    self.setState({loading:true})
    requestInterface(reqInfo,userInfo).then(function(res){
      //console.log(self.props);
      if(res.RNUM !== '-1'){
        //console.log(res);
        let resData=''
        res.list.map((item,index)=>{
          resData+=item.outparam;
        })
        resData = JSON.parse(resData);
        //console.log(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 = ((item.ORDER_TYPE === 'OCO' || item.ORDER_TYPE === 'PT') ? '止盈：' : '止损：') +item.ORDER_RATE1.toFixed(priceObj[item.CURRENCY_PAIR].AVAIL_POINT)+ (item.ORDER_TYPE === 'OCO'?' 止损：'+item.ORDER_RATE2.toFixed(priceObj[item.CURRENCY_PAIR].AVAIL_POINT):'');
                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{
        //接口错误
        self.setState({
          queryResultNum:0,
          queryResultArr:[],
          loading:false,
          noResult:true,
        });
        let resList = res.list[0];
        Modal.warning({
          okText:'知道了',
          title: '接口返回错误',
          content: resList.ERRMSG
        });
      }  
    });
  }
  //资金流水查询
  CapitalAccounts(userInfo,priceObj){
    const self = this;
    const beginDate = self.dateFormat(this.state.beginDate, 'yyyy-mm-dd');
    const endDate = self.dateFormat(this.state.endDate, 'yyyy-mm-dd');
    var reqInfo = {
      name:'资金账号流水历史查询',
      data:{
        inparam:{
          'param.CUSTOMER_ID':'#{{longCustId}}',
          'param.TRADE_ACCOUNT':userInfo.longBusiId,
          "param.BOOKING_ID":"ENT00002",
          'param.ACCOUNT_TYPE': this.state.accountType,  //资金类型
          'param.QUERY_COUNT': this.queryCount,
          'param.START_COUNT': this.startCount,
          'param.START_DATE': beginDate.replace(/-/g, '') * 1,
          'param.END_DATE': endDate.replace(/-/g, '') * 1,
          'terminalinfo': '[terminalinfo]',
        }
      }
    };
    self.setState({loading:true})
    requestInterface(reqInfo,userInfo).then(function(res){
      if(res.RNUM !== '-1'){
        //console.log(res);
        let resData=''
        res.list.map((item,index)=>{
          resData+=item.outparam;
        })
        resData = JSON.parse(resData);
        //console.log(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=[];
                dataItem=[
                        item.TRADE_ACCOUNT,                                           //资金账号
                        commonTool.transAccountTypeToChinese(item.ACCOUNT_IN_TYPE),   //资金类型
                        item.CURRENCY,                                                //币种
                        commonTool.formatFloatAmount(item.AMOUNT, (item.CURRENCY === 'JPY' ? 0 : 2)), //金额
                        commonTool.formatDate(item.TRADE_DATE) +' ' +commonTool.formatTime(item.TRADE_TIME),//操作时间
                        commonTool.formatDate(item.CLEAR_DATE),                                             //清算日期
                      ];
                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{
        //接口错误
         self.setState({
            queryResultNum:resData.data.result.total,
            queryResultArr:[],
            loading:false,
            noResult:true,
          });
        let resList = res.list[0];
        Modal.warning({
          okText:'知道了',
          title: '接口返回错误',
          content: resList.ERRMSG
        });
      }  
    });
  }
  //当日交易查询
  QueryTradeList(userInfo,priceObj){
    var reqInfo = {
      name:'实盘交易当日查询',
      data:{
        inparam:{
          'param.CUSTOMER_ID': '#{{longCustId}}',
          'param.TRADE_ACCOUNT': parseInt(userInfo.longBusiId),
          'param.START_DATE': commonTool.getFormateDate().replace(/-/g, '') * 1,
          'param.END_DATE': commonTool.getFormateDate().replace(/-/g, '') * 1,
          'param.CURRENCY_PAIR': this.state.currencyPair,//货币对
          'param.TRADE_MODE': this.state.tradeType,    //交易类型
          'param.TRADE_STATE': this.state.tradeState,  //交易状态
          'param.QUERY_COUNT': this.queryCount,
          'param.START_COUNT': this.startCount,
          '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 !== '-1'){
        //console.log(res);
        let resData=''
        res.list.map((item,index)=>{
          resData+=item.outparam;
        })
        resData = JSON.parse(resData);
        //console.log(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=[];
                dataItem=[
                          item.SERIAL_NO,       //交易流水号
                          item.CURRENCY_PAIR,   //交易货币对
                          item.TRADE_CCY,        //交易币种
                          item.TRADE_AMT,      //交易金额
                          item.BUY_OR_SELL === 'B' ? '买入' : '卖出', //买卖方向
                          item.TRADE_RATE.toFixed(priceObj[item.CURRENCY_PAIR].AVAIL_POINT),     //成交价格
                          commonTool.transTradeModeToChinese(item.TRADE_MODE), //交易方式
                          commonTool.formatDate(item.VALUE_DATE),//交付日期
                          commonTool.formatDate(item.TRADE_DATE)+' '+commonTool.formatTime(item.TRADE_TIME),//交易时间
                          commonTool.transTradeStateToChinese(item.TRADE_STATE)//交易状态
                        ];
                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{
        //接口错误
        self.setState({
          queryResultNum:0,
          queryResultArr:[],
          loading:false,
          noResult:true,
        });
        let resList = res.list[0];
        Modal.warning({
          okText:'知道了',
          title: '接口返回错误',
          content: resList.ERRMSG
        });
      }  
    });
  }
  //当日挂单查询
  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': this.queryCount,
          'param.START_COUNT': this.startCount,
          "param.CHANNEL":"5",
          "param.BOOKING_ID":"ENT00002",
          'terminalinfo': '[terminalinfo]',
        }
      }
    };
    const self = this;
    //console.log(self.state.priceObj);
    self.setState({loading:true})
    requestInterface(reqInfo,userInfo).then(function(res){
      if(res.RNUM !== '-1'){
        
        let resData=''
        res.list.map((item,index)=>{
          resData+=item.outparam;
        })
        resData = JSON.parse(resData);
        //console.log(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 = (
                //   (item.ORDER_TYPE === 'OCO' || item.ORDER_TYPE === 'PT') ? '止盈：' : '止损：') +item.ORDER_RATE1.toFixed(priceObj[item.CURRENCY_PAIR].AVAIL_POINT)+ (item.ORDER_TYPE === 'OCO'?' 止损：'+item.ORDER_RATE2.toFixed(priceObj[item.CURRENCY_PAIR].AVAIL_POINT):'');
                  
                  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{
        //接口错误
        self.setState({
          queryResultNum:0,
          queryResultArr:[],
          loading:false,
          noResult:true,
        });
        let resList = res.list[0];
        Modal.warning({
          okText:'知道了',
          title: '接口返回错误',
          content: resList.ERRMSG
        });
      }  
    });
  }
  //当日资金流水查询
  CapitalAccountsToday(userInfo,priceObj){
    var reqInfo = {
      name:'资金账号流水当日查询',
      data:{
        inparam:{
          'param.CUSTOMER_ID':'#{{longCustId}}',
          'param.TRADE_ACCOUNT':userInfo.longBusiId,
          "param.BOOKING_ID":"ENT00002",
          'param.ACCOUNT_TYPE': this.state.accountType,  //资金类型
          'param.QUERY_COUNT': this.queryCount,
          'param.START_COUNT': this.startCount,
          'param.START_DATE': commonTool.getFormateDate().replace(/-/g, '') * 1,
          'param.END_DATE': commonTool.getFormateDate().replace(/-/g, '') * 1,
          'terminalinfo': '[terminalinfo]',
        }
      }
    };
    let self = this;
    self.setState({loading:true})
    requestInterface(reqInfo,userInfo).then(function(res){
      if(res.RNUM !== '-1'){
        let resData=''
        res.list.map((item,index)=>{
          resData+=item.outparam;
        })
        resData = JSON.parse(resData);
        //console.log(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=[];
                dataItem=[
                        item.TRADE_ACCOUNT,                                           //资金账号
                        commonTool.transAccountTypeToChinese(item.ACCOUNT_IN_TYPE),   //资金类型
                        item.CURRENCY,                                                //币种
                        commonTool.formatFloatAmount(item.AMOUNT, (item.CURRENCY === 'JPY' ? 0 : 2)), //金额
                        commonTool.formatDate(item.TRADE_DATE) +' ' +commonTool.formatTime(item.TRADE_TIME),//操作时间
                        commonTool.formatDate(item.CLEAR_DATE),                                             //清算日期
                      ];
                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{
        //接口错误
        self.setState({
          queryResultNum:0,
          queryResultArr:[],
          loading:false,
          noResult:true,
        });
        let resList = res.list[0];
        Modal.warning({
          okText:'知道了',
          title: '接口返回错误',
          content: resList.ERRMSG
        });
      }  
    });
  }
  //账户余额查询
  BalanceQuery(userInfo,priceObj){
    var reqInfo = {
      name:'资金账号余额查询',
      data:{
        inparam:{
          'param.CUSTOMER_ID':'#{{longCustId}}',
          'param.TRADE_ACCOUNT':userInfo.longBusiId,
          "param.BOOKING_ID":"ENT00002",
          'terminalinfo': '[terminalinfo]',
        }
      }
    };
    let self = this;
    self.setState({loading:true})
    requestInterface(reqInfo,userInfo).then(function(res){
      if(res.RNUM !== '-1'){
        let resData=''
        res.list.map((item,index)=>{
          resData+=item.outparam;
        })
        resData = JSON.parse(resData);
        //console.log(resData);
        if(resData.success){
          if(resData.data.result.pageSize>0){ //搜索结果多于0
            let queryResultArr=[];
            resData.data.result.datals.map((item,index)=>{
              let dataItem=[];
              dataItem=[
                        {
                          image:self.setImageByCur(item.CURRENCY),
                          text:item.CURRENCY
                        },   //账号货币
                        commonTool.formatFloatAmount(item.BALANCE_AMT * 1, (item.CURRENCY === 'JPY' ? 0 : 2)),   //余额
                        commonTool.formatFloatAmount(item.AVAIL_AMT * 1, (item.CURRENCY === 'JPY' ? 0 : 2)),                                                //客户权益
                        commonTool.formatFloatAmount(item.FREEZE_ACCOUNT * 1, (item.CURRENCY === 'JPY' ? 0 : 2)), //应付金额
                        commonTool.formatFloatAmount(item.EXTRACT_AMT * 1, (item.CURRENCY === 'JPY' ? 0 : 2)),//可提金额
                      ];
              queryResultArr.push(dataItem);
            })
            self.setState({
              queryResultNum:resData.data.result.pageSize,
              queryResultArr:queryResultArr,
              loading:false,
              noResult:false,
            });
          }else{
            self.setState({
              queryResultNum:resData.data.result.pageSize,
              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{
        //接口错误
        self.setState({
          queryResultNum:0,
          queryResultArr:[],
          loading:false,
          noResult:true,
        });
        let resList = res.list[0];
        Modal.warning({
          okText:'知道了',
          title: '接口返回错误',
          content: resList.ERRMSG
        });
      }  
    });
  }
  // 接口测试
  test(userInfo,priceObj){
    //console.log(userInfo);
    var reqInfo = {
      name:'系统参数查询接口',
      data:{
        inparam:{       
          'param.CHANNEL':'5',//px
          'param.ISPRIVATE':'FIRM_FOREX',
          // 'terminalinfo': '[terminalinfo]',
        }        
      }
    };
    let self = this;
    requestInterface(reqInfo,userInfo).then(function(res){
      //console.log(res);
      if(res.RNUM !== '-1'){
        let resData=''
        res.list.map((item,index)=>{
          resData+=item.outparam;
        })
        resData = JSON.parse(resData);
        //console.log(resData);
        if(resData.success){
          //
        }else{
          //数据返回异常
          
        }
      }else{
        //接口错误
        let resList = res.list[0];
        Modal.warning({
          okText:'知道了',
          title: '接口返回错误',
          content: resList.ERRMSG
        });
      }  
    });
  }
  render() {
    let {productIdIndex,tradeTypeIndex,tradeStateIndex,orderStatusIndex,accountTypeIndex,timeSelectFlag} = this.state;
    let {queryResultNum,queryResultArr,loading,noResult} = this.state;
    // console.log(this.state.loading);
    return (
  
      <div className='matket-trade'>
        <div className='order-list'>
          <div className='right-top'>
            <Tool refresh={()=>this.setState({queryResultArr:[]},this.transParamsToQuery(this.props.match.params.queryText,this.props.userInfo,this.props.priceObj))
      } title={this.state.subTitle} userInfo={this.props.userInfo} queryResultNum={queryResultNum} list = {this.state.orderTable} data={queryResultArr}/>
            {this.props.match.params.queryText == 'BalanceQuery'
              ?''
              :<div className='choose'>
                <SelectOption okBtnHandle={this.okBtnHandle.bind(this)} selectIndexArr = {[productIdIndex,tradeTypeIndex,tradeStateIndex,orderStatusIndex,accountTypeIndex,timeSelectFlag]}></SelectOption> 
              </div>
            }    
                
          </div>

            {/*<p className='title'>
                <span className='orders-type-confirm' onClick={(e)=>this.onSelectChange(e)}>撤销</span>         
            </p> 
            {this.props.match.params.queryText == 'BalanceQuery'
              ?''
              :<div className='choose'>
                <SelectOption okBtnHandle={this.okBtnHandle.bind(this)} selectIndexArr = {[productIdIndex,tradeTypeIndex,tradeStateIndex,orderStatusIndex,accountTypeIndex,timeSelectFlag]}></SelectOption> 
              </div>
            } */}      
          <OrderTable userInfo = {this.props.userInfo} list = {this.state.orderTable} data={queryResultArr} loading={loading} noResult={noResult} ref='orderTable' height={this.state.tableHeight} cancelFxOrderIndex={this.state.cancelFxOrderIndex}></OrderTable>       
        </div> 
      </div>
    );
  }
}
const mapStateToProps = (state,ownProps) => {
  const { loginLogout } = state;
  return {
    loginState: loginLogout.loginState,
    userInfo: loginLogout.userInfo,
    priceObj:loginLogout.priceObj,
  };
};
export default connect(mapStateToProps)(QueryEntrust);

