<template>
  <div :id="chartId" class="linechart">

  </div>
</template>

<script>
import echarts from "echarts";
import moment from "moment"
export default {
    props:{
        chartId:String,
        chartDate:{
            default:null
        },
        xType:String,
        normalChart:{
            type:Boolean,
            default:false,
        },
        weekNormalChart:{
          type:Boolean,
            default:false,
        },
        numberChart:{
            // type:Boolean,
            default:false,
        },
        yType:{
            type:String,
            default:"rate"
        },
        sjChartType:{
            type:String
        },
        envType:{
            type:String,
            default:'Tdb'
        },
        tempColor:{
            default:false
        }
    },
    data(){
        return {
            chartInit:null,
            envMap:{
                'Tdb':{
                    name:'温度',
                    unit:"°C",
                    color:"#0091FF",
                    avg:"avgTemp",
                    param:[
                        {name:"偏冷占比",numName:"偏冷",color:"#0091FF",key:"coldProprotion"},
                        {name:"达标占比",numName:"达标",color:"#ffffff",key:"normalProprotion",centerShow:true},
                        {name:"偏热占比",numName:"偏热",color:"#F9908B",key:"hotProprotion"},
                    ]
                },
                'CO2':{
                    name:'CO₂',
                     unit:"ppm",
                     color:"#2EA121",
                     avg:"avgCo2",
                     param:[
                        {name:"正常",color:"#ffffff",key:"co2NormalProprotion",centerShow:true},
                        {name:"超标",color:"#DCAA04",key:"co2AbNormalProprotion"},
                    ]
                },
                'HCHO':{
                    name:'甲醛',
                    unit:"mg/m³",
                    color:"#2EA121",
                    avg:"avgHcho",
                    param:[
                         {name:"正常",color:"#ffffff",key:"hchoNormalProprotion",centerShow:true},
                        {name:"超标",color:"#C6322B",key:"hchoAbNormalProprotion"},
                    ]
                },
                'RH':{
                    name:'相对湿度',
                    unit:"%",
                    color:"#2EA121",
                    avg:"avgRh",
                    param:[
                        {name:"偏湿",color:"#0091FF",key:"rhPartialHumidityProprotion"},
                        {name:"正常",color:"#ffffff",key:"rhNormalProprotion",centerShow:true},
                        {name:"偏干",color:"#F58300",key:"rhPartialDryProprotion"},
                    ]
                },
                'PM2d5':{
                    name:'PM2.5',
                    unit:"μg/m³",
                    color:"#2EA121",
                    avg:"avgPm2d5",
                     param:[
                         {name:"正常",color:"#ffffff",key:"pm2d5NormalProprotion",centerShow:true},
                        {name:"超标",color:"#dcaa04",key:"pm2d5AbNormalProprotion"},
                    ]
                },
                'userAdjust':{
                    name:'用户调节',
                    unit:"个",
                    color:"#2EA121",
                    avg:"",
                     param:[
                        //  {name:"正常调节",color:"#2EA121",key:"feedbackNorSpaceNum"},
                         {name:"无用户调节",color:"#ffffff",key:"feedbackNoSpaceNum",centerShow:true},
                         {name:"用户调节",color:"#F9908B",key:"feedbackAbnorSpaceNum"},
                    ]
                },
                'energyManage':{
                    name:'能源管理',
                    unit:"kWh",
                    color:"#2EA121",
                    avg:"",
                    param:[
                         {name:"日能耗",color:"#2EA121",key:"energy"},
                    ]
                },
                'Num':{
                    name:'温度',
                    unit:"°C",
                    color:"#0091FF",
                    avg:"avgTemp",
                    param:[
                        {name:"偏冷数量",color:"#0091FF",key:"coldSpaceNum"},
                        {name:"达标数量",color:"#ffffff",key:"normalSpaceNum",centerShow:true},
                        {name:"偏热数量",color:"#F9908B",key:"hotSpaceNum"},
                    ]
                },
            },
        }
    },
    mounted(){
        this.$once("hook:beforeDestroy", () => {
            if (this.chartInit) {
                this.chartInit.clear();
            }
        })
    },
    methods:{
        moment,
        showChartInfo(divId, infoStr="暂无数据"){
            let msgOption = {
                title: {
                    show: true,
                    textStyle:{
                    color:'grey',
                    fontSize:14
                    },
                    text: infoStr,
                    left: 'center',
                    top: 'center'
                },
                xAxis: {
                    show: false
                },
                yAxis: {
                    show: false
                },
                series: []
            };
             this.chartInit= echarts.init(document.getElementById(divId));
             this.chartInit.hideLoading()
             this.chartInit.setOption(msgOption)
        },
        initDayTime(value){
            value =value.slice(4,6)+'-'+ value.slice(6,8)
            return value
        },
        initHourTime(value){
            value =value.slice(0,2)+':'+ value.slice(2,4)
            return value
        },
        drawChart(id = this.chartId,data={}){
            if(!data||!Object.keys(data).length){
                this.showChartInfo(id);
                return
            }
            let that=this;
            this.chartInit&&(this.chartInit=null)
            this.chartInit= echarts.init(document.getElementById(id));
            let dataX;
            if(this.xType=="day"){
                dataX=data.date||[];
            }else if(this.xType=="hour"){
                dataX=data.time||[];
            }else{
                dataX=data.floorName||[];
            }
            let option = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                        type: ''        // 默认为直线，可选为：'line' | 'shadow'
                    },
                    formatter: params=> {
                        var showHtm="";
                        let name = params[0].name;
                        let scale=100;
                        let fixed=1;
                        let unit ='%';
                        if(this.numberChart){
                            scale=1;
                            fixed=0;
                            unit=this.envMap[envType].unit||'个';
                        }
                        if(this.xType&&this.xType!=="floor"){
                           name = this.xType=="day"?this.initDayTime(params[0].name):this.initHourTime(params[0].name)
                        }
                        for(var i=0;i<params.length;i++){
                            //名称
                            var text =  params[i].marker +params[i].seriesName;
                            //值
                            var value = (params[i].value||params[i].value==0)?params[i].value:'--';
                            value = this.yType=="rate"?(value!=='--'?((value*scale).toFixed(fixed)+unit):'--'):value;
                            showHtm+= text+ ':' + value +'<br>'
                        }
                        showHtm =`${name}<br/>${showHtm}`;
                        return showHtm;
                    }
                },
                 grid: {
                    left: "50",
                    right:(this.envType=="PM2d5"||this.envType=="HCHO"||this.envType=="CO2")?"60":"50",
                    bottom: "30",
                    top:"7",
                    borderColor:'#E9E9E9',
                },
                color: ['#0091FF','#FFFFFF','#F9908B'],
                animation:false,
                xAxis: {
                    type: 'category',
                    // boundaryGap: false,
                    data: dataX,
                    axisTick:{
                        show:false
                    },
                    interval:0,
                    axisLine:{
                        lineStyle:{
                            color:'#D9D9D9',
                            // width:8,//这里是为了突出显示加上的
                        }
                    },
                    axisLabel: {
                        color:'#848484',
                        interval:0,
                        fontSize:11,
                        formatter:(value)=>{
                            if(this.xType=="hour"&&value.endsWith("0000")){
                                return value.slice(0,2)+':'+value.slice(2,4)
                            }else if(this.xType=="hour"&&!value.endsWith("0000")){
                                return ''
                            }
                            if(this.xType=="day"){
                                return value.slice(4,6)+'-'+value.slice(6,8)+'\n'+'周'+this.getWeek(moment(value).format('E'))
                            }else{
                                return value
                            }
                            // !this.normalChart&&(value = value*100+'%');

                        }
                    },
                },
                yAxis: {
                    type: 'value',
                    position:'left',
                    axisLabel: {
                        color:'#848484',
                        fontSize:12,
                        formatter:(value,index)=>{
                            if(index%2!==0&&this.numberChart){
                                return '';
                            }
                            if(!this.normalChart&&!this.numberChart){
                                value = value*100+'%'
                            }
                            return value
                        }
                    },

                    splitLine: {
                        show: false,
                        lineStyle:{
                            color: ['#E9E9E9'],
                            width: 1,
                            type: 'dashed'
                        }
                　　},
                    nameTextStyle:{
                        color:'#848484'
                    },
                    axisTick: {
                        show: false
                    },
                    axisLine: {
                        show: false
                    },
                },
                series: []
            };
            let envType = this.yType!=="rate"?"Num":this.envType;
            this.envMap[envType].param.forEach(item=>{
                let obj= {
                    name: item.name,
                    type: 'bar',
                    stack: '达标率',
                    data: data[item.key],
                    barWidth: '50%',
                    barMaxWidth:'50',
                    color:item.color
                };
                if(item.centerShow){
                    obj.itemStyle={barBorderColor: '#D6DADF'};
                    obj.label={
                            normal: {
                                show: (this.yType=="rate"&&this.xType=='day'||(this.sjChartType))?true:false,
                                position: 'inside',
                                color:"#1F2329",
                                formatter: (params)=>{
                                    if(this.numberChart){
                                          return !params.value?'':params.value;
                                    }
                                    return !params.value?'':`${parseInt(params.value*100)}%`;
                                }
                            },
                        }
                }
                option.series.push(obj)
            })

            // 各房间日均温度分布
            if(this.normalChart){
                //  ["<=23","23~24","24~25","25~26","26~27",">27"]
                // let normalDatex=["≤18","18<X≤20","20<X≤22","22<X≤24","24<X≤26","26<X≤28","X>28"];
                let normalDatex=["≤18","18~20","20~22","22~24","24~26","26~28","X>28"];
                option.xAxis.data=normalDatex;
                option.grid.top="45"
                option.title={
                    subtext: '空间数量'
                }
                option.series=[];
                option.series=[
                    {name: '空间数量',
                        type: 'bar',
                        stack: '达标率',
                        color:"#82c7fc",
                        barWidth: '30%',
                        data: []
                    }
                ]
                if(this.tempColor){
                     option.series[0].itemStyle= {
                        normal:{
                            color: function (params){
                                let colorList =["#4a88c0","#adcce9","#ffffff","#ffffff","#ffffff","#f5b588","#ff0000"];
                                return colorList[params.dataIndex];
                            },
                            barBorderColor: '#eaeaea',
                            borderType : 'solid',
                            borderWidth:1,
                        },
                        //鼠标悬停时：
                            emphasis: {
                                barBorderColor: '#eaeaea',
                                borderType : 'solid',
                                borderWidth:1,
                            }
                    };
                };
                if(data[0]){
                    option.series[0].data=[data[0].oneSpaceNum,data[0].twoSpaceNum,data[0].threeSpaceNum,data[0].fourSpaceNum,data[0].fiveSpaceNum,data[0].sixSpaceNum,data[0].sevenSpaceNum];
                }
            }
            // 各达标区间空间数量分布
            if(this.weekNormalChart){
                // ["≥90%","80%~90%","70%~80%","<70%"]
                let normalDatex=["90~100","80~90","70~80","60~70","50~60","40~50","30~40","20~30","10~20","0~10"];
                option.xAxis.data=normalDatex;
                option.xAxis.name="达标区间(%)";
                option.xAxis.nameTextStyle={
                        color:"#aaaaaa"
                }
                option.yAxis.show=false;
                // option.grid.top="45"
                option.title={
                    subtext: '空间数量'
                }
                option.grid= {
                    top:"18",
                    left: "50",
                    right: "65",
                    right: "500",
                    bottom: "30",
                };
                option.series=[];
                option.series=[
                    {name: '空间数量',
                        type: 'bar',
                        stack: '数量',
                        // color:"#82c7fc",
                        barWidth: '50%',
                        itemStyle: {
                            //通常情况下：
                            normal:{
        　　　　　　　　　　　　//每个柱子的颜色即为colorList数组里的每一项，如果柱子数目多于colorList的长度，则柱子颜色循环使用该数组
                                color: function (params){
                                    // var colorList = ['#0091FF','#0091FF','#0091FF','#0091FF'];
                                    let colorList =["#ffffff","#f2f2f2","#d9d9d9","#bfbfbf","#ff0000","#ff0000","#ff0000","#ff0000","#ff0000","#ff0000"];
                                    return colorList[params.dataIndex];
                                },
                                barBorderColor: '#eaeaea',
                                borderType : 'solid',
                                borderWidth:1
                            },
                            //鼠标悬停时：
                            emphasis: {
                                barBorderColor: '#eaeaea',
                                borderType : 'solid',
                                borderWidth:1,

                                // shadowBlur: 10,
                                // shadowOffsetX: 0,
                                // shadowColor: 'rgba(0, 145, 255, 0.5)'
                            }
                        },
                        label: {
                            normal: {
                                show: true,
                                position: 'top',
                                color:"#1F2329",
                                formatter: (params)=>{
                                    return `${parseInt(params.value)}`
                                }
                            },

                        },
                        data: []
                    }
                ]
                if(data){
                    option.series[0].data=[
                    data.oneSpaceNum,data.twoSpaceNum,data.threeSpaceNum,data.fourSpaceNum,data.fiveSpaceNum,
                    data.sixSpaceNum,data.sevenSpaceNum,data.eightSpaceNum,data.nineSpaceNum,data.tenSpaceNum
                    ];
                }
            }
            if(this.numberChart){
                option.grid.top="22"
                option.title={
                    top:-13,
                    left:0,
                    subtext: '空间数量'
                }
                if(this.envType==="energyManage"){
                    option.title={
                        top:-13,
                        left:12,
                        subtext: 'kWh'
                    };
                    option.series[0].label= {
                            normal: {
                                show: true,
                                position: 'top',
                                color:"#1F2329",
                                formatter: (params)=>{
                                    return `${parseInt(params.value)}`
                                }
                            },
                    };
                    option.series[0].itemStyle= {
                        normal:{
                            color: function (params){
                                if(params.dataIndex<7){
                                    return '#D6DADF'
                                }
                                return '#BCBFC2'
                            },
                            barBorderColor: '#eaeaea',
                            borderType : 'solid',
                            borderWidth:1,
                        },
                        //鼠标悬停时：
                        emphasis: {
                            barBorderColor: '#eaeaea',
                            borderType : 'solid',
                            borderWidth:1,
                        }
                    };
                }
            }
            if(this.sjChartType){
                if(this.sjChartType=="regions"){
                    let normalDatex=["内区","外区"];
                    option.xAxis.data=normalDatex;
                }
                if(this.sjChartType=="orientation"){
                    let normalDatex=["东","南","西","北"];
                    option.xAxis.data=normalDatex;
                }
                if(this.sjChartType=="localtion" || this.sjChartType=="freshAir" ){
                    let normalDatex=data.objectName;
                    option.xAxis.data=normalDatex;
                }
                option.yAxis.show=false;
                option.grid= {
                    left: "0",
                    right: "0",
                    bottom: "30",
                    top:"7",
                    borderColor:'#E9E9E9',
                };
            }
            this.chartInit.setOption(option);
            window.addEventListener("resize",function(){
                that.chartInit.resize();
            })
        },
         getWeek (week) {
            switch (Number(week)) {
                case 1:
                    return '一'
                case 2:
                    return '二'
                case 3:
                    return '三'
                case 4:
                    return '四'
                case 5:
                    return '五'
                case 6:
                    return '六'
                case 7:
                    return '日'
                default:
                    return '--'
            }
        },
    },
    watch:{
        chartDate:{
            handler(newval){
                if (this.chartInit) {
                    this.chartInit.clear();
                }
                this.chartDate=newval;
                this.$nextTick(()=>{
                    this.drawChart(this.chartId,this.chartDate)
                })
            },
            deep:true,
             immediate: true,
        },
        envType(n){
            this.envType=n;
            console.log(this.envType,"this.envType")
            if (this.chartInit) {
                this.chartInit.clear();
            }
            this.drawChart(this.chartId,this.chartDate)
        }
    }
}
</script>

<style lang="less" scoped>
.linechart{
    width: 100%;
    height: 240px;
}
</style>