import React, { Component } from 'react'
import { Radio, InputNumber, Checkbox, Select, Modal, Table, Icon, message, Tabs, Row, Col, Button, Menu, Dropdown, Alert, Spin } from 'antd';
const TabPane = Tabs.TabPane;
import TdCmpName from '../common/TdCmpName'
import SearchFields from '../common/searchfields/'
import './pivot.css'
import axios from 'axios'
import qs from 'qs';
import TabPaneContent from './TabPaneContent'
import DetailModal from './DetailModal'

let sum
//按key查找数据
let myObj
function getDataByKey(dataSource, key) {
    for (var i = 0; i < dataSource.length; i++) {
        if (dataSource[i].key == key) {
            myObj = dataSource[i]
            break
        } else {
            if (dataSource[i].children) {
                getDataByKey(dataSource[i].children, key)
            }
        }
    }
}
const getQueryParams = () => {
    var qs = location.search.length > 0 ? location.search.substr(1) : '',
        args = {},
        items = qs.length > 0 ? qs.split('&') : [],
        item = null, name = null, value = null, i = 0, len = items.length;
    for (i = 0; i < len; i++) {
        item = items[i].split('=');
        name = decodeURIComponent(item[0]);
        value = decodeURIComponent(item[1]);

        if (name.length) {
            args[name] = value;
        }
    }
    return { ...args }
}
class Pivot extends Component {
    constructor(props) {
        super(props)
        this.state = {
            loading: true,
            isError: false,
            errorText: '',
            //数据集id
            id: '',
            //行信息
            row: '',
            //列信息
            col: '',
            //过滤项信息
            filter: [],
            //计算项信息
            counterItem: [],
            //表格列信息
            columns: [],
            //表格数据信息
            tableData: [],
            //加载过的key
            loadedKeys: [],
            //展开的keys
            expandedRowKeys: [],
            //详情模态框是否可见
            detailModalVisible: false,
            //详情行数据的key
            detailKey: '',
            //详情行列数据的key
            columnKey: '',
            reportName: '',
            // loading: false,
            siderWidth: 0,
            searchParams: [],
            selec_data:[],
            report_id: '',
            timeStamp: '',
            dataFilterParams:[],
            dataLink:[],
            link_type: props.linkType?true:false,
            slot:props.slot,
            selectedVal:'',
            fullScreenDom:  new Date().getTime().toString(),
            portal_data_link:[],   //门户关联关系数据
            portal_rep_link:[],   //门户关联字段
        }
    }
    isIntNum(val){
        // isNaN()函数 把空串 空格 以及NUll 按照0来处理 所以先去除
        if(val === "" || val ==null){
            return false;
        }
        if(!isNaN(val)){
            return true;
        }else{
            return false;
        }
    }

    handleDetailClick(dataIndex, record) {
        const { dataLink ,columns,counterItem}  = this.state;

        function getColumnsFields(columns,columnsObj){//获取列字段
            columns.children.forEach(function(item){
                if(item.children){
                    getColumnsFields(item,columnsObj)
                }else{
                    if(!columnsObj[item.key]){
                        columnsObj[item.key]=item.title
                   }
                }
            })
        }
        let columnsObj={}
        columns.forEach(function(item){
            if(item.children){
                getColumnsFields(item,columnsObj)
            }else{
               if(!columnsObj[item.key]){
                    columnsObj[item.key]=item.title
               }
            }
        })
        let isContinue=true;
        counterItem.forEach(function(item){
            if(item.isCountFiled==="true"){
                if(columnsObj[dataIndex]===item.id){
                    isContinue=false
                }
            }
        })
        if(!isContinue){
            message.info("计算字段不支持穿透功能")
            return;
        }

        let count = 0 ;
        let newRow = this.state.row ;
        newRow = newRow.split(',');
        newRow.map((val,index)=>{
            if(val === dataIndex){
                count ++;
            }
        })


        if(!(count === 1) ){
            let newdataLink = JSON.parse(JSON.stringify(dataLink));
            newdataLink = newdataLink.filter((elem)=>{
              return elem.label != '';
            });


            let newIndex = dataIndex.split("_");
            let selectField = '';
            if(newIndex.length){
                selectField = newIndex[newIndex.length - 1];
            }else{
                selectField = '';
            }
            let fieldFlag = false;
            if(newdataLink.length === 1 && selectField === '' ){
                selectField = 0
            }
            let dataFlagArr = [];
			let tmpFlag='';
            if(this.isIntNum(selectField)){
                
                tmpFlag = this.state.counterItem[selectField].id;
                let tmpcount = 0;
                dataFlagArr = newdataLink.filter(function (items,idx) {
                    if(items.label == tmpFlag){
                        tmpcount++ ;
                        return items;
                    }
                })
                fieldFlag =  tmpcount>0? true:false;
            }

            let portal_rep_link = this.state.portal_rep_link;
                   

           
            let portalState=-1;  //  1 数据关联     2  门户关联    3 数据下钻
            portal_rep_link&&portal_rep_link.forEach(function(item){
                if(item.value===tmpFlag){
                    portalState=item.state
                }  
            })     

            
                if(portalState===1){
                    let row = this.state.row
                    let col = this.state.col
                    let filter = this.state.filter
                    let counterItem = this.state.counterItem
                    let id = this.state.id
                    let { searchParams, link_type, dataFilterParams } = this.state
                    let params = { page:1, pageSize:10, key: record.key, row, col, filter, counterItem, id, column_key: dataIndex,searchParams:searchParams.concat(dataFilterParams), value:record[dataIndex], dataLink: dataFlagArr, link_type };
                    axios({
                        method: "POST",
                        url: '/general/appbuilder/web/report/pivottable/getslicelink',
                        data: qs.stringify(params),
                    }).then((response) => {
                        if (response.data.status != "ok") {
                            let msg = response.message || '获取数据失败'
                            message.error(msg);
                        } else {
                            let url = response.data.data;
                            if(window.top.dd&&window.tMobileSDK.openBrowerWindow){
                                tMobileSDK.openBrowerWindow(url) 
                                return;
                            }
                            window.open(url, '_blank')
                        }
                    })
                }else if(portalState===2){
                    let param={}
                    param.selectedVal=record[dataIndex]
                    param.columnKey=dataIndex
                    param.detailKey=record.key
                    param.record=record
                    param.state=this.state
                    let portal_data_link = this.state.portal_data_link
                    let portalLinkDatas={};
                    let columns = this.state.columns
                    function unique(arr) {
                        const res = new Map();
                        return arr.filter((a) => !res.has(a) && res.set(a, 1))
                    }
                    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:[]
                            }                        
                            if(param.record[d.label]){
                                obj.value.push(param.record[d.label])
                            }
                            obj.value=unique(obj.value);
                            portalLinkDatas[key].data.push(obj)
                        }
                    })
                    param.linkdata=portalLinkDatas
                    if(this.props.onhandleClick){
                        this.props.onhandleClick(param)
                    }
                }else if(portalState===3){
                    this.setState({
                        detailKey: record.key,
                        columnKey: dataIndex,
                        selectedVal: record[dataIndex],
                        detailModalVisible: true
                    })     
                }
        
        }

    }
    getColumns = (params) => {
        const me = this
        this.setState({
            loadedKeys: []
        })
        //获取table数据
        let myParams = { ...params }
        myParams.report_id = this.props.reportId
        myParams.link_type = this.state.link_type
        myParams.rename_filed = this.state.rename_filed
        myParams.slot = this.state.slot
        myParams.dataLink = this.state.dataLink
        axios({
            method: "POST",
            url: '/general/appbuilder/web/report/pivottable/gettable',
            data: qs.stringify(myParams),
        }).then((response) => {
            if (response.data.status != "ok") {
                let msg = response.data.message || '获取表头数据失败'
                message.error(msg);
            } else {
                let columns = JSON.parse(JSON.stringify(response.data.data))
                this.setTableWidth(columns)
                columns=this.tranformColumns(columns)
                this.setState({
                    columns
                })


            }
        }).catch((error) => {
            me.setState({
                // tableData: [],
                loading: false,
                isError: true,
                errorText: error.message
            });
        })
    }
    getTableWidth = (arr) => {
        function getTotal(arr) {
            let total = 0
            function loop(arr) {
                arr.map(item => {
                    if (item.children) {
                        loop(item.children)
                        item.width = getTotal(item.children)
                    } else {
                        item.width ? total = total + parseInt(item.width) : null
                    }
                });
            }
            loop(arr)
            return total
        }
        let tableWidth = getTotal(arr)
        return tableWidth
    }
    setTableWidth = columns => {
        
       
        let arr = this.tranformColumns(columns)
        let tableWidth = this.getTableWidth(arr)
        if(this.props.moduleType==="portal"){
            return;
        }
        let  contentWidth=$(".pivot-content-container").width();
        let tableInfo = document.querySelectorAll('.ant-table-scroll table')[0]
        //暂无数据的提示
        let placeholder = document.querySelectorAll('.table-content .ant-table-placeholder')[0]
        if (tableWidth) {
            tableInfo.style.width = `${tableWidth}px`;
            placeholder ? placeholder.style.width = `${tableWidth + 1}px` : null
            if(tableWidth<contentWidth){
              
                document.querySelectorAll('.table-content')[0].style.width= `${tableWidth+18}px`;
            }else{
                document.querySelectorAll('.table-content')[0].style.width= `${contentWidth-15}px`;
            }
        } else {
        }
    }
    updateData(reportId) {
        const me = this
        this.fetchReportInfo(reportId)
            .then(res => {
                let searchParams = res && res.searchParams ? res.searchParams : []
                let selec_data = res && res.selec_data ? res.selec_data : []
                let tmpdataLink = res && res.data_link ? res.data_link : []
                let rename_filed = res && res.rename_filed ? res.rename_filed : []
                let formula = res && res.formula ? res.formula : []
                let newSearchParams = searchParams.filter(function (elem) {
                    if(elem.type_of_reports === 'search'){
                        return elem;
                    }
                })
                let newDataFilterParams = searchParams.filter(function (elem) {
                    if(elem.type_of_reports === 'select'){
                        return elem;
                    }
                })
                
                let portal_data_link = res && res.portal_data_link ? res.portal_data_link : []
                let portal_rep_link = res && res.portal_rep_link ? res.portal_rep_link : []
                me.setState({
                    searchParams: newSearchParams,
                    selec_data: selec_data,
                    dataFilterParams:newDataFilterParams,
                    // loading: false,
                    dataLink: tmpdataLink,
                    portal_data_link:portal_data_link,
                    portal_rep_link:portal_rep_link,
                    rename_filed:rename_filed,
                    formula:formula
                })
                let dataset_id = res && res.dataset_id ? res.dataset_id : ''
                this.fetchFieldItemsByDataSetId(dataset_id)
                    .then(fieldItems => {
                        let columns = res && res.columns ? res.columns : []
                        this.setTableWidth(columns)
                        let arr = this.tranformColumns(columns)
                        let tmpArr = []
                        res && res.filters.map((item) => {
                            item.dataset_id = res.dataset_id
                            tmpArr.push(this.fetchFilterContent(item))
                        })
                        Promise.all(tmpArr).then(response => {
                            let ary = []
                            res && res.filters.map(item => {
                                let obj = { ...item }
                                response.map(i => {
                                    if (i.id == item.id) {
                                        obj.filterArr = i.filterArr
                                        fieldItems.map(fieldItem => {
                                            if (fieldItem.id == item.id) {
                                                obj.value = fieldItem.value
                                            }
                                        })
                                        // obj.value = item.id
                                        ary.push(obj)
                                    }
                                })
                            })
                            if (res) {
                                this.setState({
                                    reportName: res.name,
                                    id: res.dataset_id,
                                    row: res.horizon_fields,
                                    col: res.vertical_fields,
                                    filter: ary,
                                    counterItem: res.calculate_fields,
                                    formula: res.formula,
                                    columns: arr
                                })
                                let params = {}
                                params.id = res.dataset_id
                                params.row = res.horizon_fields
                                params.col = res.vertical_fields
                                params.filter = res.filters
                                params.counterItem = res.calculate_fields
                                params.formula = res.formula
                                this.fetchData(params)
                            }
                        })
                    })
            })
    }
    refreshData() {
        this.fetchReportInfo(reportId)
            .then(res => {
                this.fetchFieldItemsByDataSetId(res.dataset_id)
                    .then(fieldItems => {
                        this.setTableWidth(res.columns)
                        let arr = this.tranformColumns(res.columns)
                        let tmpArr = []
                        res.filters.map((item) => {
                            item.dataset_id = res.dataset_id
                            tmpArr.push(this.fetchFilterContent(item))
                        })
                        Promise.all(tmpArr).then(response => {
                            let ary = []
                            res.filters.map(item => {
                                let obj = { ...item }
                                response.map(i => {
                                    if (i.id == item.id) {
                                        obj.filterArr = i.filterArr
                                        fieldItems.map(fieldItem => {
                                            if (fieldItem.id == item.id) {
                                                obj.value = fieldItem.value
                                            }
                                        })
                                        // obj.value = item.id
                                        ary.push(obj)
                                    }
                                })
                            })
                            this.setState({
                                reportName: res.name,
                                id: res.dataset_id,
                                row: res.horizon_fields,
                                col: res.vertical_fields,
                                filter: ary,
                                counterItem: res.calculate_fields,
                                columns: arr
                            })
                            let params = {}
                            params.id = res.dataset_id
                            params.row = res.horizon_fields
                            params.col = res.vertical_fields
                            params.filter = res.filters
                            params.counterItem = res.calculate_fields
                            this.fetchData(params)
                        })
                    })
            })
    }
    componentWillReceiveProps(nextProps) {
        let {reportId,linkdata} = nextProps
        
        if (this.state.report_id === reportId) {
            if(this.state.linkdata!==linkdata){
                let params = {}
                params.id = this.state.id
                params.col = this.state.col
                params.row = this.state.row
                let tmpArr = []
                let obj
                [...this.state.filter].map(item => {
                    obj = {}
                    obj.id = item.id;
                    item.selected && item.selected.length === 0 ? null : obj.selected = item.selected
                    tmpArr.push(obj)
                })
                params.filter = tmpArr
                params.counterItem = this.state.counterItem
                params.searchParams = this.state.searchParams.concat(this.state.dataFilterParams)
                params.dataLink = this.state.dataLink
                params.slot = this.state.slot
                params.portal_linkage = linkdata
                this.fetchData(params)
            }
        } else {
            this.setState({
                report_id: reportId,
                linkdata:linkdata
            })
            jQuery(`#${this.state.timeStamp}`).hide()
            this.updateData(reportId)
        }
    }
    componentDidMount() {
        let reportId = this.props.reportId
        this.updateData(reportId)
        this.setState({
            report_id: reportId,
            timeStamp: '' + new Date().getTime()
        })

        // let urlParams = JSON.parse(JSON.stringify(repGetDatas))
        // let { report_id, type } = urlParams
        // if (report_id && type) {
        // } else {
        //     this.setState({
        //         siderWidth: 205
        //     })
        // }
        if(this.state.timeStamp){
            jQuery(`#${this.state.timeStamp}`).hide()
        }
    }
    //获取筛选项下的具体筛选项
    fetchFilterContent = (item) => {
        let myItem = { ...item }
        let params = {}
        params.filter_id = item.id
        params.id = item.dataset_id
        return axios({
            method: "GET",
            url: '/general/appbuilder/web/report/pivottable/getfilter',
            params
        }).then((response) => {
            if (response.data.status != "ok") {
                let msg = response.data.message || '获取筛选项数据失败'
                message.error(msg);
            } else {
                myItem.filterArr = [...response.data.data]
                return myItem
            }
        }).catch((response) => {
            // message.error('获取筛选项数据失败');
        })

    }
    fetchDataByKey(key) {
        let params = {}
        params.report_id = this.props.reportId
        params.id = this.state.id
        params.col = this.state.col
        params.row = this.state.row
        params.filter = this.state.filter
        params.counterItem = this.state.counterItem
        params.expandedKey = key
        params.sum = sum
        params.link_type = this.state.link_type
        params.slot = this.state.slot
        params.dataLink = this.state.dataLink
        params.searchParams = this.state.searchParams
        params.formula = this.state.formula
        let preTableData = [...this.state.tableData]
        getDataByKey(preTableData, key)
        this.setState({
            loading: true
        })
        // axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
        axios({
            method: "POST",
            url: '/general/appbuilder/web/report/pivottable/showdata',
            data: qs.stringify(params),
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).then((response) => {
            this.setState({
                loading: false
            })
            if (response.data.status == "ok") {
                //如果参数是有key 请求的具体数据
                let length=params.row.split(",").length-1;
                let keyLength=key.split(":").length/2;
                if(length<=keyLength){ // 判断展开项的层级次数
                    response.data.data.forEach(item=>{
                        delete item.children
                    })
                }
                myObj.children = response.data.data
                this.setState({
                    tableData: preTableData
                })
                let arr = [...this.state.loadedKeys]
                arr.push(key)
                this.setState({
                    loadedKeys: arr
                })
            } else {
                let msg = response.message || '获取表格数据失败'
                me.setState({
                    loading: false,
                    isError: true,
                    errorText: msg
                })
                message.error(msg);
                return;
            }
        }).catch((error) => {
            me.setState({
                tableData: [],
                loading: false,
                isError: true,
                errorText: error.message
            });
        })

    }
    //当点击展开加号的时候
    onExpand = (expanded, record) => {
        let _loadedKeys = [...this.state.loadedKeys]
        let _expandedRowKeys = [...this.state.expandedRowKeys]
        //是否已经加载过
        let isExist=false
        if (_loadedKeys.length) {
            _loadedKeys.map(item => {
                item == record.key ? isExist = true : null
            })
        } else {
            isExist = false
        }
        if (expanded) {
            _expandedRowKeys.push(record.key)
            this.setState({
                expandedRowKeys: _expandedRowKeys
            })
            if (!isExist) {
                this.fetchDataByKey(record.key)
            }
        } else {
            let arr = _expandedRowKeys.filter(item => {
                return item != record.key
            })
            this.setState({
                expandedRowKeys: arr
            })
        }
    }
    closeDetailModal = () => {
        this.setState({
            detailModalVisible: false
        })
    }
    componentDidUpdate() {
        let filterH = this.state.filter.length === 0 ? 0 : 110
        let self = this
        jQuery(`#${this.state.timeStamp} .pivot-table-content-container`).css('max-height', jQuery(window).height() - filterH - 90)
        jQuery(`#${this.state.timeStamp} .pivot-table-content-container`).css('height', "auto")
        jQuery(".ant-table-body").css('height', "auto")
        if($(".ant-table-body").height()<$(".ant-table-body table").height()){
            let all_height=parseInt($(".table-content").height());
            $(".ant-table-fixed-left").css("height",all_height-15);  
        }else{
            // if($(".ant-table-body table").height()&&$(".ant-table-body table").height()>=51){
            //     $(".ant-table-body table").css("height",$(".ant-table-body").height())
            // }
           
        }
        //修复 表格高度不一致导致的 样式紊乱
        if($(`#${this.state.timeStamp} .ant-table  .ant-table-scroll`).length>0&&$(`#${this.state.timeStamp} .ant-table  .ant-table-fixed-left`).length>0){
            let trDom=  $(`#${this.state.timeStamp} .ant-table  .ant-table-scroll     table.ant-table-fixed tbody`).children() 
            let leftTbody= $(`#${this.state.timeStamp} .ant-table  .ant-table-fixed-left table.ant-table-fixed tbody`) 
            if(trDom&&trDom.length>0){
                for (let i = 0; i < trDom.length; i++) {
                    let height= $(trDom[i]).height();
                    $(leftTbody).children().eq(i).height(height)
                    
                }
                
            }
            
        }
    }
    fetchData(params) {
        const me = this
        this.setState({
            loadedKeys: []
        })
        //获取table数据
        let myParams = { ...params }
        myParams.report_id = this.props.reportId
        myParams.link_type = this.state.link_type
        myParams.slot = this.state.slot
        myParams.dataLink = this.state.dataLink
        if(this.props.linkdata){
            myParams.portal_linkage=this.props.linkdata
        }
        if(this.state.linkdata){
            myParams.portal_linkage=this.state.linkdata
        }
        axios({
            method: "POST",
            url: '/general/appbuilder/web/report/pivottable/showdata',
            data: qs.stringify(myParams),
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).then((response) => {
            if (response.data.status != "ok") {
                let msg = response.data.message || '获取列数据失败'
                message.error(msg);
                me.setState({
                    tableData: [],
                    loading: false,
                    isError: true,
                    errorText:msg
                });
                return;
            } else {
                sum = response.data.sum
                this.setState({
                    tableData: response.data.data,
                    loading: false
                })
                if (response.data.data.length) {
                    jQuery(`#${this.state.timeStamp}`).show()
                }

            }
        }).catch((error) => {
            me.setState({
                tableData: [],
                loading: false,
                isError: true,
                errorText: error.message
            });
        })

    }
    tranformColumns = (arr) => {

        const me = this
        const firstFlag=true;

        const loop = (arr,firstFlag) => {
            let _arr = []
            arr.forEach((item, key) => {
                if (item.children) {
                    firstFlag=false;
                    let _children = loop(item.children,firstFlag)
                    _arr.push({
                        key: item.key,
                        dataIndex: item.dataIndex,
                        title: item.title,
                        children: _children,
                        render: function (text, record) {
                            return <div onClick={() => me.handleDetailClick(item.dataIndex, record)} className="detail-hover">{record[item.dataIndex]}</div>
                        }
                    })
                } else {
                    let obj={
                        key: item.key,
                        dataIndex: item.dataIndex,
                        width:item.width || 140,
                        // sorter: true,
                        title: item.title,
                        render: function (text, record) {
                            return <span onClick={() => me.handleDetailClick(item.dataIndex, record)} className="detail-hover">{record[item.dataIndex]}</span>
                        }
                    }
                    if(firstFlag){
                        obj.fixed= 'left';
                        obj.width=item.width || 167;
                        item.visibleWidthSetting=true;
                        firstFlag=false;
                        
                    }
                    _arr.push(obj);
                }

            })

            return _arr
        }
        return loop(arr,firstFlag)
    }
    fetchReportInfo = (reportId) => {
        const me = this
        let params = {}
        params.id = reportId
        params.link_type = me.state.link_type
        params.slot = me.state.slot
        return axios({
            method: "GET",
            url: '/general/appbuilder/web/report/repdetail/edit',
            params
        }).then((response) => {
            return response.data.data
        }).catch(function (error) {
            me.setState({
                loading: false,
                isError: true,
                errorText: error.message
            });
        });
    }
    fetchFieldItemsByDataSetId(id) {
        const me = this
        let params = {}
        params.id = id
        params['reportId'] = this.props.reportId
        params.link_type = me.state.link_type
        params.slot = me.state.slot
        return axios({
            method: "GET",
            url: '/general/appbuilder/web/report/pivottable/alldata',
            params
        }).then((response) => {
            if (response.data.status != "ok") {
                let msg = response.data.message || '获取字段数据失败'
                message.error(msg);
            } else {
                let tmpdata = [...response.data.data].map(item => {
                    item.dataSetId = id
                    return item
                })
                return tmpdata
            }
        }).catch(function (error) {
            me.setState({
                loading: false,
                isError: true,
                errorText: error.message
            });
        });
    }
    setSelected = (id, selected) => {
        let tmpArr = [...this.state.filter];
        tmpArr.forEach((item) => {
            if (item.id === id) {
                item.selected = selected
            }
        })
        this.setState({
            filter: [...tmpArr]
        })
        this.preview()
    }
    preview = () => {
        let tmpArr = []
        let params = {}
        params.id = this.state.id
        params.col = this.state.col
        params.row = this.state.row
        tmpArr = []
        let obj
        [...this.state.filter].map(item => {
            obj = {}
            obj.id = item.id;
            item.selected && item.selected.length === 0 ? null : obj.selected = item.selected
            tmpArr.push(obj)
        })
        params.filter = tmpArr
        params.counterItem = this.state.counterItem
        this.fetchData(params)
    }
    onSearch(searchParams) {
        this.setState({
            searchParams,
            expandedRowKeys:[],
            tableData:[]

        }, () => {
            this.getData()
        })
    }
    getData() {
        let tmpArr = []
        let params = {}
        params.id = this.state.id
        params.col = this.state.col
        params.row = this.state.row
        tmpArr = []
        let obj
        [...this.state.filter].map(item => {
            obj = {}
            obj.id = item.id;
            item.selected && item.selected.length === 0 ? null : obj.selected = item.selected
            tmpArr.push(obj)
        })
        params.filter = tmpArr
        params.counterItem = this.state.counterItem
        params.searchParams = this.state.searchParams.concat(this.state.dataFilterParams)
        params.dataLink = this.state.dataLink
        params.slot = this.state.slot
        params.slot = this.state.slot
        params.formula = this.state.formula
        this.fetchData(params)
        this.getColumns(params)
    }
    handleExportMenuClick(e) {
        let _sef = this
        let category;
        if (e.key === '1') {
            category = 'excel';
            _sef.sendExportData(category)
        } else if (e.key === '2') {
            category = 'html';
            _sef.sendExportData(category)
        }
    }
    sendExportData(category) {
        let params = {}
        let url = '/general/appbuilder/web/report/pivottable/export';
        params.category = category
        params.reportId = this.props.reportId
        params.id = this.state.id
        params.col = this.state.col
        params.row = this.state.row
        params.filter = this.state.filter
        params.counterItem = this.state.counterItem
        params.formula = this.state.formula
        params.reportName = this.state.reportName || '统计表'
        params.searchParams=this.state.searchParams.concat(this.state.dataFilterParams)
        let xx = JSON.stringify(params);
        url = `${url}?reportId=${params.report_id}&id=${params.id}&col=${params.col}&row=${params.row}&filter=${JSON.stringify(params.filter)}&formula=${JSON.stringify(params.formula)}&counterItem=${JSON.stringify(params.counterItem)}&category=${category}&reportName=${JSON.stringify(params.reportName)}&searchParams=${JSON.stringify(this.state.searchParams.concat(this.state.dataFilterParams))}`;
        console.log(url)
        // window.location.href = url    
        //由于get在IE下面提交字符限制,修改成post
        jQuery.post('/general/appbuilder/web/report/repdetail/getquerykey', { ...params }, function (res) {
            console.log(res)
            window.location.href = `/general/appbuilder/web/report/pivottable/export?key=`+res            
        })
    }

    //统计表打印
    reportPrint() {
        let params = {}
        let url = '/general/appbuilder/web/report/pivottable/export';
        params.report_id = this.props.reportId
        params.id = this.state.id
        params.col = this.state.col
        params.row = this.state.row
        params.filter = this.state.filter
        params.formula = this.state.formula
        params.counterItem = this.state.counterItem
        params.reportName = this.state.reportName || '统计表';
        url = `${url}?reportId=${params.report_id}&id=${params.id}&col=${params.col}&row=${params.row}&filter=${JSON.stringify(params.filter)}&formula=${JSON.stringify(params.formula)}&counterItem=${JSON.stringify(params.counterItem)}&category=html&print=1&reportName=${JSON.stringify(params.reportName)}&searchParams=${JSON.stringify(this.state.searchParams.concat(this.state.dataFilterParams))}`;
        if(window.top.dd&&window.tMobileSDK.printReport){
            tMobileSDK.printReport(url) 
            return;
        }
        console.log(url)
        axios({
            method: "GET",
            url: url
        }).then((response) => {
            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(JSON.stringify(response.data));
            doc.close();
            iframe.contentWindow.focus();
            iframe.contentWindow.print();
            if (navigator.userAgent.indexOf("MSIE") > 0) {
                document.body.removeChild(iframe);
            }
        }).catch((response) => {
            message.error('获取打印数据失败');
        })
    }
    fullScreen(){// 全屏显示
        this.setState({
            fullScreenBool:true
        })
        let me=this;
        setTimeout(() => {
            let myRepPovitInstance= document.getElementById(this.state.timeStamp).children
            // $("#fullScreenPivot").html(myRepPovitInstance)
            document.getElementById(me.state.fullScreenDom).appendChild(myRepPovitInstance[0])
        });
    }
    closeFullScreenModal(){
        let me=this
        let myRepPovitInstance= document.getElementById(me.state.fullScreenDom).children;
        document.getElementById(me.state.timeStamp).appendChild(myRepPovitInstance[0])
        
        this.setState({
            fullScreenBool:false
        })
    }
    render() {
        const exportMenu = (
            <Menu onClick={this.handleExportMenuClick.bind(this)}>
                <Menu.Item className="ui-pivot-export-excel" key="1">导出Excel</Menu.Item>
                <Menu.Item className="ui-pivot-export-html" key="2">导出Html</Menu.Item>
            </Menu>
        );
        $(".ant-table-fixed-left").css({"border-right":"1px solid #e9e9e9"})

        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 me=this;    
        let x=1200,y=400;
        let width=$(".ant-table-header .ant-table-fixed").width();
        if(width){
            x=width;
        }
        let all_height=$(".pivot-table-content-container").css("max-height");
        let header_height=$(".ant-table-header") ?$(".ant-table-header").height() :0 ;
        let search_height=$(".rep-search") ?$(".rep-search").height() :0 ;
        if(all_height&&parseInt(all_height)){
             y= parseInt(all_height)-header_height-search_height;
        }
        let  containerStyle={}
        if(this.props.style){
            if(this.props.style.width){
                containerStyle.width=this.props.style.width
            }
            if(this.props.style.height){
                containerStyle.height=this.props.style.height
            }
        }
        if(this.props.moduleType==="portal"){
            if(this.state.columns.length){
                x=(this.state.columns.length*140)
            }
            y=parseInt(containerStyle.height,10)-header_height
        }
        const container = (
            <div>
                <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-pivot-print-btn" onClick={this.reportPrint.bind(this)}>打印</Button> : null
                    }
                </div>
                <TdCmpName visible={showName} title={this.state.reportName} />
                <div className="td-cmp-content pivot-content-container" >
                    <div>
                    {
                        this.state.filter.length ? <Row>
                            <Col span={21}><Tabs
                                tabPosition='top'
                                style={{ height: 110 }}
                            >
                                {
                                    this.state.filter.map((item) => {
                                        return <TabPane tab={item.value} key={item.id}><TabPaneContent
                                            id={item.id}
                                            arr={item.filterArr}
                                            setSelected={this.setSelected}></TabPaneContent></TabPane>
                                    })
                                }
                            </Tabs></Col>
                            <Col span={3} style={{ position: 'relative' }}>
                                <Row>
                                    <Col span={8} offset={8}><Button type="primary" className='button-center' onClick={this.preview}>刷新</Button></Col>
                                </Row>
                            </Col>
                        </Row> : null
                    }
                    {
                        showSearchParams && this.state.searchParams.length ? <SearchFields selec_data={this.state.selec_data} searchParams={this.state.searchParams} onSearch={this.onSearch.bind(this)} /> : null
                    }
                    {
                        this.state.detailModalVisible ? <DetailModal {...this.props} {...this.state} showExport={showExport} searchParams={this.state.searchParams.concat(this.state.dataFilterParams)} dataLink={this.state.dataLink} closeDetailModal={this.closeDetailModal} detailKey={this.state.detailKey} columnKey={this.state.columnKey} row={this.state.row} col={this.state.col} filter={this.state.filter} selectedVal={this.state.selectedVal} counterItem={this.state.counterItem} id={this.state.id} siderWidth={this.state.siderWidth}></DetailModal> : null
                    }
                    <Modal
                        closable={true}
                        visible={me.state.fullScreenBool}
                        onCancel={(e)=>me.closeFullScreenModal(e)}
                        width={document.body.clientWidth-20}
                        height={document.body.clientHeight}
                        style={{"top":0}}
                        className="fullScreenModal"
                        bodyStyle={{"width":document.body.clientWidth-20,"height":document.body.clientHeight,"overflow":"auto"}}
                        footer={null}
                        >
                        <div className="report-preview" id={me.state.fullScreenDom} ></div> 
                    </Modal>
                    <div className="pivot-table-content-container" id={this.state.timeStamp} style={containerStyle}>
                        {
                            this.props.moduleType==="portal"?
                            <Table className='table-content' style={{"borderBottom":"1px solid #e9e9e9"}} columns={this.state.columns} dataSource={this.state.tableData} pagination={false} onExpand={this.onExpand}  bordered  scroll={{ y:y,x:x}} />
                            :
                            <Table className='table-content' style={{"borderBottom":"1px solid #e9e9e9"}} columns={this.state.columns}  dataSource={this.state.tableData} expandable={{expandedRowKeys:this.state.expandedRowKeys,defaultExpandedRowKeys:[]}} pagination={false} onExpand={this.onExpand}  bordered  scroll={{ y: y ,x:x}} useFixedHeader/>
                        }
                    </div>
                    </div>
                </div>
            </div>
        )
        let rep_name = this.state.reportName ? this.state.reportName : ''
        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>
    }
}

export default Pivot
