import React, { Component } from 'react'
import "./chart.css"
import { message, Button, Row, Col, Menu, Dropdown, Icon, Spin, Alert,Checkbox,Modal,Select,Table } from "antd"
import TdCmpName from '../common/TdCmpName'
import SearchFields from '../common/searchfields/'
import DetailModal from "./DetailModal"
import { Highcharts } from "react-highcharts"
import HighchartsMore from "./highcharts/highcharts-more"
import HighchartsGroupedCategories from "./highcharts/grouped-categories"
import screenCategories from "./highcharts/screenCategories"
let Option= Select.Option;

var ReactHighcharts = require('react-highcharts');
// Highcharts exporting
var HighchartsExporting = require('highcharts-exporting');
HighchartsExporting(ReactHighcharts.Highcharts);
var HighchartsExportingCsv = require('highcharts-export-csv');
HighchartsExportingCsv(ReactHighcharts.Highcharts);
var HighchartsOfflineExporting = require('highcharts-offline-exporting')
HighchartsOfflineExporting(ReactHighcharts.Highcharts);
HighchartsGroupedCategories(Highcharts)
HighchartsMore(Highcharts)
window.Highcharts_chart=Highcharts

class Chart extends Component {
	constructor(props) {
		super(props)
		this.state = {
            loading: true,
            isError: false,
            errorText: '',
			detailModalVisible: false,
			mostWidth: 1,
			direction: "",
            rep_name: '',
            res: [],
            chart_type: '',
            x_axis_fields: [],
            y_axis_fields: [],
            i_dataset: '',
            forecolor_value:'',
            tableData: [],
            searchParams: [],
            selec_data:[],
            category_fileds: '',
            series_fields: '',
            cache_span: '',
            method:[],
            dataType:[],
            currentClickInfo: null,
            showElIdRef: "reportPreviewWrapper" + Math.random().toString() + "",
            dataFilterParams:[],
            link_type: props.linkType?true:false,
            slot:props.slot,
            dataLink:[],
            rename_filed:{},
            drilldownPrivince:"",//下钻的省份或者市
            mapBreadcrumbBool:false,
            mixedMapModal:false,//混合图的字段选择弹框
            mixedMapSeriesTypeLines:[],//将数组里面的字段设置为混合图中对应的折线图
            columns:[],
            currentTableData:[],
            oldSize:{},
            fullScreenDom:  new Date().getTime().toString(),
            portal_data_link:[],
            portal_rep_link:[]

        },
        this.forecolor_array = [
            ['#2f7ed8', '#e0522f', '#ffcc00', '#10cca6', '#6bb61d', '#f2a21a', '#ff7372', '#a5e8d2', '#9ce810', '#fff80a', '#1dcfab', '#858e54'],
            ['#138cdd', '#fda122', '#ff7372', '#4ebff9', '#8bcb2e', '#a97aca', '#b3e7d6', '#fce997', '#fcdaaa', '#fed2de', '#5f9baf', '#dd0ab2'],
            ['#bb1d48', '#5435ae', '#ffcc00', '#e0522f', '#6bb61d', '#2e8bef', '#a97aca', '#f59bb3', '#2ecb70', '#f2c40f', '#8f6f4d', '#ff8947'],
            ['#0e94db', '#ffbf01', '#6ab206', '#128ece', '#f13158', '#f86031', '#8350c6', '#bbde5b', '#dea15b', '#77bfd1', '#c6868e', '#aab300'],
            ['#9b0d27', '#fe9721', '#0e94db', '#e87a69', '#000000', '#ffff00', '#90c543', '#428190', '#b5634b', '#c1de34', '#e30450', '#654458']
        ]
        this.myRepChartInstance = null
	}
	closeDetailModal = () => {
		this.setState({
			detailModalVisible: false
		})
    }
    openMixedMapModal=(e)=>{//打开混合图选择弹框
        
        this.setState({
			mixedMapModal: true
		})
    }
    closeMixedMapModal=(e)=>{//关闭混合图选择弹框
        this.setState({
			mixedMapModal: false
		})
    }
    onChangehandle=(e)=>{ //
        let {
			mixedMapSeriesTypeLines
        } = this.state;
       
        let mixedArray =[];
        let isCheckNull=0;
        mixedMapSeriesTypeLines.forEach((v,i) => {
            let obj=Object.assign({}, v);
            if(v.field_name===e.target.value){
                obj.selected=e.target.checked;
            }
            if(obj.selected){
                isCheckNull++; 
            }
            mixedArray.push(obj) 
        })
        if(isCheckNull===0){
            message.info("混合图字段设置不能为空");
            return;
        }
        if(mixedArray.length===isCheckNull){
            message.info("混合图不能将所有字段全部设置为折线类型")
            return;
        }
        this.setState({
            mixedMapSeriesTypeLines:mixedArray
        })
        this.getData();

        
    }
	initInstance() {
        this.myRepChartInstance = null
        if(document.getElementById(this.state.showElIdRef)){
            this.myRepChartInstance = new Highcharts.Chart(this.state.showElIdRef, { ...setting })	
        }
        this.adjustChart()	
    }
    adjustChart(){
        let me=this
        function adjustStyle(){
            if(me.props.style){
                let width1= parseInt(me.props.style.width,10)   //容器的宽度
                let height =me.myRepChartInstance.chartHeight  
                // let width =me.myRepChartInstance.chartWidth
                let width=parseInt(document.getElementById(me.state.showElIdRef).style.width)
                let {chart_type}=me.state
                if(chart_type==="5"||chart_type==="1"||chart_type==="6" || chart_type==="7" || chart_type==="14" || chart_type==="2"|| chart_type==="9"|| chart_type==="10" ){
                    width=me.myRepChartInstance.chartWidth
                }
                let height1 =parseInt(me.props.style.height,10)  //容器的高度
                let element=document.getElementById(me.state.showElIdRef)
                if(chart_type==="3"||chart_type==="4"){
                    height=  me.state.res.length*40
                }
                if(height<=height1){  // 容器的高度大于 自身高度  以容器高度为准  
                    height=height1
                }else{
                    $(element).parent().css({"overflow-y":"scroll"})
                }
                if(width<=width1){ // 容器的宽度大于 自身宽度  以容器宽度为准  
                    width=width1
                }else{
                    $(element).parent().css({"overflow-x":"scroll"})
                }
                me.myRepChartInstance.setSize(width-30,height-55,false)
                $(element).parent().height(height1-40).width(width1)
            }
        }
        if(document.getElementById(this.state.showElIdRef)){  // 先判断  当前需要渲染的dom 是否存在
            if(this.props.moduleType==="portal"){
                // let width=this.state.res.length*40;
                adjustStyle(me)
            // }else if($("#root .main")&& $("#root .main").height()){
            }else{
                let element=document.getElementById(me.state.showElIdRef)
                let {chart_type}=me.state
                let height=this.myRepChartInstance.chartHeight
                let width=this.myRepChartInstance.chartWidth
                let width1=$("#root .main").width() || $("#chart1").width()
                let height1=$("#root .main").height() || $("#chart1").height()
                if(this.state.searchParams.length){
                    height1=height1-80-120
                    document.getElementById(me.state.showElIdRef).style.height= height1+"px";
                }else{
                    height1=height1-80
                    document.getElementById(me.state.showElIdRef).style.height= height1+"px";
                }
                if(chart_type==="3"||chart_type==="4"){
                    height=me.state.res.length*40
                    if(height<height1){  // height1容器的高度大于 height自身高度  以容器高度为准 
                        height1=height1
                    }else{
                        height1=height
                    }
                    $(element).parent().css({"height":height1})

                }
                if(width<=width1){ // 容器的宽度大于 自身宽度  以容器宽度为准  
                    width=width1
                    $(element).parent().css({"overflow-x":"auto"})

                }else{
                    $(element).parent().css({"overflow-x":"scroll"})
                }
                
                this.myRepChartInstance.setSize(width-20,height1-10,false)
                $(element).parent().css({"width":"100%"})
            }
	
        }else {
            let  chartTimer=setInterval(() => {
                if(document.getElementById(me.state.showElIdRef)){
                    me.myRepChartInstance = new Highcharts.Chart(me.state.showElIdRef, { ...setting })
                    if(this.props.moduleType==="portal"){
                        adjustStyle(me)
                    }
                    clearInterval(chartTimer)		
                }else if($("#root .main")&& $("#root .main").height()&&document.getElementById(me.state.showElIdRef)){
                    let height=$("#root .main").height()
                    if(this.myRepChartInstance&&this.myRepChartInstance.chartHeight){
                        height=this.myRepChartInstance.chartHeight
                    }
                    if(this.state.searchParams.length){
                        height=$("#root .main").height()-80-120
                        document.getElementById(me.state.showElIdRef).style.height= height+"px";
                    }else{
                        height=$("#root .main").height()-80
                        document.getElementById(me.state.showElIdRef).style.height= height+"px";
                    }
                    this.myRepChartInstance.setSize(this.myRepChartInstance.chartWidth,height,false)
                }
            }, 1000);
        }
    }
    getClickInfo(obj, callback){
        const me = this
        let { 
            reportInfo
        } = this.state
        jQuery.post('/general/appbuilder/web/report/repchart/data', {
            ...obj
        }, (response) => {
            let tableData = JSON.parse(response)
            let nextReportInfo = {...reportInfo}
            nextReportInfo['tableData'] = tableData
            me.setState({
                reportInfo: nextReportInfo
            })
            callback && callback()
        })
    }
    returnChainMap(e){
        this.setState({
            mapBreadcrumbBool:false
        })
        this.setState({
            drilldownPrivince:"china"
        })      
        this.getData();
    }
    handleExportMenuClick(e) {
        // if(this.state.chart_type==="15"){
        //     this.myRepChartInstance=this.state.myRepChartXrange;
        // }else if(this.state.chart_type==="13"){
        //     this.myRepChartInstance=this.state.myRepChartMap;
        // }
		if(e.key ==='1'){
            // window.location.href = `/general/appbuilder/web/report/repchart/export?id=${this.props.reportId}&category=excel&method=${JSON.stringify(this.state.method)}&searchParams=${JSON.stringify(this.state.searchParams.concat(this.state.dataFilterParams))}`;
            //由于get在IE下面提交字符限制,修改成post
            let data = {
                id: this.props.reportId,
                category:"excel",
                method:this.state.method,
                searchParams:this.state.searchParams.concat(this.state.dataFilterParams)
            }
            
            jQuery.post('/general/appbuilder/web/report/repdetail/getquerykey', { ...data }, function (res) {
                console.log(res)
                window.location.href = `/general/appbuilder/web/report/repchart/export?key=`+res            
            })
        }else if(e.key === '2'){
            if(this.myRepChartInstance.exportChartLocal){
                this.myRepChartInstance.exportChartLocal({
                    type: 'image/png'
                });
            }
		}else if (e.key === '3') {
            if(this.myRepChartInstance.exportChartLocal){
                this.myRepChartInstance.exportChartLocal({
                    type: 'image/svg+xml'
                });
            }
		}
    }
    setChartType(type){
        
        if(type==="0"){
            this.setState({
                currentChartType:type,
                chart_type:type,
            })
        }else{
            this.setState({
                chart_type:type,
                currentChartType:type,
            },()=>{
                this.renderChart(this.state.currentTableData)
            })
        }
    }
    fullScreen(){// 全屏显示
        this.setState({
            fullScreenBool:true
        })
        let me=this;
        setTimeout(() => {
            // this.myRepChartInstance = null
            // if(me.state.chart_type==="13"){  //地图
            //     me.myRepChartInstance  = window.Highcharts.mapChart(this.state.showElIdRef,mapConfig)
            // }else if(me.state.chart_type==="15"){  //甘特图
            //     me.myRepChartInstance  = window.Highcharts.chart("fullScreenChart",setting)                    
            // }else{
            //     me.myRepChartInstance = new Highcharts.Chart("fullScreenChart", { ...setting })	
            // }
            let oldSize={
                height:me.myRepChartInstance.chartHeight,
                width:me.myRepChartInstance.chartWidth,
            }
            me.setState({
                oldSize
            })
            let  width=document.body.clientWidth-50
            let  height=document.body.clientHeight-60
            if(width<oldSize.width){
                width=oldSize.width
            }
            if(height<oldSize.height){
                height=oldSize.height
            }
            me.myRepChartInstance.setSize(width,height,false)
            document.getElementById(me.state.fullScreenDom).appendChild(me.myRepChartInstance.container)
        });
        

    }
    closeFullScreenModal(){
        let {
            oldSize:{
                width,
                height
            }
        }=this.state
        let me=this
        this.myRepChartInstance.setSize(width,height,false)
        document.getElementById(me.state.showElIdRef).appendChild(me.myRepChartInstance.container)
        this.setState({
            fullScreenBool:false
        })

    }
    reportPrint(){
        if(window.top.dd&&window.tMobileSDK.printReport){
            let url='/general/appbuilder/web/report/repdetail/view/?type=2&report_id='+this.props.reportId
            tMobileSDK.printReport(url) 
            return;
        }
        this.myRepChartInstance.print()
    }
	render() {
        const me = this
        let  {
            mixedMapSeriesTypeLines,
            chart_type
        }=me.state
        const exportMenu = (
			<Menu onClick={this.handleExportMenuClick.bind(this)}>
                <Menu.Item className="ui-chart-export-excel" key="1">导出Excel文件</Menu.Item>
				<Menu.Item className="ui-chart-export-png" key="2">导出PNG图片</Menu.Item>
				<Menu.Item className="ui-chart-export-svg" key="3">导出SVG文件</Menu.Item>
			</Menu>
        );
        Highcharts.setOptions({
			allowHTML: true,
			lang: {
				// printChart: '打印图表',
				// downloadJPEG: '下载 JPEG 文件',
				// downloadPDF: '下载 PDF   文件',
				// downloadPNG: '下载 PNG  文件',
				// downloadSVG: '下载 SVG  文件',
				// downloadCSV: '下载 CSV  文件',
				// downloadXLS: '下载 XLS   文件',
				// viewData: '查看数据表格'
			},
			navigation: {
				buttonOptions: {
					enabled: false
				}
			},
			exporting: {
				chartOptions: { // specific options for the exported image
					plotOptions: {
						series: {
							dataLabels: {
								enabled: true
							}
						}
					}
				},
				fallbackToExportServer: false
			},
        });
        
		let obj = {
        }
		if(this.state.direction!=""&&this.state.direction=="width"){
			obj = {"width":`${this.state.mostWidth*16}px`,"height":"100%","minWidth":"100%","paddingTop":"5px"}
		}
		if(this.state.direction!=""&&this.state.direction=="height"){
			obj = {"height":`${this.state.mostWidth*16}px`,"width":"100%","minWidth":"100%","paddingTop":"5px"}
		}
		if(this.state.direction!=""&&this.state.direction=="normal"){
			obj = {"width":"100%","height":"100%","minWidth":"100%","paddingTop":"5px"}
        }
        
        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
        if($("#root .main")&&$("#root .main").height()){
            if(this.state.searchParams.length){
                obj.height= $("#root .main").height()-80-120+"px";
            }else{
                obj.height= $("#root .main").height()-80+"px";
            }

        }
        if(this.props.style){
            if(this.props.style.width){
                obj.width=parseInt(this.props.style.width)-20+"px"
            }
            if(this.props.style.height){
                obj.height=parseInt(this.props.style.height)-55+"px"
            }
        }
        obj.boxSizing="border-box"
		const container = (
            <div>
                <div className="td-cmp-option">
                    <div style={{"float":"left","width":"250px","height":"28px"}}>
                    {
                          this.state.mapBreadcrumbBool ? 
                          <div style={{"paddingLeft":"20px","textAlign":"left"}}>
                              <span style={{"color":"blue","cursor":"pointer"}} onClick={(e)=>this.returnChainMap(e)} >全国</span>
                              <span> / {this.state.drilldownPrivince_field}</span>
                          </div>
                          :null
                    }
                    
                    </div> 
                  
                    <div style={{"float":"right"}}>
                        {/* {
                            chart_type==="14"?
                            <img className="" src="/static/modules/appbuilder/report/repchart/images/mixed_toggle.png" onClick={(e)=>this.openMixedMapModal(e)} style={{"width":"25px","height":"25px","cursor":"pointer","verticalAlign":"middle"}}/>
                                // <i className="anticon anticon-clock-circle-o " onClick={(e)=>this.openMixedMapModal(e)} style={{"fontSize":"16px","cursor":"pointer","verticalAlign":"middle"}}></i>
                            :null
                        } */}
                        {
                            // chart_type==="13" || chart_type==="15"?null:
                            // <Select 
                            //     value = {this.state.currentChartType}
                            //     onChange={(value) => {this.setChartType(value) }}
                            //     style={{"width":"86px"}}
                            //     title="图标类型"
                            // >
                            //     <Option value="1">柱状图</Option>
                            //     <Option value="2">栈柱状图</Option>
                            //     <Option value="3">条形图</Option>
                            //     <Option value="4">栈条形图</Option>
                            //     <Option value="5">曲线图</Option>
                            //     <Option value="6">面积图</Option>
                            //     <Option value="7">栈面积图</Option>
                            //     <Option value="8">饼图</Option>
                            //     <Option value="9">散点图</Option>
                            //     <Option value="10">气泡图</Option>
                            //     <Option value="11">雷达图</Option>
                            //     <Option value="14">混合图</Option>
                            //     {/* <Option value="0">表格</Option> */}
                            // </Select> 
                        }   
                        
                        <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-chart-print-btn' onClick={() => { me.reportPrint(); }}>打印</Button>:null
                        }
                    </div>
                   
                </div>
                <TdCmpName visible={showName} title={this.state.rep_name} />
                <div style={{"width":"100%","margin":"0 auto"}}>
                {
                    showSearchParams && this.state.searchParams.length ? <SearchFields selec_data={this.state.selec_data} searchParams={this.state.searchParams} onSearch={this.onSearch.bind(this)} /> : null
                }
                </div>
                <div className="td-cmp-content" style={{"margin":"0"}}>
                    {
                        this.state.currentChartType==="0"?
                        null
                        // <Table  style={{"margin":"0 auto","width":this.state.mostWidth * 10}} className = "detail-table" columns={this.state.columns} dataSource={this.state.currentTableData}  bordered  />
                        :<div className="report-preview" id={this.state.showElIdRef} style={obj}></div>
                    }
                    
                    {
                        this.state.detailModalVisible ? <DetailModal {...this.props} showExport={showExport} closeDetailModal={this.closeDetailModal} {...this.state}></DetailModal> : null
                    }
                </div>
                <Modal
					closable={true}
					visible={me.state.fullScreenBool}
                    onCancel={(e)=>me.closeFullScreenModal(e)}
                    width={document.body.clientWidth-20}
                    height={document.body.clientHeight}
                    style={{"top":0}}
                    bodyStyle={{"width":document.body.clientWidth-20,"height":document.body.clientHeight,"overflow":"auto"}}
                    footer={null}
					>
                      <div className="report-preview" id={me.state.fullScreenDom} ></div> 
				</Modal>
                
                <Modal
					title="混合图选择图型"
					closable={true}
					visible={me.state.mixedMapModal}
					onCancel={(e)=>me.closeMixedMapModal(e)}
					footer={[
						<Button key="back" size="large" onClick={(e)=>me.closeMixedMapModal(e)}>取消</Button>,
						<Button key="submit" type="primary" size="large" onClick={(e)=>me.closeMixedMapModal(e)}>
						确定
						</Button>
					]}>
                    {/* <Checkbox.Group style={{ width: '100%' }} > */}
                        <Row>
                        <Col span={24} key="tip">将以下字段设置为折线图</Col>

                            {
                                mixedMapSeriesTypeLines&&mixedMapSeriesTypeLines.map((item,key)=>(
                                    <Col span={24} key={key}><Checkbox value={item.field_name} defaultChecked={item.defaultChecked} checked={item.selected} onChange={me.onChangehandle}>{item.field_name}</Checkbox></Col>
                                ))
                            }
                        </Row>
                    {/* </Checkbox.Group> */}
				</Modal>
			</div>
        )
        let rep_name = this.state.rep_name ? this.state.rep_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,
            loading:true
        },()=>{
            this.getData()
        })
    }
	componentDidMount() {
        // window.Highcharts=null;
        this.myRepChartInstance=null;
        this.getReportInfo(this.props.reportId);
    }
    componentWillReceiveProps(next){
        let linkdata=next.linkdata
        if(linkdata){
            this.setState({
                linkdata:linkdata
            })
        }
        if(next.reportId!==this.props.reportId){
            this.getReportInfo(this.props.reportId);
        }else{
            this.getData({
                linkdata:linkdata
            })
        }
        
    }
    getReportInfo = (id) => {
        const me = this
        let slot = me.state.slot
        let link_type = me.state.link_type
        jQuery.post('/general/appbuilder/web/report/repchart/fetch', {
            id,
            slot,
            link_type,
            myrep: !!1
        }, (response) => {
            let res = JSON.parse(response)
            if(res.status=="ok") {
                let {
                    category_fileds,
                    series_fields,
                    dataset_id,
                    chart_type,
                    cache_span,
                    theme: forecolor_value,
                    name: rep_name,
                    data_type,
                    searchParams,
                    selec_data,
                    rename_filed,
                    data_link,
                    map,//地图的省市区字段
                    formula,//计算字段
                    portal_data_link,//门户关联
                    portal_rep_link,// 关联字段状态
                } = res.data
                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;
                    }
                })
                
                me.setState({
                    category_fileds,
                    series_fields,
                    i_dataset: dataset_id,
                    chart_type,
                    currentChartType:chart_type,
                    cache_span,
                    dataType:data_type?data_type:[],
                    forecolor_value,
                    rep_name,
                    searchParams: newSearchParams,
                    selec_data:selec_data,
                    dataFilterParams: newDataFilterParams,
                    loading: false,
                    dataLink: data_link ? data_link :[],
                    rename_filed:rename_filed?rename_filed:{},
                    map:map,
                    formula:formula,
                    portal_data_link:portal_data_link,
                    portal_rep_link:portal_rep_link,
                })
                if(category_fileds===""&&series_fields.length===0){
                    me.setState({
                        loading: false,
                        isError: true,
                        errorText: "请选择至少一种分类或图例"
                    })
                    message.error("请选择至少一种分类或图例")
                    return;
                }else{
                    let columns=[];
                    category_fileds&&category_fileds.split(",").forEach(function(item){
                        let obj={
                            title: item,
                            dataIndex: item,
                            key: item,
                        }
                        columns.push(obj)
                    })
                    series_fields.forEach(function(item){
                        let obj={
                            title: item.field_name,
                            dataIndex: item.field_name,
                            key: item.field_name,
                        }
                        columns.push(obj)
                    })
                    this.setState({
                        columns:columns 
                    })
                }
                me.getData()

            }else{
            	if(res.status=="error"){
            		 me.setState({
                    isError: true,
                    errorText: res.message,
                    loading: false
                })
            	}else{
            		 me.setState({
                    isError: true,
                    errorText: "获取报表信息格式错误",
                    loading: false
                })
            	}
               
            }
        }).catch((error) => {
            me.setState({
                loading: false,
                isError: true,
                errorText: e.responseText
            })
        })
       
    }
    renderChart(res){
        const me = this
        const t = this;
        let {
            category_fileds,
            series_fields,
            i_dataset,
            chart_type,
            cache_span,
            forecolor_value,
            rep_name,
            searchParams,
            dataFilterParams,
            dataType,
            map,
            formula
        } = this.state
        
        
        
        let chartIdType = [
            {
                "id": 1, 
                "type": "column"
            }, 
            {
                "id": 2, 
                "type": "stack_column"
            }, 
            {
                "id": 3, 
                "type": "bar"
            }, 
            {
                "id": 4, 
                "type": "stack_bar"
            }, 
            {
                "id": 5, 
                "type": "line"
            }, 
            {
                "id": 6, 
                "type": "area"
            }, 
            {
                "id": 7, 
                "type": "stack_area"
            }, 
            {
                "id": 8, 
                "type": "pie"
            }, 
            {
                "id": 9, 
                "type": "scatter"
            }, 
            {
                "id": 10, 
                "type": "bubble"
            }, 
            {
                "id": 11, 
                "type": "polar"
            }, 
            {
                "id": 12, 
                "type": "gauge"
            },
            {
                "id": 13, 
                "type": "map"
            },
            {
                "id": 14, 
                "type": "mixed"
            },
            {
                "id": 15, 
                "type": "xrange"
            },
            {
                "id": 16, 
                "type": "wordcloud"
            },
            {
                "id": 17, 
                "type": "pyramid"
            },
        ]
        let chart;
        chartIdType.forEach((v, i) => {
            v.id == chart_type && (chart = v.type)
        })
        let x_axis_fields = category_fileds ? category_fileds.split(",") : [],
        y_axis_fields = series_fields ?  JSON.parse(JSON.stringify(series_fields)) : [];
        chart_type = chart;
        let direction = "";
        let element=document.getElementById(me.state.showElIdRef)
        
        if(res.length>0&&chart){
            if(chart_type == "column" || chart_type == "stack_column" || chart_type == "line" || chart_type == "area" || chart_type == "stack_area" || chart_type == "bubble"||chart_type == "scatter") {
                //修改宽度

                $(element).parent().css({
                    "width": res.length*40,
                    "height": "100%"
                })
                direction = "width"
            } else if(chart_type == "bar" || chart_type == "stack_bar") {
                //修改高度
                $(element).parent().css({
                    "height": res.length*40,
                    "width": "100%"
                })
                direction = "height"
            }else if(chart_type == "polar" || chart_type == "pie" || chart_type == "gauge"){
                direction = "normal"
               if(this.props.moduleType!=="portal"){
                $(element).parent().css({
                    "height": "100%",
                    "width": "100%"
                })
               }
            }else if(chart_type == "mixed"){
                //修改宽度
                $(element).parent().css({
                    "width": res.length*40,
                    "height": "100%"
                })
                direction = "width"
            }
        }
        //初始化设置字段别名
        let rename_filed=me.state.rename_filed;
            if(rename_filed&&rename_filed.counterItem_nick_name&&rename_filed.counterItem_nick_name.length>0&&y_axis_fields){
                for(let i=0;i<y_axis_fields.length;i++){
                    rename_filed.counterItem_nick_name.forEach((item, d) => {
                        if(item.label!=""&&item.value!=""){
                            if(y_axis_fields[i].field_name===item.label){
                                y_axis_fields[i].field_name=item.value;	
                            }
                        }
                    })

                }
            }
        let screenCategoriesArray = []; //需要分类的数据
        let normalCategoriesArray = []; //不需要分类的数据
        let highchartsCheck = {}; //判断highchart款高度需要的数组
        res.forEach((v, i) => {
            let arr = [];
            for(let k in v) {
                for(let xAxisKey in x_axis_fields) {
                    x_axis_fields[xAxisKey] == k && arr.push(v[k])
                }
                k == x_axis_fields[x_axis_fields.length - 1] && normalCategoriesArray.push(v[k])
            }
            screenCategoriesArray.push(arr)
        })

        let categories = screenCategories(screenCategoriesArray) //分类的categories数据
        ///////////////////利用数据判断highcharts的宽高////////////////////////////
        for(let i of screenCategoriesArray) {
            for(let k in i) {
                highchartsCheck[k] += i[k]
            }
        }
        let transitionWidth = 1
        for(let i in highchartsCheck) {
            transitionWidth < highchartsCheck[i].length && (transitionWidth = highchartsCheck[i].length)
        }
        let chartsData = []; //series数据
        let transitionArray = [];
        res && res.forEach((v, i) => {
            let a = {}
            for(let j in v) {
                a[j] = v[j]
            }
            transitionArray.push(a)
        })
        for(let i = 0; i < y_axis_fields.length; i++) {
            chartsData.push({
                name: y_axis_fields[i].field_name,
                data: [],
                cursor: "pointer"
            })
        }
        let mixedArray=[];
        if(me.state.mixedMapSeriesTypeLines.length===0){
                y_axis_fields.forEach((v,i) => {
                    let obj={};
                    if(i===0){
                        obj.selected=true;
                        obj.defaultChecked=true
                    }else{
                        obj.selected=false;
                    }
                    obj.field_name=v.field_name
                    mixedArray.push(obj)
                })
                me.setState({
                    mixedMapSeriesTypeLines:mixedArray
                })
        }
            transitionArray.forEach((dataV, i) => {
                for(let t in dataV) {
                    chartsData.forEach((v, i) => {
                        if(v.name == t) {
                            v.data.push(parseFloat(dataV[t]))
                        }
                    })
                }
            })
    /////////////////////////////////////图表数据处理//////////////////////////////////////////////
        setting.series = chartsData;
        setting.xAxis={
            tickmarkPlacement: "between",
            categories: null
        }
        setting.xAxis.categories = chart_type == "pie" || chart_type == "polar" || chart_type == "gauge" ? normalCategoriesArray : categories;
        //处理饼图
        if(chart_type == "pie" && normalCategoriesArray && setting.series) {
            let pieChartsData = [];
            for(let a = 0; a < normalCategoriesArray.length; a++) {
                pieChartsData.push([normalCategoriesArray[a]])
            }
            for(let b = 0; b < setting.series[0].data.length; b++) {
                pieChartsData[b].push(parseInt(setting.series[0].data[b]))
            }
            setting.series = [{
                type: "pie",
                data: pieChartsData,
                name:y_axis_fields[0].field_name
            }]
        }
        me.forecolor_array.forEach((v, i) => {
            i == forecolor_value && (setting.colors = v)
        });
        if(chart_type.indexOf("stack_") >= 0) {
            //判断堆叠图
            setting.chart.type = chart_type.replace("stack_", "");
            setting.plotOptions.series.stacking = "normal";
        } else {
            setting.plotOptions.series.stacking = null;
            setting.chart.type = chart_type;
        }
        //如果是极地图
        setting.chart.polar = chart_type == "polar" ? !0 : !1;
        if(chart_type != "pie") {
            setting.series && setting.series.forEach(v => {
                v.type = chart_type == "polar" ? "line" : ""
            })
        }
        if(chart_type == "gauge") {
            setting.pane = {
                startAngle: -150,
                endAngle: 150,
                background: [{
                    backgroundColor: {
                        linearGradient: {
                            x1: 0,
                            y1: 0,
                            x2: 0,
                            y2: 1
                        },
                        stops: [
                            [0, '#FFF'],
                            [1, '#333']
                        ]
                    },
                    borderWidth: 0,
                    outerRadius: '109%'
                }, {
                    backgroundColor: {
                        linearGradient: {
                            x1: 0,
                            y1: 0,
                            x2: 0,
                            y2: 1
                        },
                        stops: [
                            [0, '#333'],
                            [1, '#FFF']
                        ]
                    },
                    borderWidth: 1,
                    outerRadius: '107%'
                }, {
                    // default background
                }, {
                    backgroundColor: '#DDD',
                    borderWidth: 0,
                    outerRadius: '105%',
                    innerRadius: '103%'
                }]
            }

            setting.yAxis = {
                min: 0,
                max: 200,
                minorTickInterval: 'auto',
                minorTickWidth: 1,
                minorTickLength: 10,
                minorTickPosition: 'inside',
                minorTickColor: '#666',
                tickPixelInterval: 30,
                tickWidth: 2,
                tickPosition: 'inside',
                tickLength: 10,
                tickColor: '#666',
                labels: {
                    step: 2,
                    rotation: 'auto'
                },
                title: {
                    text: ''
                },
                plotBands: [{
                    from: 0,
                    to: 120,
                    color: '#55BF3B' // green
                }, {
                    from: 120,
                    to: 160,
                    color: '#DDDF0D' // yellow
                }, {
                    from: 160,
                    to: 200,
                    color: '#DF5353' // red
                }]
            }
        } else {
            setting.pane = {};
            setting.yAxis = {};
        }
        setting.plotOptions.series.events.mouseOver = function (e) {
            let { chart_type}=me.state
            if(this.chart.options.chart.type==="xrange" ||this.chart.options.chart.type==="mixed" || chart_type==="16"  || chart_type==="17" ){//判断是否为甘特图
                return;
            }
            let config = dataType;
            let thisName = e.target.name;
            let ouYuan = "";
            let numFormat="";
            let thousandsSep="";
            let decimals=2
            config.forEach((v,i) => {
                if(v.name == thisName){
                    if(v.money && v.money.money_type && v.money.money_type === "O"){
                        ouYuan = "€"
                    }else if (v.money && v.money.money_type && v.money.money_type != "O"){
                        ouYuan = v.money.money_type
                    }
                    if(v.digital&&v.digital.digital_format === "%"){
                        numFormat = "%";
                    }
                    if(v.digital&&v.digital.digital_format === ","){
						thousandsSep = ",";
					}
					if(v.digital&&v.digital.digital_site){
						decimals =v.digital.digital_site ;
					}
                }
            })
            if(ouYuan){
                if(thousandsSep===","){
                    e.target.tooltipOptions.pointFormatter = function(){
                        return  this.category.name +":"+ouYuan+ Highcharts_chart.numberFormat(this.y, decimals, ".", ",");
                    }
                }else{
                    e.target.tooltipOptions.pointFormat = ` {point.category}: ${ouYuan}{point.y}`
                }
			}else if(numFormat){
				e.target.tooltipOptions.pointFormat = ` {point.category}: {point.y}${numFormat}`
			}else{
                if(this.chart.options.chart.type==="xrange"){
                    // let yData=store.getState().reportInfo.xrangeData.yaxis;
                    // e.target.tooltipOptions.pointFormat = ` {${yData}[point.y]}`
                    
                }else{
                    if(thousandsSep===","){
                        e.target.tooltipOptions.pointFormatter = function(){
                            return  this.category.name +":"+ Highcharts_chart.numberFormat(this.y, decimals, ".", ",");
                        }                        
                    }else{
                        e.target.tooltipOptions.pointFormat = ` {point.category}:{point.y}`
                    }
                }
            }
            if(this.chart.options.chart.type==="pie"){
                e.target.tooltipOptions.pointFormat = ` {point.name}:{point.y}`
            }
        }
        setting.plotOptions.series.point.events.click = function(e) {
            
            let newdataLink = me.state.dataLink;
            let obj = {}
            let params = {}
            let isContinue=true;
            let that=this;
            let transition = e.point.category || e.point.name;
            y_axis_fields.map(function(item){
                if( item.field_name===that.series.name&&item.isCountFiled===true){
                    isContinue=false;
                }
            })
            if(!isContinue){
                message.info("计算字段不支持穿透功能")
                return;
            }
            if(chart_type == "pie" || chart_type == "pyramid" || chart_type == "wordcloud") {
                obj[x_axis_fields[x_axis_fields.length - 1]] = e.point.name;
            } else if(chart_type == "polar") {
                obj[x_axis_fields[x_axis_fields.length - 1]] = e.point.category.name;
            }else if(chart_type == "gauge") {
                message.info("仪表图暂不支持穿透功能")
                return
            } else {
                for(let i = x_axis_fields.length - 1; i >= 0; i--) {
                    
                    obj[x_axis_fields[i]] = transition.name
                    if(transition.parent) {
                        transition = transition.parent;
                    }
                }
            }
            if(chart_type == "wordcloud") {
                this.series.name=y_axis_fields[0].field_name;
                e.point.y=e.point.weight;
            }
            params.searchParams = searchParams.concat(dataFilterParams)
            params.slot = me.state.slot
            params.linkType = me.state.link_type

            let tmpUU = this.series.name
            let initDatas = me.state.res;
            let currVal = [];
            // obj[tmpUU]= e.point.y
            currVal = initDatas.filter(function (item, index) {
                return  item[tmpUU] == e.point.y
            })
            params['linkValue'] = currVal
            params['value'] = e.point.y
            params['linkFiled'] = this.series.name
            let linkFlag = false;
            let newdataRename = me.state.rename_filed;
            let linkDatas = newdataLink.filter((v,n)=>{
                if(v.label === tmpUU){
                    linkFlag = true
                    return v
                }
            })
            let fileName = this.series.name
            let portal_rep_link = me.state.portal_rep_link;
                   

            let renameData =  newdataRename&&newdataRename.counterItem_nick_name&&newdataRename.counterItem_nick_name.length>0 && newdataRename.counterItem_nick_name.filter((v,n)=>{
                if(v.value === tmpUU) {
                    fileName=v.id                    
                    return v ;
                }
            })           

            if(chart_type==="xrange"){
                let field=  y_axis_fields[0].field_name;
                let object={};
                object[y_axis_fields[0].field_name]=this[field]
                params.where=object
                if(newdataLink.length>0&&(!(this.hrefUrl===undefined))&&this.hrefUrl){
                    if(window.top.dd&&window.tMobileSDK.openBrowerWindow){
                        tMobileSDK.openBrowerWindow(url) 
                        return;
                    }
                    window.open(this.hrefUrl, '_blank')
                    return;
                }
                
            }else{
                params.where = obj;
            }
            let portalState=-1;  //  1 数据关联     2  门户关联    3 数据下钻
            portal_rep_link&&portal_rep_link.forEach(function(item){
                if(item.value===fileName){
                    portalState=item.state
                }  
            })     
                         
                if(portalState===1){
                    if(newdataLink.length>0&&(!(this.hrefUrl===undefined))&&this.hrefUrl){
                        if(window.top.dd&&window.tMobileSDK.openBrowerWindow){
                            tMobileSDK.openBrowerWindow(url) 
                            return;
                        }
                        window.open(this.hrefUrl, '_blank')
                        return;
                    } 
                    if(chart_type === "pyramid"){
                        let hrefUrl=""
                        this.series&&this.series.userOptions.data.forEach(function(item){
                            if(item[0]===that.name&&item[2]){
                                hrefUrl=item[2]
                            }
                        })
                        if(hrefUrl){
                            if(window.top.dd&&window.tMobileSDK.openBrowerWindow){
                                tMobileSDK.openBrowerWindow(url) 
                                return;
                            }
                            window.open(hrefUrl, '_blank')
                        return;
                        }
                    }    
                    params['dataLink'] = linkDatas;
                    params['rename'] = renameData;
                    $.post("/general/appbuilder/web/report/repchart/datalink",{
                        i_dataset,
                        params
                    },response=>{
                        if (response.status != "ok") {
                            let msg = response.message || '获取数据失败'
                            message.error(msg);
                        } else {
                            let url = response.data;
                            if(window.top.dd&&window.tMobileSDK.openBrowerWindow){
                                tMobileSDK.openBrowerWindow(url) 
                                return;
                            }
                            window.open(url, '_blank')
                        }
                    })
                }else if(portalState===2){  
                    let currVal = [];
                    let tmpUU = this.series.name
                    let initDatas = me.state.res;
                    let portal_data_link = me.state.portal_data_link;
                    let config={
                        label:this.series.name,
                        value:e.point.y,
                        // data:currVal
                    }                    
                    
                    config.where =params.where
                    let portalLinkDatas={};
                    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(config.where[d.label]){
                                obj.value.push(config.where[d.label])
                            }
                            obj.value=unique(obj.value);
                            portalLinkDatas[key].data.push(obj)
                        }
                    })
                    // console.log(portalLinkDatas)    
    
                    config.state=me.state
                    config.linkdata=portalLinkDatas 
                    if(me.props.onhandleClick){  
                        me.props.onhandleClick(config)   
                    }   
                }else if(portalState===3){
                    params['dataLink'] = me.state.dataLink
                    t.setState({
                        currentClickInfo: params,
                        detailModalVisible: true
                    })
                    // t.getClickInfo({
                    //     i_dataset,
                    //     params
                    // }, () => {
                    //     t.setState({
                    //         currentClickInfo: params,
                    //         detailModalVisible: true
                    //     })
                    // })
                } 
            
        }
        setting.plotOptions.series.events.legendItemClick= function(e) {
            const {
                y_axis_fields,
                chart_type
            } = me.state

            let rep_type;
            chartIdType.forEach((v, i) => {
                v.id == chart_type && (rep_type = v.type)
            })
                let num = 0,
                eventDom = $(e.browserEvent.toElement).parents(".highcharts-legend-item"),
                index = eventDom.prevAll().length;
                let sign = ""
                if(rep_type=="column"||rep_type=="stack_column"){
                sign = "highcharts-legend-item highcharts-column-series highcharts-color-" + index + " highcharts-series-" + index;
                }else if(rep_type=="bar"||rep_type=="stack_bar"){
                sign = "highcharts-legend-item highcharts-bar-series highcharts-color-" + index + " highcharts-series-" + index;
                }else if(rep_type=="line"||rep_type=="polar"){
                sign = "highcharts-legend-item highcharts-line-series highcharts-color-" + index + " highcharts-series-" + index;
                }else if(rep_type=="area"||rep_type=="stack_area"){
                sign = "highcharts-legend-item highcharts-area-series highcharts-color-" + index + " highcharts-series-" + index;
                }else if(rep_type=="scatter"){
                sign = "highcharts-legend-item highcharts-scatter-series highcharts-color-" + index + " highcharts-series-" + index;
                }else if(rep_type=="bubble"){
                sign = "highcharts-legend-item highcharts-bubble-series highcharts-color-" + index + " highcharts-series-" + index;
                }
            if($(eventDom).attr("class").trim() == sign.trim()) {
                //如果要隐藏图例
                if(y_axis_fields.length - 1 == $(e.browserEvent.toElement).parents(".highcharts-legend").find(".highcharts-legend-item-hidden").length) {
                    message.info("最少显示一个图例");
                    return false;
                }
            }
            
        }
        
            
        setting.tooltip = {
            headerFormat: '{series.name}<br>',
            pointFormat: ' {point.y}'
        }
        if(chart_type==="mixed"){//多坐标混合图
            setting.yAxis=[];
            // setting.xAxis.crosshair=true;
            setting.yAxis= [{
                title: {
                    text: ''
                },
            }, {
                title: {
                    text: ''
                },
                opposite: true
            }]
            setting.series && setting.series.forEach((v,i) => {
                let obj={
                    labels: {
                        format: '{value}',
                    },
                    title: {
                        text: v.name,
                    },
                }
                v.type="column"
                
                me.state.series_fields.length>0&&me.state.series_fields.forEach((item,j) => {
                    if(v.name===item.field_name&&item.selected==="true"){
                        v.type="line"
                        v.yAxis=1     
                    }else{
                        v.yAxis=0
                    }
                })
            
            // if(i+1<setting.series.length){
            //     v.yAxis=i+1;
            // }
            // setting.yAxis.push(obj)
            })
            setting.tooltip = {
                headerFormat: "<strong>{point.key}</strong><br>",
                // pointFormat: '{point.y}',
                shared: true
            }
        
        }else{
            setting.series && setting.series.forEach((v,i) => {
            if(v.yAxis){
                delete v.yAxis;//删除属性
            }
            })
        }


        // console.log(transitionWidth)
        t.setState({
            mostWidth: transitionWidth,
            direction,
            x_axis_fields,
            y_axis_fields,
            res,
            loading: false
        })
        if(!(chart_type==="map" ||chart_type==="xrange" || chart_type==="wordcloud" || chart_type==="pyramid" )){
            // window.Highcharts =null
           
            t.initInstance()
        }else{
            if(chart_type==="map"){//对地图进行处理
                window.Highcharts =null;//清空之前的图表引入文件对象防止冲突
                me.myRepChartInstance=null;
                window.mapConfig={}
                window.Highcharts = require('./highcharts/highmaps');
                require('./highcharts/export.js');     
                require('./highcharts/offline-export.js');     
                if(me.state.map.map_name!=="" &&mapsFileConfig[me.state.map.map_name]){
                    require('./highcharts/maps/'+mapsFileConfig[me.state.map.map_name]+'.js');
                }else{
                    require('./highcharts/maps/china.js'); 

                }
                let  colors = me.forecolor_array.reduce(function (a, b) { return a.concat(b)} );
                colors= Array.from(new Set(colors))
                res.forEach(function(item,index){
                    item.color= colors[index]
                    if(item.province){
                        item.name=item.province
                    }else if(item.city){
                        item.name=item.city
                    }else if(item.district){
                        item.name=item.district
                    }
                })
                let str='';
                for(let key in res[0]){
                    if(key!=="province" &&key!=="city"&&key!=="name"&&key!=="district"&&key!=="color"&&key!=="hrefUrl"){
                        str+= '<tr><td>'+key+'</td><td>{point.'+key+'}</td></tr>'
                    }                    
                }
                mapConfig.tooltip= {
                    useHTML: true,
                    headerFormat: '<table><tr><td>{point.name}</td></tr>',
                    pointFormat: '<tr><td>全称</td><td>{point.properties.fullname}</td></tr>' +
                    '<tr><td>父级</td><td>{point.properties.parent}</td></tr>' +
                    str,
                    footerFormat: '</table>'
                }
                let mapData=null;
                if(me.state.drilldownPrivince!=="china"&& me.state.drilldownPrivince!==""){
                    mapData= window.Highcharts.maps['cn/'+me.state.drilldownPrivince];
                }else  if(me.state.map.map_name!=="" &&mapsFileConfig[me.state.map.map_name]){
                    mapData= window.Highcharts.maps['cn/'+mapsFileConfig[me.state.map.map_name]];//跳转过来的数据加载对应的地图
                }else{
                    mapData= window.Highcharts.maps['cn/china']
                }

                mapConfig.title={}
                mapConfig.title.text="";
                mapConfig.legend={}
                mapConfig.legend.enabled=false;
                mapConfig.mapNavigation= {
                    enabled: true,
                    buttonOptions: {
                        verticalAlign: 'bottom'
                    }
                };
                
                let index=0
                if(me.state.forecolor_value){
                    index=me.state.forecolor_value;
                }
            
                mapConfig.colors=colors[index];

                mapConfig.series=[{
                    data:res ,
                    name: '',
                    mapData:mapData ,
                    dataLabels: {
                    enabled: true,
                    color: 'blue',
                    // color:  ['#2f7ed8', '#e0522f', '#ffcc00', '#10cca6', '#6bb61d', '#f2a21a', '#ff7372', '#a5e8d2', '#9ce810', '#fff80a', '#1dcfab', '#858e54'],

                    format: '{point.name}'
                    },
                    states: {
                    hover: {
                        color: '#a4edba'
                    }
                    },
                    joinBy: 'name' // 根据 fullname 属性进行关联
                },
                ]
                mapConfig.plotOptions={};
                mapConfig.plotOptions.series={};
                mapConfig.plotOptions.series.events={};
                mapConfig.plotOptions.series.events.click=function(e){
                    const {
                        province,
                        city,
                        district
                    }=me.state.map
                    let {
                        dataLink,
                    } = me.state
        
                    let newdataLink = JSON.parse(JSON.stringify(dataLink));
                    newdataLink = newdataLink.filter((elem)=>{
                        return elem.label != '';
                    });
                    let obj={
                        province:province,
                        city:city,
                        province_name:e.point.name,
                        district:district,
                        chart_type : 13,
                    }
                    if(newdataLink.length>0&&(!(e.point.hrefUrl===undefined))&&e.point.hrefUrl){  //数据关联
                        if(window.top.dd&&window.tMobileSDK.openBrowerWindow){
                            tMobileSDK.openBrowerWindow(url) 
                            return;
                        }
                        window.open(e.point.hrefUrl, '_blank')
                    }else if(mapsFileConfig[e.point.name]){
                        let isHrefPortal=false;   //判断门户是否关联了省字段
                        me.state.portal_data_link.forEach(function(item){
                            for (var i = 0; i < item.child.length; i++) {
                                let d=item.child[i]
                                if(d.label===province){
                                    isHrefPortal=true;
                                }
                            }
                        })
                        if(me.props.onhandleClick&&isHrefPortal){
                            let config={
                                province:province,
                                city:city,
                                province_name:e.point.name,
                            }
                            let where={};
                            where[city]=e.point.name;
                            where[province]=me.state.drilldownPrivince_field;
                            let portal_data_link=me.state.portal_data_link;
                            let portalLinkDatas={};
                            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:[e.point.name]
                                    }
                                    if(where[d.label]){
                                        obj.value.push(where[d.label])
                                    }
                                    obj.value=unique(obj.value);
                                    portalLinkDatas[key].data.push(obj)
                                }
                            })
                            config.where=where
                            config.linkdata=portalLinkDatas
                            config.state=me.state
                            me.props.onhandleClick(config)
                            return;
                        }
                        require('./highcharts/maps/'+mapsFileConfig[e.point.name]+'.js');
                        mapConfig.title.text=e.point.name+"地图";
                        me.setState({
                            mapBreadcrumbBool:true,
                            drilldownPrivince_field:e.point.name,
                            drilldownPrivince:mapsFileConfig[e.point.name],
                        })
                        me.getData(obj)
                    }else{  //穿透
                        let where={};
                        where[city]=e.point.name;
                        where[province]=me.state.drilldownPrivince_field;
                        let params={}
                        params.where=where
                        if(me.props.onhandleClick){
                            let config={
                                province:province,
                                city:city,
                                province_name:me.state.drilldownPrivince_field,
                                city_name:e.point.name,
                            }
                            let portal_data_link=me.state.portal_data_link;
                            let portalLinkDatas={};
                            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(where[d.label]){
                                        obj.value.push(where[d.label])
                                    }
                                    obj.value=unique(obj.value);
                                    portalLinkDatas[key].data.push(obj)
                                }
                            })
                            config.where=where
                            config.linkdata=portal_data_link
                            config.state=me.state
                            me.props.onhandleClick(config)
                            return;
                        }
                        params['dataLink'] = me.state.dataLink
                        me.setState({
                            currentClickInfo: params,
                            detailModalVisible: true
                        })
                    }
                }
                mapConfig.exporting={ enabled: false }     
                me.myRepChartInstance=null;
                me.myRepChartInstance= window.Highcharts.mapChart(this.state.showElIdRef,mapConfig)
                me.adjustChart()
            }else if(chart_type==="xrange"){//对甘特图进行处理
                window.Highcharts =null;//清空之前的图表引入文件对象防止冲突
                me.myRepChartInstance=null;
                window.Highcharts =require('./highcharts/highcharts.js'); 
                require('./highcharts/xrange-series.js');     
                require('./highcharts/export-xrange.js');     
                require('./highcharts/offline-export-xrange.js');     
                let yaxis=[];
                let x=x_axis_fields[0];
                let x2=x_axis_fields[1];
                let y=series_fields[0].field_name;
                let partialFill=series_fields[1].field_name;
                function dateFormat(date){
                    let d=new Date(date)
                    let year= d.getFullYear();
                    let month= d.getMonth();
                    let day= d.getDate();
                    return  Date.UTC(year, month, day)
                }
                res.forEach((v, i) => { 
                    v.x=dateFormat(v[x]);  
                    v.x2=dateFormat(v[x2]);  
                
                    v.partialFill=parseInt(v[partialFill])/100
                    if(yaxis.length===0){
                        yaxis.push(v[y]);
                    }else{
                        let ishasBool=false
                        yaxis.forEach((item, i) => {
                            if(item===v[y]){
                                ishasBool=true
                            }
                        })
                        if(!ishasBool){
                            let index=yaxis.length;
                            yaxis.push(v[y]);
                        }
                    }
                            
                });
                yaxis.forEach((item, i) => {
                    res.forEach((d, j) => {
                        if(item===d[y]){
                            d.y=i
                        }
                    })
                })
                let xrangeData={
                    data:res,
                    yaxis:yaxis 
                }

                setting.chart.type="xrange";
                setting.title.text="";
                let index=0
                if(me.state.forecolor_value){
                    index=me.state.forecolor_value;
                }
                setting.colors=me.forecolor_array[index];
                setting.legend.enabled=false;
                setting.xAxis= {
                    type: 'datetime',
                    dateTimeLabelFormats: {
                        week: '%Y/%m/%d'
                    }
                };
                setting.yAxis= {
                    title: {
                        text: ''
                    },
                    categories: xrangeData.yaxis,
                    reversed: true
                };
                setting.tooltip= {
                    dateTimeLabelFormats: {
                        week: '%Y/%m/%d'
                    },
                    formatter:function(){
                        return'<strong>'+this.yCategory+'</strong><br>'+
                        "日期: "+Highcharts.dateFormat('%Y/%m/%d',this.x)+' - '+Highcharts.dateFormat('%Y/%m/%d ',this.x2);
                    }
                };
                setting.series=[{
                    borderColor: 'gray',
                    pointWidth: 20,
                    data: xrangeData.data,
                    dataLabels: {
                        enabled: true
                    }
                }]
                setting.exporting={ enabled: false }           
                //    $(this.state.showElIdRef).html("")
                me.myRepChartInstance=null;
                me.myRepChartInstance  = window.Highcharts.chart(this.state.showElIdRef,setting) 
                me.adjustChart()
            }else  if(chart_type==="wordcloud"){  //词云图
                window.Highcharts =require('./highcharts/highcharts.js'); 
                // require('../../highcharts/modules/exporting.js');                       
                let wordcloudFactory =require('./highcharts/wordcloud.js');  
                wordcloudFactory(window.Highcharts)

                delete setting.yAxis
                delete setting.xAxis
                let name=setting.series[0]&&setting.series[0].name
                setting.series= [{
                    type: 'wordcloud',
                    data: res
                }]
                setting.title={
                    text: ''
                }
                setting.tooltip = {
                    headerFormat: "<strong>{point.key}</strong><br>",
                    // headerFormat: '{series.name}<br>',
                    pointFormat: name+':{point.weight}',
                    shared: true
                }
                // window.Highcharts.chart('report-draw-container',setting)
                if(document.getElementById(this.state.showElIdRef)){
                    this.myRepChartInstance = new window.Highcharts.chart(this.state.showElIdRef, { ...setting })	
                    me.adjustChart()
                }
            }else if(chart_type==="pyramid"){  // 金字塔
                window.Highcharts =require('./highcharts/highcharts.js'); 
                let pyramidFactory =require('./highcharts/funnel.js');  
                pyramidFactory(window.Highcharts)

                    setting.chart.type="pyramid";
                    setting.plotOptions.series.dataLabels={
                        enabled: true,
                        format: '<b>{point.name}</b> ({point.y})',
                        softConnector: true
                    }

                    setting.tooltip = {
                        // headerFormat: "<strong>{point.key}</strong><br>",
                        pointFormat: '{series.name}:{point.y}',
                        shared: true
                    }
                    if(res&&res.length){
                        let initD={
                            data:res,
                            name:setting.series[0]&&setting.series[0].name
                        }
                        setting.series=[]
                        setting.series.push(initD)
                    }
                if(document.getElementById(this.state.showElIdRef)){
                    this.myRepChartInstance = new window.Highcharts.chart(this.state.showElIdRef, { ...setting })	
                    me.adjustChart()
                }
            
            }
        }
   
    }
    getData(obj){
        const me = this
        const t = this;
        let {
            category_fileds,
            series_fields,
            i_dataset,
            chart_type,
            cache_span,
            forecolor_value,
            rep_name,
            searchParams,
            dataFilterParams,
            dataType,
            map,
            formula
        } = this.state
        const calculationMethods = [
            {
                type: 'sum',
                value: '求和'
            },
            {
                type: 'count',
                value: '计数'
            },
            {
                type: 'distinct',
                value: '数值计数'
            },
            {
                type: 'max',
                value: '最大值'
            },
            {
                type: 'min',
                value: '最小值'
            },
            {
                type: 'avg',
                value: '平均值'
            }
        ];
        let chartIdType = [
            {
                "id": 1, 
                "type": "column"
            }, 
            {
                "id": 2, 
                "type": "stack_column"
            }, 
            {
                "id": 3, 
                "type": "bar"
            }, 
            {
                "id": 4, 
                "type": "stack_bar"
            }, 
            {
                "id": 5, 
                "type": "line"
            }, 
            {
                "id": 6, 
                "type": "area"
            }, 
            {
                "id": 7, 
                "type": "stack_area"
            }, 
            {
                "id": 8, 
                "type": "pie"
            }, 
            {
                "id": 9, 
                "type": "scatter"
            }, 
            {
                "id": 10, 
                "type": "bubble"
            }, 
            {
                "id": 11, 
                "type": "polar"
            }, 
            {
                "id": 12, 
                "type": "gauge"
            },
            {
                "id": 13, 
                "type": "map"
            },
            {
                "id": 14, 
                "type": "mixed"
            },
            {
                "id": 15, 
                "type": "xrange"
            },
            {
                "id": 16, 
                "type": "wordcloud"
            },
            {
                "id": 17, 
                "type": "pyramid"
            },
        ]
        let chart;
        chartIdType.forEach((v, i) => {
            v.id == chart_type && (chart = v.type)
        })
        let params = {
            method: [] //name calculation
        }
        params.id = this.props.reportId;
        params.cache_span = cache_span;
        
        series_fields.length!==0 && series_fields.forEach((v, i) => {
            let arr = v.field_name.split(" : ")
            v.isCountFiled=v.isCountFiled==="true"?true:false;
            if(v.isCountFiled){
                return;
            }
            if(arr.length > 1) {
                params.method.push({
                    name: arr[1],
                    calculation: function() {
                        for(let i = 0; i < calculationMethods.length; i++) {
                            if(calculationMethods[i].value == arr[0]) return calculationMethods[i].type
                        }
                    }()
                })
            } else {
                params.method.push({
                    name: arr[0],
                    calculation: "sum"
                })
            }
        })
        params.searchParams = searchParams.concat(dataFilterParams)
        params.slot = this.state.slot
        params.rename_filed=me.state.rename_filed
        params.link_type = this.state.link_type
        params.dataLink = this.state.dataLink
        this.setState({
            method: params.method
        })
        let config={}
        config.chart_type= chart_type
        if(this.props.linkdata){
            config.portal_linkage=this.props.linkdata
        }
        if(obj){
            config=obj
            if(obj.linkdata){
                config.portal_linkage=obj.linkdata
                delete config.linkdata
            }
        }
        if(chart_type==="13"){
            if(JSON.stringify(config.portal_linkage)!=="{}"){
                let linkdata=config.portal_linkage
                if(linkdata&&linkdata.data[0].value){
                    let data=linkdata.data[0].value[0]
                    if(data.indexOf("省")){
                    map.map_name= data.split("省")[0]
                    }else if(data.indexOf("市")){
                        map.map_name= data.split("市")[0]
                    }
                    map.map_name= data
                    config.province_name=data
                    config.city=map.city
                }
                this.setState({
                    map:map
                })
            }
            config.province=map.province
            config.chart_type= 13
        }else if(chart_type==="15"){
            config.chart_type= 15
        } 

        jQuery.post('/general/appbuilder/web/report/repchart/data', {
            s_categories: category_fileds,
            s_series: series_fields,
            i_dataset: i_dataset,
            dataType:dataType,
            params,
            formula,
            ...config
        }, (response) => {
            let res = JSON.parse(response);
            if(res.status == "error"){
                me.setState({
                    loading: false,
                    isError: true,
                    errorText: res.message
                })
                message.error(res.message)
                return;
            }
            if(chart_type==="13"){
                let {city,district,province}=map
                res.forEach(function(item){
                    if(province&&item[province]){
                        item.province=item[province]
                    }
                    if(city&&item[city]){
                        item.city=item[city]
                    }
                    if(district&&item[district]){
                        item.district=item[district]
                    }
                })
                
            }
            this.setState({
                currentTableData:res,
                res:res
            })
            me.renderChart(res)
        }).catch((error) => {
            me.setState({
                loading: false,
                isError: true,
                errorText: e.responseText
            })
        })      
    }
}
let setting = {
	chart: {
		type: 'column',
		zoomType: 'xy',
		animation: true
	},
	title: {
		text: ''
	},
	legend: {
		layout: 'vertical',
		align: 'right',
		verticalAlign: 'top',
		x: -20,
		y: 50,
		floating: true,
		borderWidth: 1,
		backgroundColor: '#FFFFFF',
		shadow: true
	},
	pane: {},

	yAxis: {

	},
	xAxis: {
		tickmarkPlacement: "between",
		categories: null
	},
	credits: {
		enabled: false
	},
	plotOptions: {
		scatter: {
			tooltip: {
				headerFormat: '<b>{series.name}:{point.y}</b><br>',
				pointFormat: ''
			}
		},
		pie: {
			allowPointSelect: true,
			cursor: 'pointer',
			dataLabels: {
				enabled: true,
				format: '<b>{point.name}</b>: {point.percentage:.1f} %',
				style: {
					color: 'black'
				}
			},
			tooltip: {

			}
		},
		series: {
            events:{
                mouseOver: function(e) {

                }
            },
			point: {
				events: {
					click: function(e) {

					}
				}
			}
		}
	},
	scrollbar: {
		enabled: true
	},
	series: []
}

const mapsFileConfig={
        "中国": "china",
        "安徽": "anhui",
        "澳门": "aomen",
        "北京": "beijing",
        "福建": "fujian",
        "甘肃": "gansu",
        "广东": "guangdong",
        "广西": "guangxi",
        "贵州": "guizhou",
        "海南": "hainan",
        "河北": "hebei",
        "河南": "henan",
        "黑龙江": "heilongjiang",
        "湖北": "hubei",
        "湖南": "hunan",
        "吉林": "jilin",
        "江苏": "jiangsu",
        "辽宁": "liaoning",
        "内蒙古": "neimenggu",
        "宁夏": "ningxia",
        "青海": "qinghai",
        "山东": "shandong",
        "山西": "shanxi",
        "陕西": "shanxi2",
        "上海": "shanghai",
        "四川": "sichuan",
        // "台湾": "taiwan",
        "天津": "tianjin",
        "西藏": "xizang",
        "香港": "xianggang",
        "新疆": "xinjiang",
        "云南": "yunnan",
        "浙江": "zhejiang"
    
}
export default Chart
