import React, { Component } from 'react';
import OrderTabel from 'components/Tabel/Tabel';
import PriceFormat from 'components/PriceFormat/PriceFormat';
import Tool from 'components/Tool/Tool';
import { connect } from 'react-redux';
import commonTool from 'utils/commonTool.js';
import './view.scss'
import { Radio,DatePicker,Table,Slider,Select,message,Modal,Button,Icon   } from 'antd';
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 { requestInterface } from 'utils/dom.js';
import SelectOption from 'components/selectOption/selectOption';

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

class MarketTrade extends Component {
  constructor(props) {
    super(props);
    this.state = {
      currencyIndex:0,
      code1:'',
      code2:'',
      direct:'buy', //买卖方向
      currency:'',//交易币种
      account:'',//交易金额
      budgetAccount: 0,
      pip:2,//价格容差点
      maxPip: 10,
      tradeAccountBalance: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){
  let userInfo = nextProps.userInfo;
  if(userInfo && nextProps.priceObj){
    this.getDtate(userInfo);
    currencyList = Object.values(nextProps.priceObj);
    this.setState({
      code1:currencyList[0].CURRENCY_PAIR.split('/')[0],
      code2:currencyList[0].CURRENCY_PAIR.split('/')[1],
      currency:currencyList[0].CURRENCY_PAIR.split('/')[0],//交易币种
    }) 

    this.startCount = 1;
    this.setState({queryResultArr:[]});
    this.QueryTradeList(nextProps.userInfo,nextProps.priceObj);
  }
}
componentWillMount() {
    let userInfo = this.props.userInfo;
    if(userInfo && this.props.priceObj){
      this.getDtate(userInfo);
      currencyList = 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],//交易币种
      })     


      this.startCount = 1;
      this.setState({queryResultArr:[]});
      this.QueryTradeList(this.props.userInfo,this.props.priceObj);
    }
    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){
    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.QueryTradeList(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.tradeAccountBalance();
        console.log('success',resList)
      }else{//数据返回异常
        console.log('接口返回错误',commonTool.transformErrMsg(resList.message));
      }
    }else{//接口错误       
      let resList = res.list[0];
      console.log('接口返回错误',resList.ERRMSG)
    }
  });
  ths.getSysparam();
}
getSysparam(){
  let ths = this;
  let accReqInfo = {
    name:'系统参数查询接口',
    data:{
      inparam:{
        'param.CHANNEL':'5',
        'param.ISPRIVATE':'FIRM_FOREX'
      }
    }
  };
  requestInterface(accReqInfo,{}).then(function(res){
    if(res.RNUM !== '-1'){
      // console.log(res)
      let resList = '' 
      res.list.map((item,index)=>{
        resList+=item.outparam;
      });  
      // console.log(resList);   
      resList = JSON.parse(resList);
      // console.log(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)
    }
  });   
}
changePip(){
  let str = this.state.code1+'/'+this.state.code2;
  this.setState({
    pip:this.staticParams.productParams[str].DEFAULTPIP,
    maxPip:this.staticParams.productParams[str].MAXPIP
  })
}
  changeCurrencyChecked(value,option){
    this.setState({
      currencyIndex:value,
      currency:option.props.u0,
      uncurrency:option.props.u1,
      code1:option.props.u0,
      code2:option.props.u1,  
      direct:'buy',
      account:'',   
      expiryDate:moment(new Date())
    },function(){
      this.tradeAccountBalance();
      this.changePip()
    })
  }
  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;
  }
  handleDirect(e) {
    this.setState({
      direct: e.target.value,
    }, this.caculateCharge);
  }
  handleCurrency(e) {
    this.setState({
      currency:e.target.value,
      uncurrency:e.target.unval,
      account: '',
    }, this.caculateCharge);
  }
  handleAccount(e) {
    var inAmount = e.target.value
    e.target.value = inAmount.replace('\\.(\\d?)\\.+', '$1');
    const reg = this.state.currency!== 'JPY' ? this.teReg1 : this.teReg2;
    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});
  }
  caculateCharge() {
    const param = this.state;
    const curPriceObj = currencyList[param.currencyIndex];//this.props.priceObject[param.objectId];
    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();
  }
  handleSlider(name, value) {
    this.setState({
      pip: value,
    });
  }
  alertTradeMsg(obj) {
    return (
      <div className='order-success'>
        <div><label>流水号</label><span>{obj.SERIAL_NO}</span></div>
        <div><label>货币对</label><span>{obj.CURRENCY_PAIR}</span></div>
        <div><label>交易金额</label><span>{obj.TRADE_AMT}{obj.TRADE_CCY}</span></div>
        <div>
          <label>对手金额</label><span>{obj.RELATE_AMT}{this.state.currency === this.state.code1 ? this.state.code2 : this.state.code1}</span>
        </div>
        <div><label>成交汇率</label><span>{obj.TRADE_RATE}</span></div>
        {obj.PREF_POINT ? <div><label>优惠点数</label><span>{obj.PREF_POINT}</span></div> : ''}
        {obj.BIG_QUEYR_FLAG && obj.BIG_QUEYR_FLAG === '0' && <div className="big-data-info">该交易归类为大额交易,需后台人员进行审核</div>}
      </div>
    );
  }
  doFirmTrade(event) {
    var ths = this;
    console.log(ths.props)
    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);
    let userInfo = this.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.TOLERATE_POINT': param.pip,
      'param.REFERENCE_RATE': this.referenceRate,//---------参考汇率
      'param.TRADE_TYPE': 'FIRM_FOREX',
      'param.ENQUIRY_FLAG':'1',//正常价格
      'param.CUSTOMER_ID':'#{{longCustId}}',
      'param.TRADE_ACCOUNT':userInfo.longBusiId,
      'param.CHANNEL': '5',//pc-------------
      'param.VALUE_DATE':currencyList[param.currencyIndex].VALUE_DATE * 1,//交付日
      'param.BOOKING_ID': 'ENT00002',
      'terminalinfo': '[terminalinfo]',
    };
    var reqInfo = {
      name:'实盘即时交易',
      data:{
        inparam:reqParam
      }
    }
    requestInterface(reqInfo,userInfo).then(function(res){
      message.destroy();
      console.log(res)
      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.alertTradeMsg(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
        });
      }
    });
  }
  tradeAccountBalance() {
    let currencyAccount = {
      AVAIL_AMT: QUERY_FAILD,
    };
    tradeAccountList && tradeAccountList.map((i, index) => {
      if (i.CURRENCY === this.getCurrency()) {
        currencyAccount = i;
      }
    });
    this.setState({
      tradeAccountBalance: currencyAccount.AVAIL_AMT,
    });
  }
  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;
  }
  //当日交易查询
  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': 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=[];
                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
        });
      }  
    });
  }
  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.QueryTradeList(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 = [];
    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>
        )
      })
    }
    let {queryResultNum,queryResultArr,loading,noResult,productIdIndex,tradeTypeIndex,tradeStateIndex,orderStatusIndex,accountTypeIndex,timeSelectFlag} = this.state;
    return (
      <div className='matket-trade'>
        <aside className='aside'>
          <ul>
            <li className='title'>
              市场交易
            </li>
            <li>
              <span>货币对</span>
              {
                currencyList?
                <div>
                <Select size='small' notFoundContent='暂无数据' defaultValue={0} onChange={this.changeCurrencyChecked.bind(this)}>
                  {currencyOpt}
                </Select>
                <i>{currencyList[currencyIndex].CURRENCY_PAIR}</i>
                <p className='ratio'>
                  <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={this.state.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>
              <p>最大价格容忍点差 <Icon onClick={()=>{
                Modal.info({
                  centered:true,
                  okText:'确定',
                  title: '最大价格容忍点差',
                  content: '如果客户提交订单的价格与最新报价之间的价格差异超过最大价格容忍点差，则交易不予成交。如果价格差异小于最大价格容忍点差，交易以最新报价成交。'
                });
              }} type="question-circle" /><span className='fright'>{param.pip}</span></p>              
            </li>
            <li>
              <i>0</i>
              <Slider 
              defaultValue={2} 
              min={0}
              max={param.maxPip}
              onChange={this.handleSlider.bind(this, 'change')}
              onAfterChange={this.handleSlider.bind(this, 'afterChange')}
              />
              <i>{param.maxPip}</i>
            </li>
            <li>
              <span className='confirmbtn' onClick={this.doFirmTrade.bind(this)}>确定</span>
            </li>
          </ul>
        </aside>
        <div className='order-list'>
          <div className='right-top'>
            {/* <p className='title'>
              <span className='orders-type'>当日交易查询</span>
              <span className='queryResult'>查询结果: 共[{queryResultNum}]笔 记录</span>         
            </p> */}
            <Tool title='当日交易查询' refresh={()=>this.setState({queryResultArr:[]},this.QueryTradeList(this.props.userInfo,this.props.priceObj))}
            list = {this.orderTable} queryResultNum={queryResultNum} userInfo={this.props.userInfo} data={queryResultArr}/>
            <div className='choose'>
              <SelectOption okBtnHandle={this.okBtnHandle.bind(this)} selectIndexArr = {[productIdIndex,tradeTypeIndex,tradeStateIndex,orderStatusIndex,accountTypeIndex,timeSelectFlag]}></SelectOption> 
            </div>       
          </div>
          <OrderTabel list = {this.orderTable} data={queryResultArr} loading={loading} noResult={noResult} height={this.state.tableHeight}></OrderTabel>      
        </div> 
      </div>
    );
  }
}

const mapStateToProps = (state) => {
  const { loginLogout } = state;
  return {
    loginState: loginLogout.loginState,
    userInfo: loginLogout.userInfo,
    priceObj:loginLogout.priceObj,
  };
};
export default connect(mapStateToProps)(MarketTrade);