import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import { Row, Col, Pagination, Button, Menu, Dropdown, Icon, message, Alert, Spin,Modal,Select } from 'antd'
import TdCmpName from '../common/TdCmpName'
import { SketchPicker } from 'react-color';
import SearchFields from '../common/searchfields/'
// let Handsontable = require('handsontable');
import './newDetail.css'
let Option= Select.Option;

let myRepDetailNewDataBegin = null;
///集合取交集
Array.intersect = function () {
    var result = new Array();
    var obj = {};
    for (var i = 0; i < arguments.length; i++) {
        for (var j = 0; j < arguments[i].length; j++) {
            var str = arguments[i][j];
            if (!obj[str]) {
                obj[str] = 1;
            }
            else {
                obj[str]++;
                if (obj[str] == arguments.length)
                {
                    result.push(str);
                }
            }//end else
        }//end for j
    }//end for i
    return result;
}


class Detail extends Component {
    constructor(props){
        super(props)
        this.instance = null
        this.state = {
            loading: true,
            isError: false,
            errorText: '',
            reportId : props.reportId,
            moduleType : props.moduleType,   //报表来自于哪个模块
            name: "",
            rep_data: [],
            rep_config: {
                manualColumnResize: "true",
                manualRowResize: "true",
                colWidths: [],
                rowHeights: [],
                mergeCells: []
            },
            db: '',
            guid: "",
            cache_span: '',
            rep_data_new: 2, 
            total:0,
            page:1,
            count:[],
            searchParams:[],
            showElIdRef : "preview" + Math.random().toString() + "",
            selec_data:[],
            link_type: props.linkType?true:false,
            slot:props.slot?props.slot:{},
            style:{
                fontSize:"12px",
                fontWeight:"normal",
                fontStyle:"normal",
                color:"#000",
                fontFamily:"Microsoft YaHei",
                textAlign:"center",
                backgroundColor:"#fff",
                borderStyle:"solid",
                borderColor:"#e9e9e9"
            },
            megreconfig:[],
            tableStyle:{
                td:{},
                th:{},
            },
            fields:[],
            portal_data_link:[],
            pageSize:20,
            currentPageData:[],
            fullScreenDom:  new Date().getTime().toString()


        }
    }
    handleExportMenuClick(e) {
        let data = {
            id: this.props.reportId,
            type : 'Yes'
        }
        // if (e.key === '1') {
        //     window.location.href = `/general/appbuilder/web/report/replist/export?id=${this.props.reportId}&type=Yes&category=excel&searchParams=${JSON.stringify(this.state.searchParams)}&slot=${JSON.stringify(this.state.slot)}&link_type=${this.state.link_type}`;
        // } else if (e.key === '2') {
        //     window.location.href = `/general/appbuilder/web/report/replist/export?id=${this.props.reportId}&type=Yes&category=html&searchParams=${JSON.stringify(this.state.searchParams)}&slot=${JSON.stringify(this.state.slot)}&link_type=${this.state.link_type}`;
        // }
		//由于get在IE下面提交字符限制,修改成post
		if(e.key === '1') {
            data.category="excel"
        } else if (e.key === '2') {
            data.category="excel"
        }
		data.searchParams=this.state.searchParams
		data.slot=this.state.slot
		data.link_type=this.state.link_type
		jQuery.post('/general/appbuilder/web/report/repdetail/getquerykey', { ...data }, function (res) {
            console.log(res)
            window.location.href = `/general/appbuilder/web/report/replist/export?key=`+res            
        })
    }

    //明细表打印
    reportPrint() {
        let data = {
            id: this.props.reportId,
            type: 'Yes',
            category: 'html',
            print: 1,
            searchParams: this.state.searchParams,
            slot:this.state.slot,
            link_type:this.state.link_type
        }
        if(window.top.dd&&window.tMobileSDK.printReport){
            let url='/general/appbuilder/web/report/replist/export?'
            url+=`id=${data.id}&type=${data.type}&category=${data.category}&print=${data.print}&searchParams=${JSON.stringify(data.searchParams)}&slot=${JSON.stringify(data.slot)}&link_type=${JSON.stringify(data.link_type)}`
            tMobileSDK.printReport(url) 
            return;
        }
        jQuery.get('/general/appbuilder/web/report/replist/export', { ...data }, function (res) {
            var iframe = document.createElement('IFRAME');
            var doc = null;
            iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:-500px;top:-500px;');
            document.body.appendChild(iframe);
            doc = iframe.contentWindow.document;
            doc.write(res);
            doc.close();
            iframe.contentWindow.focus();
            iframe.contentWindow.print();
            if (navigator.userAgent.indexOf("MSIE") > 0) {
                document.body.removeChild(iframe);
            }
        })
    }
    onShowSizeChange(current, pageSize){
        // console.log(current, pageSize)
        this.setState({
            pageSize:pageSize,
            page:1
        })
        this.updateData({
            page: 1,
            pageSize: pageSize
        })
    }
    renderTableHeader(param){
        let {
            rep_data,
            rep_data_new,
            rep_config,
            rep_config:{
                
            },
            style,
            tableStyle,
            open_number,
            number_name
        }=this.state
        let  newObject = JSON.parse(JSON.stringify(rep_data ))
        let mergeCells=[]
        if(rep_config.mergeCells){
            mergeCells = JSON.parse(JSON.stringify(rep_config.mergeCells))
        }

        let header=newObject.slice(0,rep_data_new);
        if(open_number!==undefined&& open_number){//判断是否开启编号
            header.forEach(function(item,index){
                if((index+1)===rep_data_new&&number_name){
                    item.unshift(number_name)
                }else{
                    item.unshift("")
                }
            })
            mergeCells.forEach(function(item,index){
                item.col+=1;
            })
        }  
        let thEle= function(j,data){
            let html=[];
            let colNum=-1;
            let length=data.length
           
            data.map((item,z)=>{
                if(z<colNum || length<colNum){
                    return html;
                }
                let objStylr= JSON.parse(JSON.stringify(style))
                if(tableStyle.th&&JSON.stringify(tableStyle.th)!=="{}"){
                    if(open_number){
                        let index=z-1
                        if(tableStyle.th[j+"_"+index]){
                            objStylr=tableStyle.th[j+"_"+index]
                        }else{
                            objStylr=objStylr
                        }
                    }else{
                        if(tableStyle.th[j+"_"+z]){
                            objStylr=tableStyle.th[j+"_"+z]
                        }
                    }     
                }
                objStylr.width= rep_config.colWidths[z]+"px";
                if(!objStylr.height){
                    objStylr.height="50px"
                }
                let isMergeCellBool=false
                if(mergeCells&&mergeCells.length>0){
                    for(var i=0;i<mergeCells.length;i++){
                        // if(mergeCells[i].row===j&&mergeCells[i].col===z){  //横向合并
                        //     isMergeCellBool=true
                        //     colNum=mergeCells[i].colspan+z
                        //     html.push(<th style={objStylr} key={`th_${j}_${z}`} rowSpan={`${mergeCells[i].rowspan}`} colSpan={`${mergeCells[i].colspan}`}>{ item}</th>)
                        // }else if(mergeCells[i].col===z&&mergeCells[i].rowspan>1 &&mergeCells[i].row!==j ){  //纵向合并
                        //     isMergeCellBool=true
                        // }
                        if(mergeCells[i].row===j&&mergeCells[i].col===z&&mergeCells[i].colspan>1){  //横向合并
                            isMergeCellBool=true
                            colNum=mergeCells[i].colspan+z;
                            html.push(<td style={objStylr} key={`td_${j}_${z}`} rowSpan={`${mergeCells[i].rowspan}`} colSpan={`${mergeCells[i].colspan}`} >
                                <span onClick={()=>me.handleClick(item,j,z)} dangerouslySetInnerHTML={{ __html: item }}></span>
                            </td>)
                        }else if(mergeCells[i].col===z&&mergeCells[i].rowspan>1 &&mergeCells[i].row===j ){  //纵向合并
                            isMergeCellBool=true;
                            html.push(<td style={objStylr} key={`td_${j}_${z}`} rowSpan={`${mergeCells[i].rowspan}`} colSpan={`${mergeCells[i].colspan}`} >
                                <span onClick={()=>me.handleClick(item,j,z)} dangerouslySetInnerHTML={{ __html: item }}></span>
                            </td>)
                        }else if(mergeCells[i].col===z&&mergeCells[i].rowspan>1 &&mergeCells[i].row!==j){  //跳过合并列
                            let max=mergeCells[i].rowspan+mergeCells[i].row;
                            if(j>mergeCells[i].row&&j<max){
                                isMergeCellBool=true
                            }

                        }
                    }
                }
                if(!isMergeCellBool){
                    colNum=-1;
                    html.push(<th style={objStylr} key={`${j}_${z}`} >{ item}</th> )
                }
            })
            return html
        }
        
        let trEle = header.map((item, i) => {
            return (
                <tr key={`row_${i}`}>
                    {
                        thEle(i,item)
                    }
                </tr>
            );
            
        });
        return trEle;
        
    }
    handleClick(data,row,col){
        // console.log(data,row,col);
        if(data.indexOf('href="/general/appbuilder/web/report/repdetail/view/?')>-1){  
            return;
        }
        let {currentPageData,portal_data_link,fields}=this.state;
        let me=this
        let colFields=""
        // for(let  key in fields){
        //     let index=key.lastIndexOf("_")
        //     if(index>-1){
        //         if(parseInt(key.slice(index+1),10)===col){
        //             colFields=fields[key]
        //         }
        //     }
        // }
       
        if(fields[col]&&fields[col].indexOf(":编号")>-1){
            return;
        }
        
        let selectedData=[];
        for(let j = row; j < currentPageData.length; j ++ ){
            let item=currentPageData[j]
            if(currentPageData[j+1]&&currentPageData[j+1][col]===currentPageData[j][col]){ //判断下一行的同一列字段是否相同
                if(item[col]===data){
                    selectedData.push(item)
                }
            }else {
                if(item[col]===data){
                    selectedData.push(item)
                }
                break; 
            }
        }
       
        function unique(arr) {
            const res = new Map();
            return arr.filter((a) => !res.has(a) && res.set(a, 1))
        }
        let portalLinkDatas={};
        portal_data_link&&portal_data_link.forEach(function(item){
            let key= item.value;  //关联门户的id
            portalLinkDatas[key]={};
            portalLinkDatas[key].linkage_data=item.child
            portalLinkDatas[key].data=[]
            for(let i=0;i<item.child.length;i++){
                let d=item.child[i];
                let obj={
                    label:d.label,
                    value:[]
                }
                let index= fields.indexOf(d.label);
                selectedData.forEach(function(s){
                    obj.value.push(s[index])
                })
                obj.value=unique(obj.value);
                portalLinkDatas[key].data.push(obj)
            }
        })
        // console.log(portalLinkDatas)        
        
        let param={
            linkdata:portalLinkDatas,
            state:me.state,
            selectedValue:data,
            colFidld: fields[col]
        }
        if(me.props.onhandleClick){
            me.props.onhandleClick(param)
        }
        
        // console.log(selectedData)
    }
    
    renderTableBody(param){
        let {
            rep_data,
            rep_data_new,
            style,
            rep_config,
            megreconfig,
            tableStyle,
            currentPageData,
            open_number,
            isOpenMerge
        }=this.state
        let me=this;
        // let data=rep_data.slice(rep_data_new);
        let data=currentPageData;
        let mergeCells=megreconfig
        let hash = {}
        mergeCells = mergeCells.reduceRight((item, next) => {  // 去重且修改行下标
            next.key=next.row+"_"+next.col+"_"+next.rowspan+"_"+next.colspan
            // next.row=next.row-rep_data_new
            hash[next.key] ? '' : hash[next.key] = true && item.push(next);
            return item
        }, []);
        // console.log(mergeCells)
        let tdEle= function(j,data){
            let html=[];
            let colNum=-1;
            let length=data.length
            data.map((item,z)=>{
                if(z<colNum || length<colNum){
                    return html;
                }
                let objStylr= JSON.parse(JSON.stringify(style))
                if(tableStyle.td&&JSON.stringify(tableStyle.td)!=="{}"){
                    if(open_number){
                        let index=z-1
                        if(tableStyle.td[rep_data_new+"_"+index]){
                            objStylr=tableStyle.td[rep_data_new+"_"+index]
                        }else{
                            objStylr=objStylr
                        }
                    }else{
                        if(tableStyle.td[rep_data_new+"_"+z]){
                            objStylr=tableStyle.td[rep_data_new+"_"+z]
                        }
                    }   
                    
                }
                if(j===0){     
                    objStylr.width= rep_config.colWidths[z]+"px";
                }
                
                let isMergeCellBool=false
                if(mergeCells&&mergeCells.length>0){
                    for(var i=0;i<mergeCells.length;i++){
                        if(mergeCells[i].row===j&&mergeCells[i].col===z&&mergeCells[i].colspan>1){  //横向合并
                            isMergeCellBool=true
                            colNum=mergeCells[i].colspan+z;
                            html.push(<td style={objStylr} key={`td_${j}_${z}`} rowSpan={`${mergeCells[i].rowspan}`} colSpan={`${mergeCells[i].colspan}`} >
                                <span onClick={()=>me.handleClick(item,j,z)} dangerouslySetInnerHTML={{ __html: item }}></span>
                            </td>)
                        }else if(mergeCells[i].col===z&&mergeCells[i].rowspan>1 &&mergeCells[i].row===j ){  //纵向合并
                            isMergeCellBool=true;
                            html.push(<td style={objStylr} key={`td_${j}_${z}`} rowSpan={`${mergeCells[i].rowspan}`} colSpan={`${mergeCells[i].colspan}`} >
                                <span onClick={()=>me.handleClick(item,j,z)} dangerouslySetInnerHTML={{ __html: item }}></span>
                            </td>)
                        }else if(mergeCells[i].col===z&&mergeCells[i].rowspan>1 &&mergeCells[i].row!==j){  //跳过合并列
                            let max=mergeCells[i].rowspan+mergeCells[i].row;
                            if(j>mergeCells[i].row&&j<max){
                                isMergeCellBool=true
                            }

                        }
                        
                    }
                }
                if(!isMergeCellBool){
                    colNum=-1;
                    html.push(<td style={objStylr} key={`${j}_${z}`} >
                        <span onClick={()=>me.handleClick(item,j,z)} dangerouslySetInnerHTML={{ __html: item }}></span>
                    </td> )
                }
            })
            
            return html
        }
        let trEle = data.map((item, i) => {
            return (
                <tr key={`tr_${i}`} className="ant-table-row">
                    {
                        // item.map((text,z)=>{
                        //     let obj= JSON.parse(JSON.stringify(style))
                        //     if(i===0){                            
                        //         obj.width= rep_config.colWidths[z]+"px"
                        //     }
                        //     return(
                        //         <td style={obj} key={`td_${i}_${z}`} >{text}</td> 
                        //     )
                        // })
                        tdEle(i,item)
                    }
                </tr>
                
            );
            
        });
        return trEle;
        
    }
    onHandleScroll(event){
        if(event.target){
            document.querySelector('.tableHeader').scrollLeft=event.target.scrollLeft
        }
    }
    fullScreen(){// 全屏显示
        this.setState({
            fullScreenBool:true
        })
        let me=this;
        setTimeout(() => {
            let myRepDetailInstance= document.getElementById(this.state.showElIdRef).children
            // $("#fullScreenChart").html(myRepDetailInstance)
            document.getElementById(me.state.fullScreenDom).appendChild(myRepDetailInstance[0])

        });
    }
    closeFullScreenModal(){
        let me=this
        let myRepDetailInstance= document.getElementById(me.state.fullScreenDom).children;
        document.getElementById(this.state.showElIdRef).appendChild(myRepDetailInstance[0])
        this.setState({
            fullScreenBool:false
        })
    }
    render(){
        const me = this;
        const exportMenu = (
            <Menu onClick={this.handleExportMenuClick.bind(this)}>
                <Menu.Item className="ui-detail-export-excel" key="1">导出Excel</Menu.Item>
                <Menu.Item className="ui-detail-export-html" key="2">导出Html</Menu.Item>
            </Menu>
        );
        let {page,rep_data,pageSize}=this.state
        let showName = this.props.showName ? true : false
        let showSearchParams = this.props.showSearchParams ? true : false
        let showExport = this.props.showExport ? true : false
        let showPrint = this.props.showPrint ? true : false
        let showElId = this.props.el ? this.props.el.toString():'';
        const container = (
            <div id="myRepDetail">
                <div className="td-cmp-option">
                    <Button className='ui-chart-print-btn' onClick={() => { me.fullScreen(); }}>全屏显示</Button>

                    {
                        showExport? <Dropdown overlay={exportMenu}><Button>导出 <Icon type="down" /></Button></Dropdown> : null
                    }
                    {
                        showPrint ? <Button className="ui-detail-print-btn" onClick={this.reportPrint.bind(this)}>打印</Button> : null
                    }
                </div>
                <Row  type="flex" justify="center">
                    <Col>
                        <TdCmpName visible={showName} title={this.state.name} />
                        <Row type="flex" justify="center" align="middle">
                        <Col>
                            <div className="td-cmp-content">
                                {
                                    /* me.state.count.length > 0 ? <Button type="primary" onClick={this.handlerCalc.bind(this)}>计算</Button>:null */
                                }
                                <div>
                                {
                                    showSearchParams && this.state.searchParams.length ? <SearchFields selec_data={this.state.selec_data} searchParams={this.state.searchParams} onSearch={this.onSearch.bind(this)} /> : null
                                }
                                </div>
                                    <div id={this.state.showElIdRef} ref={this.state.showElIdRef} className="preview" style={{"margin":"10px 0px"}}>
                                    <div   className=" ant-table ant-table-default ant-table-large ant-table-bordered ">
                                    
                                        {
                                            this.state.currentPageData.length===0?null:
                                            <div className="ant-table-content" style={{"width":this.state.bodyWidth,"margin":"0 auto"}} >
                                                    {
                                                        me.props.moduleType==="portal"?
                                                        <div className="ant-table-body" style={{"height":parseInt(this.props.style.height,10)-70,"overflowY":"auto"}}>

                                                            <div className="tableHeader"  style={{"marginBottom":this.state.marginBottom}}  >
                                                                <table style={{"width":this.state.tableWidth}}  >
                                                                    <thead className="ant-table-thead">
                                                                        {this.renderTableHeader(rep_data)}
                                                                    </thead>
                                                                    <tbody className="ant-table-tbody" >
                                                                        {this.renderTableBody(rep_data)}
                                                                    </tbody>
                                                                </table>
                                                            </div>
                                                            
                                                        </div>
                                                        :
                                                        <div className="ant-table-body">

                                                            <div className="tableHeader" style={{"overflowX":this.state.overflowX,"overflowY":this.state.overflowY,"marginBottom":this.state.marginBottom}} >
                                                                <table style={{"width":this.state.tableWidth}}  >
                                                                    <thead className="ant-table-thead">
                                                                        {this.renderTableHeader(rep_data)}
                                                                    </thead>
                                                                </table>
                                                            </div>
                                                            <div  className="tableBody" style={{"display":"block","height":this.state.tableHeight,"overflowY":this.state.overflowY,"overflowX":this.state.overflowX}} onScroll={(event)=>{this.onHandleScroll(event)}} >
                                                                <table style={{"width":this.state.tableWidth}} >
                                                                
                                                                    <tbody className="ant-table-tbody" >
                                                                        {this.renderTableBody(rep_data)}
                                                                    </tbody>
                                                                </table>
                                                            </div>
                                                        </div>
                                                        
                                                        
                                                    }
                                                        
                                            </div>
                                        }
                                    </div>
                                    </div>
                                    {
                                        me.state.total > 0 ?
                                        <div>
                                            <div className="clearfix" style={{"float":"none","width":this.state.bodyWidth,"margin":"0 auto","minWidth":"341px"}} >
                                                <Pagination style={{"display":"inline-block","verticalAlign":"middle"}}  current={this.state.page} showSizeChanger   pageSizeOptions={[String(pageSize)]} onChange={this.onChange.bind(this)}   onShowSizeChange={(current, pageSize)=>me.onShowSizeChange(current, pageSize)} pageSize={me.state.pageSize} total={me.state.total} />
                                                <span className="pull-right" style={{"float":"none","lineHeight": "28px","marginLeft": "10px","display":"inline-block"}}>共{me.state.total}条数据</span>

                                            </div>
                                        </div>
                                    
                                        :null
                                    }   
                            </div>
                        </Col>
                        </Row>
                    </Col>
                </Row>
                
                    <Modal
                        closable={true}
                        visible={me.state.fullScreenBool}
                        onCancel={(e)=>me.closeFullScreenModal(e)}
                        width={document.body.clientWidth-20}
                        height={document.body.clientHeight}
                        className="fullScreenModal"
                        style={{"top":0}}
                        bodyStyle={{"width":document.body.clientWidth-20,"height":document.body.clientHeight,"overflow":"auto"}}
                        footer={null}
                        >
                        <div className="preview" id={me.state.fullScreenDom} ></div> 
                        {
                            me.state.total > 0 ?
                            <div className="clearfix" style={{"float":"none","width":this.state.bodyWidth,"margin":"0 auto","minWidth":"341px"}} >
                                <Pagination style={{"display":"inline-block","verticalAlign":"middle"}}  current={this.state.page} showSizeChanger  pageSizeOptions={[String(pageSize)]} onChange={this.onChange.bind(this)}   onShowSizeChange={(current, pageSize)=>me.onShowSizeChange(current, pageSize)} pageSize={me.state.pageSize} total={me.state.total} />
                                <span className="pull-right" style={{"float":"none","lineHeight": "28px","marginLeft": "10px","display":"inline-block"}}>共{me.state.total}条数据</span>

                            </div>
                            :null
                        }
                    </Modal>
            </div>
        )
        let rep_name = this.state.name ? this.state.name : ''
        return this.state.isError ? <Alert
                            message={`“${rep_name}”加载失败`}
                            description={`reportId: ${this.props.reportId} ${this.state.errorText}`}
                            type="info"
                            style={{ marginBottom: 16 }}
                        /> : 
                        <Spin spinning={this.state.loading}>
                        
                       
                        {container}
                        </Spin>
    }
    onSearch(searchParams){
        this.setState({
            searchParams
        },()=>{
            this.getShowData({
                page: 1,
                type: 'Yes',
                cacheType: false
            })
        })
    }
    onChange(page){
        this.setState({
            page,
            loading:true
        })
        this.updateData({
            page: page,
            type: 'Yes',
            cacheType: true
        })
    }
    handlerCalc(){
        this.updateData({
            page: 1,
            type: 'count',
            cacheType: false
        })
    }
    componentDidMount(){
        let firstLoad = true
        this.getShowData({
            page: 1,
            type: 'Yes',
            cacheType: false
        })
        let me=this
        $(window).resize(function() {
            me.updateData({})
        });
    }
    componentWillReceiveProps(next){
        let linkdata=next.linkdata
        if(linkdata){
            this.setState({
                linkdata:linkdata
            })
        }
        let firstLoad = true
        this.getShowData({
            page: 1,
            type: 'Yes',
            cacheType: false,
            linkdata:linkdata
        })
        let me=this
        me.updateData({})
    }
    componentDidUpdate(){
        let {
            rep_config:{
                colWidths
            }
        }=this.state
        if(this.props.moduleType==="portal"){
            return;
        }
        //修正td和th的宽度始终保持一致,达到整齐的样式,防止错位
        let tdWidth=[]
        console.log($('div.tableHeader table thead tr:last'))
        if($('div.tableHeader table thead tr:last')&&$('div.tableHeader table thead tr:last').children()){
            let children=$('div.tableHeader table thead tr:last').children()
            
            if(children&&children.length>0){
                for(let i=0;i<children.length;i++){
                    if($(children[i]).width()>0){
                        tdWidth.push($(children[i]).width())
                    }else{
                        tdWidth.push(colWidths[i])
                    }
                }
            }
        }
        if($('div.tableBody table tbody tr:first')&&$('div.tableBody table tbody tr:first').children()){
            
            let children=$('div.tableBody table tbody tr:first').children()
            
            if(tdWidth.length>0&&children&&children.length>0&&children.length===tdWidth.length){
                for(let i=0;i<children.length;i++){
                    $(children[i]).width(tdWidth[i])
                }
            }
        }
    }
    updateData(params){
        const me = this
        let { rep_tbodyData,pageSize,page,rep_config,rep_data_new,open_number,isOpenNumber,isOpenMerge } = this.state
        if(params&&params.pageSize){
            pageSize=params.pageSize
        }
        if(params&&params.page){
            page=params.page
        }
        
        let currentPageData=rep_tbodyData&&rep_tbodyData.slice(pageSize*(page-1) ,pageSize*page);
        currentPageData = JSON.parse(JSON.stringify(currentPageData ))
        if(open_number!==undefined&& open_number){//判断是否开启编号
            currentPageData.forEach(function(item,index){
                item.unshift((index+1)+((page-1)*20))//添加编号
            })
        }     
        let rowtocoldata = getPreNewData(currentPageData)//报表数据的新数据行转换为列
                let finalldata = rowtocoldata[0] ? [rowtocoldata[0]] : [];//报表数据的新数据的合并信息
                for(let j = 1; j < rowtocoldata.length; j ++ ){
                    let temArr = megMatchCol(rowtocoldata[j-1],rowtocoldata[j])//根据前一列获取后一列的合并数据
                    rowtocoldata[j] = temArr
                    if (rowtocoldata[j] !== undefined ){
                        finalldata.push(rowtocoldata[j])
                    }
                }
        let megreconfig = getMergCfg(finalldata,0)//报表数据的新数据的合并信息装换为合并配置数据  
        let  newObject = JSON.parse(JSON.stringify(currentPageData ))
 
          
        if(!isOpenMerge){
            megreconfig = []
        }else{
            megreconfig = megreconfig
        }
        if(rep_tbodyData&&rep_tbodyData[0]){
            let colWidth=rep_tbodyData[0].length
            if(rep_config.colWidths.length===0){
                rep_config.colWidths.length=colWidth;
                for(let i=0;i<colWidth;i++){
                    rep_config.colWidths[i]=90;
                }
                
            }
            // if(rep_config.colWidths.length!==colWidth){
            //     rep_config.colWidths=rep_config.colWidths.slice(0,colWidth)
            // }
        }
        // if(open_number!==undefined&& open_number){
        //     rep_config.colWidths.unshift(90)
        // }
        let tableWidth = rep_config.colWidths.length>0&&rep_config.colWidths.reduce((x,y)=>x+y)
        let bodyWidth=0
        if(this.props.style&&this.props.style.width ){  //获取样式宽度
            bodyWidth=parseInt(this.props.style.width,10)
        }else if($("#myRepDetail")){
            bodyWidth= $("#myRepDetail").width()-30;
        }
        
            if(bodyWidth!==0){
                if(tableWidth+17>=bodyWidth){
                    this.setState({
                        overflowX:"scroll",
                        marginBottom:"-17px"
                    })
                }else{
                    tableWidth+=17;
                    bodyWidth=tableWidth;
                    this.setState({
                        overflowX:"hidden",
                        marginBottom:"0"
                    })
                }
                this.setState({
                    bodyWidth:bodyWidth
                })
            }
            let bodyHeight=0
            if(this.props.style&&this.props.style.height ){  //获取样式高度
                bodyHeight=parseInt(this.props.style.height,10)
            }else if($("#root .main")){
                bodyHeight= $("#root .main").height()-135;
            }
        
        if(bodyHeight){  
            // let bodyHeight= 400-105;
            let theadHeight=rep_data_new*50; //行高按50计算
            let tbodyHeight=0;
            let tableHeight=currentPageData.length*50;   //计算出的table的真实高度
            if(bodyHeight!==0){
                if(bodyHeight-theadHeight>0){
                    tbodyHeight=bodyHeight-theadHeight;  //   实际只能占用的高度
                }
            }
            if(tbodyHeight!==0&&tbodyHeight>0){
                if(tableHeight+17>tbodyHeight){
                    this.setState({
                        overflowY:"scroll",
                    })
                    tableHeight=tbodyHeight
                }else{
                    this.setState({
                        overflowY:"auto",
                    })
                    // if(this.state.overflowX==="scroll"){
                    //     tableHeight+=17;
                    // }
                    tableHeight="auto"
                }
                this.setState({
                    tableHeight:tableHeight
                })
            }
        }
        this.setState({
            currentPageData:newObject,
            megreconfig:megreconfig,
            loading: false,
            tableWidth:tableWidth
        })
        
    }

    isPC() {
        var userAgentInfo = navigator.userAgent;
        var Agents = new Array("Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod", "webOS");
        var flag = true;
        for (var v = 0; v < Agents.length; v++) {
            if (userAgentInfo.indexOf(Agents[v]) > 0) { flag = false; break; }
        }
        return flag;
    }
    //调整明细表居中情况
    adjustStyleCenter () {
        let self = this;
        if(self.isPC()){
            if (jQuery('#preview .wtHolder  table.htCore').width() < 700) {
                jQuery('#preview .wtHolder').css({ 'width': 'auto !important;' })
                jQuery('#preview .wtHolder').addClass('preview-wrapper-wtHolder')
            }
        }
    }
    getShowData(params){
        const me = this
        const reportId = this.props.reportId
        const moduleType = this.props.moduleType
        const { link_type, slot } = this.state
        let { page,type,cacheType,linkdata } = params
        let { searchParams } = this.state
        let param={
            id: reportId, 
            type: type, 
            page: page, 
            cacheType: cacheType,
            pageSize:20,
            link_type:link_type,
            slot:slot
        }
        // if(moduleType){
        //     param.moduleType=moduleType
        // }
        if(searchParams.length>0){
            param.searchParams=JSON.stringify(searchParams)
        }
        if(this.props.linkdata){
            param.portal_linkage=this.props.linkdata
        }
        if(linkdata&&linkdata){
            param.portal_linkage=linkdata
        }
        jQuery.ajax({
            method: "post",
            url: "/general/appbuilder/web/report/replist/showdata",
            data:param,
            async: true  // 修改成异步加载  
        }).done(function (response) {
            const { status, data } = response
            if (status != 'ok') {
                me.setState({
                    isError: true,
                    loading: false,
                    errorText: response.msg ? response.msg : '请求该明细表数据失败！',
                    name:response.name
                })
                message.error(response.msg)
            } else {
                let {
                    name,
                    rep_data,
                    rep_config,
                    db,
                    guid,
                    cache_span,
                    rep_data_new, 
                    page,
                    data_type,
                    count,
                    searchParams,
                    selec_data,
                    open_number,
                    is_open_merge,
                    table_style,
                    rep_data_last,
                    portal_data_link,
                    currentPage,
                    number_name
                } = data
                
                rep_data = rep_data ? rep_data : [];
                rep_config = rep_config ? rep_config : {};
                 
                myRepDetailNewDataBegin = rep_data_new
                let newdata = rep_data_new //报表数据的新数据起始行数
                let datalenght = rep_data.length //报表数据的新数据行数
                let predata = rep_data//报表数据
                let temdata = []//报表数据的新数据
                if((datalenght - newdata  ) > 0 ){
                    for(let i= newdata;i<datalenght;i++){
                        temdata.push(predata[i])
                    }
                }
                me.adjustStyleCenter()
                let newSearchParams = searchParams.filter(function (elem) {
                    if(elem.type_of_reports === 'search'){
                        return elem;
                    }
                })
                if(table_style===""){
                    table_style=me.state.tableStyle;
                }
                if(rep_data_last===undefined || rep_data_last===null){
                    rep_data_last=me.state.fields;
                }
                if(portal_data_link===undefined ||portal_data_link===null ){
                    portal_data_link=me.state.portal_data_link;
                }
                let colWidth=rep_data_last&&rep_data_last.length
                if(rep_config.colWidths.length!==colWidth){
                    rep_config.colWidths=rep_config.colWidths.slice(0,colWidth)
                }
                if(open_number!==undefined&& open_number){
                    rep_config.colWidths.unshift(90)
                }
                if(currentPage==="" || !currentPage){
                    currentPage=20
                }
               
                me.setState({
                    name,
                    rep_data,
                    rep_config,
                    db,
                    guid,
                    cache_span,
                    rep_data_new, 
                    total:temdata.length,
                    count,
                    searchParams:newSearchParams,
                    selec_data,
                    open_number,
                    isOpenMerge:is_open_merge,
                    fields:rep_data_last,
                    portal_data_link,
                    tableStyle:table_style,
                    rep_tbodyData:temdata,
                    pageSize:currentPage,
                    number_name,

                })  
                me.updateData({
                    page: 1,
                    type: 'Yes',
                    cacheType: false
                }) 
            }
        }).fail(function (e) {
            me.setState({
                isError: true,
                errorText: e.responseText,
                loading: false
            })
        });
    }
}

export default Detail

function negativeValueRenderer(instance, td, row, col, prop, value, cellProperties) {
    Handsontable.renderers.HtmlRenderer.apply(this, arguments);
    if (row < myRepDetailNewDataBegin ) {//修改字体颜色
        td.style.color = '#666';
        td.style.fontWeight = 'bold';
        td.style.backgroundColor = '#f5f5f5';
    }
    cellProperties.renderer = Handsontable.renderers.HtmlRenderer;
}


//把预览数据中的查询出来的数据处理为有合并信息的数据
function getPreNewData(data) {
    var rows=0;
    if(!data){
        return []
    }
	var rows = data.length;//数据的行数
	var cols = 0;//数据的列数
	if (data.length > 0) {
		cols = data[0].length;
	}
	var colTorow = [];//因为根据前一列处理后一列的数据，所以为了需要，先把列转为行

	for (let j = 0; j < cols; j++) {
		var tmp = [];
		for (let i = 0; i < rows; i++) {
			tmp.push({
				row: i,
				col: j,
				data: data[i][j]
			})
		}
		colTorow.push(tmp)
	}

	var f1 = [],//一行中可合并的数据
		f2 = [],// 每一行的数据
		f3 = false,
		f4 = 'undefined',
		f5 = []//最后得到的合并数据
	for (let j = 0; j < cols; j++) {
		for (let [index, elem] of colTorow[j].entries()) {
			if (f4 == elem.data && f3 == elem.col) {//前一个数据与后一个相同则放入一个数组中，同一个数组意味着可合并
				if ((f1[f1.length - 1] + 1) == index) {
					f1.push(index)
                }
                
			} else {
				f3 = elem.col
				f4 = elem.data
					if (f1.length > 0) {
						f2.push(f1)
					}
					f1 = []
				f1.push(index)
            }
		}
		f2.push(f1)
		f5.push(f2)
		f1 = []
		f2 = []
	}
	return f5
}


//根据前一个合并的数据处理：前一列的合并数目应大于等于后一列的数据
function megMatchCol(data1, data2) {
	let arr = []
	data1.forEach(function (eles, index) {
		let ele = eles.join(',')
		data2.forEach(function (items, num) {
			let item = items.join(',')
			if (ele.indexOf(item) != -1) {
				arr.push(items)
			} else if (Array.intersect(eles, items).length > 0) {
				arr.push(Array.intersect(eles, items))
			}
		})
	});
	return arr
}

//根据前一个得到的合并数据，处理为handsontable的合并配置数据
function getMergCfg(data, newdata) {
	let mgcfg = []
	data.forEach(function (item, index) {

		if (item.length >= 1) {

			item.map(function (ele, idx) {
				if (ele.length > 1) {
					mgcfg.push({
						row: ele[0] + parseInt(newdata),
						col: index,
						rowspan: ele.length,
						colspan: 1
					})
				}
			})
		}
	})
	return mgcfg
}


function handleDataToOuYuan(params) {
    let { config, data ,begin } = params
    let locaArr = [];
    let ouYuan = "€"
    config.forEach((v,i) => {
        if(v.money && v.money.money_type && v.money.money_type === "O"){
            locaArr.push(v.id);
        }
    })
    let dataArr = data;

    locaArr.forEach((v,i) => {
        dataArr.forEach(( elem, idx ) => {
            if(idx >= (begin-1)){
                elem[v] = elem[v].replace(/O/, "€")
            }
        })
    })

    return  dataArr
}