import React, { Component } from "react";
import { Radio,DatePicker,Table,Select ,Icon,Modal,Spin} from 'antd';
import {getDomHeight} from './../../utils/dom.js'
import commonTool from 'utils/commonTool.js';
import { connect } from 'react-redux';
import { requestInterface } from 'utils/dom.js';
import moment from 'moment';
import 'moment/locale/zh-cn';
moment.locale('zh-cn');
const RadioGroup = Radio.Group;
import './Tabel.scss';

export default class OrderTabel extends Component{
    constructor(props){
        super(props);
        this.state={
          height:window.innerHeight-28-29-31-20,
          columns:[],
          selectedRowKeys: [],
          percent:0,
          cancleLoading:false,//多笔待成交挂单撤销加载状态
        }
        this.onSelectChange=this.onSelectChange.bind(this);
        this.showModal=this.showModal.bind(this);
        this.doCancelFxOrder=this.doCancelFxOrder.bind(this);
    }
    componentDidMount(){
      var ths = this;
      this.setState({
        height:getDomHeight('.order-list')-getDomHeight('.right-top')-5-28,
      })
      window.onresize=function(e){
        var  height = getDomHeight('.order-list')-getDomHeight('.right-top')-5-28;
        ths.setState({height:height});
      }
    }
    //选择要撤销的挂单事件
    onSelectChange(selectedRowKeys){
      console.log('selectedRowKeys changed: ', selectedRowKeys);
      this.setState({ selectedRowKeys: selectedRowKeys});
    }
    //点击撤销弹出确认框
    showModal(){
      if(this.state.selectedRowKeys.length>0){
        const self = this;
        Modal.confirm({
          title: '提示',
          content: '请确认是否撤销所选中的挂单',
          okText: '确认',
          cancelText: '取消',
          onOk() {
            self.doCancelFxOrder();
          },
        });
      }else{
        Modal.warning({
          okText:'知道了',
          title: '提示',
          content: '请先选中您要撤销的挂单，只有状态为"待成交"的挂单才能撤销委托！'
        });
      }
      
    }
    //实盘委托撤销函数
    doCancelFxOrder(){
      let userInfo = this.props.userInfo;
      let selectedRowKeys = this.state.selectedRowKeys;
      const dataDoCancel = this.props.data;
      if(selectedRowKeys.length<=1){
        var reqInfo = {
          name:'实盘委托撤销',
          data:{
            inparam:{
              'param.CUSTOMER_ID':'#{{longCustId}}',
              'param.TRADE_ACCOUNT':userInfo.longBusiId,
              'param.CHANNEL':'5',//px
              'param.SERIAL_NO': this.props.data[selectedRowKeys[0]][0],
              'terminalinfo': '[terminalinfo]',
            }
          }
        };
        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){
              Modal.success({
                okText:'知道了',
                title: '操作成功',
                content: '该笔挂单撤销成功',
                onOk() {window.location.reload()},
              });
            }else{
              //数据返回异常
              //console.log(commonTool.transformErrMsg(resData.message));
              Modal.warning({
                okText:'知道了',
                title: '接口返回错误',
                content: commonTool.transformErrMsg(resData.message)
              });
            }
          }else{
            //接口错误
            Modal.warning({
              okText:'知道了',
              title: '接口返回错误',
              content: resList.ERRMSG
            });
          }  
        });
      }else{
        this.setState({cancleLoading:true});
        const self = this;
        selectedRowKeys.map(function(item,index){
          console.log(self.state.cancleLoading);
          (function (index,dataDoCancel) {
              setTimeout(function () {
                var reqInfo = {
                  name:'实盘委托撤销',
                  data:{
                    inparam:{
                      'param.CUSTOMER_ID':'#{{longCustId}}',
                      'param.TRADE_ACCOUNT':userInfo.longBusiId,
                      'param.CHANNEL':'5',//px
                      'param.SERIAL_NO': dataDoCancel[item][0],
                      'terminalinfo': '[terminalinfo]',
                    }
                  }
                };
                requestInterface(reqInfo,userInfo).then(function(res){
                  if(res.RNUM !== '-1'){
                    let resData=''
                    res.list.map((item,index)=>{
                      resData+=item.outparam;
                    })
                    resData = JSON.parse(resData);
                    if(resData.success){
                      if(index == selectedRowKeys.length-1){
                        self.setState({cancleLoading:false});
                        Modal.success({
                          okText:'知道了',
                          title: '操作成功',
                          content: '选中挂单撤销成功',
                          onOk() {window.location.reload()},
                        });
                      }
                      
                    }else{
                      //数据返回异常
                      //console.log(commonTool.transformErrMsg(resData.message));
                      Modal.warning({
                        okText:'知道了',
                        title: '接口返回错误',
                        content: commonTool.transformErrMsg(resData.message),
                        onOk() {window.location.reload()},
                      });
                     
                    }
                  }else{
                    //接口错误
                    Modal.warning({
                      okText:'知道了',
                      title: '接口返回错误',
                      content: resList.ERRMSG,
                      onOk() {window.location.reload()},
                    });
                    
                  }  
                });
              }, 200 * index)
          })(index,dataDoCancel)
        })
      }
      
    }
    render(){
      let columns =[];  //表头
      if(this.props.list){
        this.props.list.map(function(item,index){
          let columnItem = {};
          columnItem.title = item;
          columnItem.dataIndex = 'dataIndex'+index;
          columnItem.width = '180';
          columnItem.key = index;
          columnItem.render =  function(text) {
            if(text){
              if(text.image){
                return <span><img src={text.image} alt="" style={{width:'18px',marginRight:'5px'}}/> <span>{text.text}</span> </span>
              }else{
                return text
              }
            }
          }
          columns.push(columnItem);
        })
      }
      var th=[];
      columns.map(function(item,index){
        th.push(
            <th key={item.title}>{item.title}</th>
        )
      })        
      const data = [];    //表格内容
      if(this.props.data && this.props.data.length>0){
        for (let i = 0; i < this.props.data.length; i++) {
          let dataIndexArr={};
          // console.log(this.props)
          for(let j=0;j<this.props.list.length;j++){
            dataIndexArr['dataIndex'+j]=this.props.data[i][j];
          }
          dataIndexArr['key']=i;
          data.push(dataIndexArr);
        }
      }

      let rowSelection={};
      if(this.props.cancelFxOrderIndex){
        rowSelection = {
          selectedRowKeys:this.state.selectedRowKeys,
          onChange: this.onSelectChange,
          getCheckboxProps: record => ({
            disabled: record.dataIndex9 !== '待成交', // Column configuration not to be checked
            name: record.name,
          }),
        };
      }
      
      return(
          <div className='order-tabel' ref='table'>
            {this.props.cancelFxOrderIndex?
              <p className='title'>
                <span className='orders-type-confirm' onClick={(e)=>this.showModal(e)}>撤销</span>         
              </p>
              :''
            }
             
            {!this.props.cancelFxOrderIndex?
              <table>
                <thead>
                    <tr>
                      {th}
                    </tr>
                </thead>
              </table>
              :''
            }
            {this.props.data.length >0
              ?(!this.props.cancelFxOrderIndex?<Table  id='table-list'
                  scroll={{y:this.props.loading?this.state.height-30:this.state.height}} 
                  showHeader={false} pagination={false} columns={columns} align='center' dataSource={data}/>
                :<Spin spinning={this.state.cancleLoading}>
                    <Table  id='table-list'
                      scroll={{y:this.props.loading?this.state.height-50:this.state.height-30}} 
                      showHeader={true} pagination={false} columns={columns} align='center' dataSource={data} rowSelection={rowSelection}/>
                  </Spin>
                )
              :''
            }
              
            {this.props.loading || this.props.noResult?
              (this.props.loading?
                <p className='load-more' ><Icon type="loading" /> 加载中...</p>:<p className='load-more' >暂时没有相关数据</p>)
              :''
            }
          </div>
      )
    }
}