import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import { Row, Col, Pagination, Button, Menu, Dropdown, Icon, message, Alert, Spin } from 'antd'
import TdCmpName from '../common/TdCmpName'
import SearchFields from '../common/searchfields/'
let Handsontable = require('handsontable');
import './handsontable.css'

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,
            name: "",
            rep_data: [],
            rep_config: {
                manualColumnResize: "true",
                manualRowResize: "true",
                colWidths: [],
                rowHeights: [],
                mergeCells: []
            },
            db: '',
            guid: "",
            cache_span: '',
            rep_data_new: 2, 
            total:50,
            page:1,
            count:[],
            searchParams:[],
            showElIdRef : "preview" + Math.random().toString() + "",
            selec_data:[],
            link_type: props.linkType?true:false,
            slot:props.slot?props.slot:{}
        }
    }
    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)}`;
        } 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)}`;
        }
    }

    //明细表打印
    reportPrint() {
        let data = {
            id: this.props.reportId,
            type: 'Yes',
            category: 'html',
            print: 1,
            searchParams: this.state.searchParams
        }
        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);
            }
        })
    }

    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 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">
                    {
                        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>
                                {
                                    me.state.total > 0 ? <Pagination pageSize={20} current={me.state.page} onChange={this.onChange.bind(this)} total={me.state.total} />:null
                                }
                            </div>
                        </Col>
                        </Row>
                    </Col>
                </Row>
            </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.updateData({
                page: 1,
                type: 'Yes',
                cacheType: false
            })
        })
    }
    onChange(page){
        this.setState({
            page
        })
        this.updateData({
            page: page,
            type: 'Yes',
            cacheType: true
        })
    }
    handlerCalc(){
        this.updateData({
            page: 1,
            type: 'count',
            cacheType: false
        })
    }
    componentDidMount(){
        this.initInstance()
        let firstLoad = true
        this.getShowData({
            page: 1,
            type: 'Yes',
            cacheType: false
        })
    }
    initInstance(){
        const me = this
        let { rep_data_new, rep_data, rep_config, name } = this.state
        const container = document.getElementById(me.state.showElIdRef);
        Handsontable.renderers.registerRenderer('negativeValueRenderer', negativeValueRenderer);
        this.instance = new Handsontable(container, {
            data: rep_data,
            readOnly: true,
            mergeCells:rep_config.mergeCells,
            colWidths:rep_config.colWidths,
            rowHeights:rep_config.rowHeights,
            className: "htCenter htMiddle",
            autoColumnSize:true,
            viewportColumnRenderingOffset:100,
            fillHandle:false,
            viewportRowRenderingOffset:100,
            cells: function (row, col, prop) {
                var cellProperties = {};
                cellProperties.renderer = "negativeValueRenderer";
                return cellProperties;
            },
        });

        setTimeout(() => {
            me.adjustStyleCenter();
        }, 500);
    }
    updateData(params){
        const me = this
        const reportId = this.props.reportId
        const { link_type, slot } = this.state
        let { page,type,cacheType } = params
        let { searchParams } = this.state
        jQuery.ajax({
            method: "post",
            url: "/general/appbuilder/web/report/replist/showdata",
            data: { 
                id: reportId, 
                type: type, 
                page: page, 
                cacheType: cacheType,
                pageSize:20,
                searchParams:JSON.stringify(searchParams),
                link_type:link_type,
                slot:slot
            },
            async: false
        }).done(function (response) {
            const { status, data } = response
            if (status != 'ok') {
                me.setState({
                    isError: true,
                    loading: false,
                    errorText: response.msg ? response.msg : '请求该明细表数据失败！'
                })
                message.error(response.msg)
            } else {
                let {
                    name,
                    rep_data,
                    rep_config,
                    db,
                    guid,
                    cache_span,
                    rep_data_new, 
                    total,
                    data_type,
                    page,
                    count,
                    searchParams,
                    selec_data,
                    open_number
                } = data
                
                rep_data = rep_data ? rep_data : [];
                rep_config = rep_config ? rep_config : {};
                if(open_number!==undefined&&open_number===true){//判断是否开启编号
                    rep_config.cell.forEach(function(item,index){
                        item.col+=1;
                    })
                }
                myRepDetailNewDataBegin = rep_data_new
                let newdata = rep_data_new //报表数据的新数据起始行数
                let datalenght = rep_data.length //报表数据的新数据行数
                let predata = rep_data//报表数据
                let temdata = []//报表数据的新数据
                if((datalenght - newdata -1 ) > 0 ){
                    for(let i= newdata;i<datalenght;i++){
                        temdata.push(predata[i])
                    }
                }
                let rowtocoldata = getPreNewData(temdata)//报表数据的新数据行转换为列
                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,newdata)//报表数据的新数据的合并信息装换为合并配置数据
                let orgmergeCells = rep_config.mergeCells
                let premergeCells = megreconfig
                let mergeCellsConfig = orgmergeCells.concat(premergeCells)

                const container = document.getElementById('preview');
                Handsontable.renderers.registerRenderer('negativeValueRenderer', negativeValueRenderer);

                let params2 = {
                    data : rep_data,
                    config : data_type,
                    begin : rep_data_new
                }
                let dataSource2 = handleDataToOuYuan(params2);
                let  newObject = JSON.parse(JSON.stringify({
                    data:dataSource2,
                    mergeCells:mergeCellsConfig
                }))
                let dataSource4=newObject.data
                let mergeCells2=newObject.mergeCells
                if(open_number!==undefined&&open_number===true){//判断是否开启编号
                    dataSource4.forEach(function(item,index){
                        if(index>=rep_data_new){
                            item.unshift((index-rep_data_new+1)+((page-1)*20))//添加编号
                        }else{
                            item.unshift("")//
                        }
                    })
                    mergeCells2.forEach(function(item,index){
                        item.col+=1;
                    })
                }
                me.instance.updateSettings({
                    data: dataSource4,
                    readOnly: true,
                    mergeCells:mergeCells2,
                    colWidths:rep_config.colWidths,
                    rowHeights:rep_config.rowHeights,
                    className: "htCenter htMiddle",
                    autoColumnSize:true,
                    viewportColumnRenderingOffset:100,
                    fillHandle:false,
                    viewportRowRenderingOffset:100,
                    comments: true,
                    cell: rep_config.cell || [],
                    cells: function (row, col, prop) {
                        var cellProperties = {};
                        cellProperties.renderer = "negativeValueRenderer";
                        return cellProperties;
                    },
                 })
                me.adjustStyleCenter()
                me.setState({
                    name,
                    rep_data,
                    rep_config,
                    db,
                    guid,
                    cache_span,
                    rep_data_new, 
                    total,
                    page,
                    count,
                    loading: false,
                    selec_data
                })   
            }
        }).fail(function (e) {
            me.setState({
                isError: true,
                errorText: e.responseText,
                loading: false
            })
        });
    }

    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 { link_type, slot } = this.state
        let { page,type,cacheType } = params
        jQuery.ajax({
            method: "post",
            url: "/general/appbuilder/web/report/replist/showdata",
            data: { 
                id: reportId, 
                type: type, 
                page: page, 
                cacheType: cacheType,
                pageSize:20,
                link_type:link_type,
                slot:slot
            },
            async: false
        }).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, 
                    total,
                    page,
                    data_type,
                    count,
                    searchParams,
                    selec_data,
                    open_number
                } = data
                
                rep_data = rep_data ? rep_data : [];
                rep_config = rep_config ? rep_config : {};
                if(open_number!==undefined&&open_number===true){//判断是否开启编号
                    rep_config.cell.forEach(function(item,index){
                        item.col+=1;
                    })
                }
                myRepDetailNewDataBegin = rep_data_new
                let newdata = rep_data_new //报表数据的新数据起始行数
                let datalenght = rep_data.length //报表数据的新数据行数
                let predata = rep_data//报表数据
                let temdata = []//报表数据的新数据
                if((datalenght - newdata -1 ) > 0 ){
                    for(let i= newdata;i<datalenght;i++){
                        temdata.push(predata[i])
                    }
                }
                let rowtocoldata = getPreNewData(temdata)//报表数据的新数据行转换为列
                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,newdata)//报表数据的新数据的合并信息装换为合并配置数据
                let orgmergeCells = rep_config.mergeCells
                let premergeCells = megreconfig
                let mergeCellsConfig = orgmergeCells.concat(premergeCells)

                let params1 = {
                    data : rep_data,
                    config : data_type,
                    begin : rep_data_new
                }
                let dataSource1 = handleDataToOuYuan(params1);
                let  newObject = JSON.parse(JSON.stringify({
                    data:dataSource1,
                    mergeCells:mergeCellsConfig
                }))
                let dataSource4=newObject.data
                let mergeCells2=newObject.mergeCells
                if(open_number!==undefined&&open_number===true){//判断是否开启编号
                    dataSource4.forEach(function(item,index){
                        if(index>=rep_data_new){
                            item.unshift((index-rep_data_new+1)+((page-1)*20))//添加编号
                        }else{
                            item.unshift("")//
                        }
                    })
                    mergeCells2.forEach(function(item,index){
                        item.col+=1;
                    })
                }
                    
                const container = document.getElementById('preview');
                Handsontable.renderers.registerRenderer('negativeValueRenderer', negativeValueRenderer);
                me.instance.updateSettings({
                    data: dataSource4,
                    readOnly: true,
                    mergeCells:mergeCells2,
                    colWidths:rep_config.colWidths,
                    rowHeights:rep_config.rowHeights,
                    className: "htCenter htMiddle",
                    autoColumnSize:true,
                    viewportColumnRenderingOffset:100,
                    fillHandle:false,
                    viewportRowRenderingOffset:100,
                    comments: true,
                    cell: rep_config.cell || [],
                    cells: function (row, col, prop) {
                        var cellProperties = {};
                        cellProperties.renderer = "negativeValueRenderer";
                        return cellProperties;
                    },
                 })
                me.adjustStyleCenter()
                let newSearchParams = searchParams.filter(function (elem) {
                    if(elem.type_of_reports === 'search'){
                        return elem;
                    }
                })
                me.setState({
                    name,
                    rep_data,
                    rep_config,
                    db,
                    guid,
                    cache_span,
                    rep_data_new, 
                    total,
                    page,
                    count,
                    searchParams:newSearchParams,
                    loading: false,
                    selec_data,
                    open_number
                })   
            }
        }).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 = 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 = 'undefinedasdasdsaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
		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 = [] 
    if(data){
        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
}