<template>
    <div class="datasExport">
        <div class="datasExport_wind">
            <div class="windStstus">
                <div class="exceed">
                    <span class="title">场站：</span>
                    <el-select v-model="exportFrom.station" multiple collapse-tags placeholder="请选择">
                        <el-option
                        v-for="item in stationOption"
                        :key="item.no"
                        :label="item.stationName"
                        :value="item.no">
                        </el-option>
                    </el-select>
                </div>
                <div class="exceed">
                    <span class="title">时间：</span>
                    <el-date-picker
                        v-model="exportFrom.pickerTime"
                        type="daterange"
                        :clearable='false'
                        value-format="YYYY-MM-DD"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期">
                    </el-date-picker>
                </div>
                <el-button color="#626aef" @click="seachData">查 询</el-button>
                <el-button @click="exportDataMsg">导 出</el-button>
            </div>
        </div>
        <div class="lineMain" :style="pageHeight">
            <div class="lineStyle1" v-for="(item, index) in 7" :key="index">
                <div :id="'yearChartBar' + Number(index+1)" style="width: 100%;height: 300px"></div>
                
            </div>
            <!-- <h1 class="hhhTest">Hover this text to see the effect!</h1> -->
        </div>
    </div>
</template>

<script>
import { apiGetannualPower, apiGetStation} from '../api/api'
import ExcelJS from 'exceljs'
import fileSave from 'file-saver'
export default {
    data() {
        return {
            exportFrom: {
                station: [],
                pickerTime: []
            },
            stationOption: [],
            tableData: []
        }
    },
    created() {
        this.exportFrom.pickerTime[0] = this.getTime(new Date(new Date().getTime() - 30*24*60*60*1000))
        this.exportFrom.pickerTime[1] = this.getTime(new Date())
        this.getYearData()
        this.getAllStations()
    },
    computed:{
        pageHeight() {
            return {
                'height': document.documentElement.clientHeight-130 + 'px'
            }
        }
    },
    methods:{
        seachData() {
            console.log('exportFrom', this.exportFrom)
        },
        // 获取所有场站
        getAllStations() {
            apiGetStation().then(datas =>{
                if (datas && datas.data && datas.data.list) {
                    this.stationOption = datas.data.list
                    if (datas.data.list.length>0) {
                        this.exportFrom.station[0] = datas.data.list[0].no
                    }
                }
            })
        },
        // 获取年发电量数据
        getYearData() {
            let that = this
            let params = {
                stationNumber: '-1',
                itemVal: 0
            }
            apiGetannualPower(params).then(datas =>{
                if (datas && datas.data.list) {
                    let monthLen = 0
                    monthLen = new Date().getMonth()+1
                    // 表格数据处理
                    that.getTableData(datas.data.list)
                    // 柱状图数据处理
                    that.getBarData(datas.data.list, monthLen)
                }
            })
        },
        // 处理当年月发电量表格数据
        getTableData(datas) {
            let proportion = {
                name: '当月占比',
                statistic: '-'
            }
            let proportionYear = {
                name: '全年占比',
                statistic: '-'
            }
            let monthName = ['january', 'february', 'march', 'april', 'may',
             'june', 'july', 'august', 'september', 'october', 'november', 'december']
            datas.forEach((item,index) =>{
                if (index === 0 || index === 1) {
                    item.statistic = 0
                    monthName.forEach(its =>{
                        item[its] = item[its] ? Math.ceil(item[its]): '-'
                    })
                    monthName.forEach(itv => {
                        item.statistic += item[itv] && item[itv] !== '-' ? item[itv] : 0
                    })
                    if (index === 0) {
                        item.name = '计划发电'
                    } else if (index === 1) {
                        item.name = '实际发电'
                    }
                } else if (index === 2 || index === 3) {
                    item.statistic = '-'
                    monthName.forEach(itv =>{
                        item[itv] = item[itv] && item[itv] !== null ? (item[itv]*100).toFixed(2) +'%' : '-'
                    })
                    if (index === 2) {
                        item.name = '短期准确率'
                    } else if (index === 3) {
                        item.name = '超短准确率'
                    }
                }
            })
            // 当月占比
            monthName.forEach(itc =>{
                proportion[itc] = this.$utils.ratioCalculation(datas[1][itc], datas[0][itc])
            })
            datas.splice(2,0,proportion)
            // 全年占比
            monthName.forEach(itc =>{
                proportionYear[itc] = this.$utils.ratioCalculation(datas[1][itc], datas[0].statistic)
            })
            datas.splice(3,0,proportionYear)

            let num = 0
            let num2 = 0
            let num3 = 0
            monthName.forEach((itb, index) =>{
                if (datas[4][itb] && datas[4][itb] !== '-') {
                    num += 1
                    num2 += (datas[4][itb].replace('%', '')) / 100
                }
                if (datas[5][itb] && datas[5][itb] !== '-') {
                    num3 += datas[5][itb].replace('%', '') / 100
                }
            })

            //全年占比统计
            proportionYear.statistic = this.$utils.ratioCalculation(datas[1].statistic, datas[0].statistic)
            //短期准确率统计
            datas[4].statistic = (num2 / num).toFixed(2) * 100 + '%'
            //超短期准确率统计
            datas[5].statistic = (num3 / num).toFixed(2) * 100 + '%'
            this.tableData = datas
            console.log('tableData', this.tableData)
        },
        //处理当年月发电量柱状图数据
        getBarData(datas, val) {
            let xAxisAll = ['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月']
            let xAxis = []
            for(let i =0; i<val; i++) {
                xAxis.push(xAxisAll[i])
            }
            let legend = ['计划发电','实际发电']
            let series = [
                {
                    name: '计划发电',
                    type: 'bar',
                    barGap: 0,
                    emphasis: {
                        focus: 'series'
                    }
                },
                {
                    name: '实际发电',
                    type: 'bar',
                    barGap: 0,
                    emphasis: {
                        focus: 'series'
                    }
                }
            ]
            datas.forEach(itn =>{
                if (itn.name === '计划发电') {
                    let data = [itn.january, itn.february, itn.march, itn.april, itn.may,itn.june, 
                    itn.july, itn.august, itn.september, itn.october, itn.november, itn.december]
                    series[0].data = data
                }
                if (itn.name === '实际发电') {
                    let data1 = [itn.january, itn.february, itn.march, itn.april, itn.may, 
                    itn.june, itn.july, itn.august, itn.september, itn.october, itn.november, itn.december]
                    series[1].data = data1
                }
            })
            for(let i=0;i<7; i++) {
                this.getPowerBar('yearChartBar', i, '功率预测', xAxisAll, legend, series)
            }
        },
        getPowerBar(name, idx, title, xAxis, legend, series) {
            let namecv = name + (idx+1)
            let option = {
                title: {
                    text: '期次' + idx + title,
                    textStyle: {
                        fontSize: '16',
                        fontWeight: 'bold'
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                    type: 'shadow'
                    }
                },
                grid: {
                    left: title === '今日发电量预测' ? '7%' : '6%',
                    right: '5%',
                    bottom: '3%',
                    containLabel: true
                },
                legend: {
                    // bottom: bott,
                    right: '20',
                    data: legend
                },
                xAxis: [
                    {
                    type: 'category',
                    axisTick: { show: false },
                    data: xAxis
                    }
                ],
                yAxis: [
                    {
                    type: 'value',
                    name: '万千瓦时(Wkw/h)'
                    }
                ],
                series: series
            };
            // 基于准备好的dom，初始化echarts实例
            let myChart = this.$echarts.init(document.getElementById(namecv))
            myChart.setOption(option);
            window.addEventListener("resize", function () {
                myChart.resize()
            })
        },
        getTime(date){
            var y = date.getFullYear();  
            var m = date.getMonth() + 1;  
            m = m < 10 ? ('0' + m) : m;  
            var d = date.getDate();  
            d = d < 10 ? ('0' + d) : d;  
            let timeF = y + '-' + m + '-' + d
            return timeF
        },
        exportDataMsg() {
            let data = this.tableData  //接口返回数据
            let data1 = this.tableData  //接口返回数据
            const workbook = new ExcelJS.Workbook()
            for(let i =0; i<2; i++) {
                const worksheet = workbook.addWorksheet('Sheet'+Number(i+1))
                //根据数据自己调整
                debugger
                worksheet.columns = [
                    { header: '月份', key: 'name', width: 24 },
                    { header: '合计', key: 'statistic', width: 24 },
                    { header: '一月', key: 'january' },
                    { header: '二月', key: 'february' },
                    { header: '三月', key: 'march' },
                    { header: '四月', key: 'april' },
                    { header: '五月', key: 'may' },
                    { header: '六月', key: 'june' },
                    { header: '七月', key: 'july' },
                    { header: '八月', key: 'august' },
                    { header: '九月', key: 'september' },
                    { header: '十月', key: 'october' },
                    { header: '十一月', key: 'november' },
                    { header: '十二月', key: 'december' }
                ]
                worksheet.getRow(1).font = {
                    size: 12,
                    bold: true
                }
                worksheet.addRows(data)

                worksheet.addTable({
                    name: 'MyTable',
                    ref: 'A10',
                    headerRow: true,
                    totalsRow: true,
                    style: {
                        theme: 'TableStyleDark3',
                        showRowStripes: true,
                    },
                    columns: [
                        {name: 'Date', totalsRowLabel: 'Totals:', filterButton: true},
                        {name: 'Amount', totalsRowFunction: 'sum', filterButton: false},
                    ],
                    rows: [
                        [new Date('2019-07-20'), 70.10],
                        [new Date('2019-07-21'), 70.60],
                        [new Date('2019-07-22'), 70.10],
                    ],
                });

                // 增加echarts图片
                
                var baseCanvas = document.getElementById('yearChartBar'+Number(i+1)).children[0].children[0]
                if (!baseCanvas) {
                    return false
                }
                var width = baseCanvas.width
                var height = baseCanvas.height
                var ctx = baseCanvas.getContext('2d')
                ctx.drawImage(baseCanvas, 0, 0, width, height)
                let base64 = baseCanvas.toDataURL()
                // 此时获取到了渲染的echart图片的base64，后续报表添加sheet2
                const imageId2 = workbook.addImage({
                    base64: base64,
                    extension: 'png'
                })
                worksheet.addImage(imageId2, {
                    tl: { col: 0, row: 20 },
                    ext: { width: width/5*4, height: height/5*4 }
                })
        
            }
            workbook.xlsx.writeBuffer().then(buffer => {
                //这里为type
                const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' })
                fileSave(blob, `数据导出.xlsx`)
            })
        }
    }
}
</script>

<style lang="less">
.datasExport{
    .datasExport_wind{
        .windStstus{
            display: flex;
            // justify-content: space-around;
            align-items: center;
            background: #3a35ae;
            margin: 0 10px;
            border: 1px solid #7674d8;
            border-radius: 10px 10px 0 0;
            border-bottom: none;
            height: 40px;
            padding-left: 10px;
            .exceed{
                display: flex;
                margin-right:20px;
                .title{
                    color: #fff;
                    font-size: 12px;
                    margin-top: 5px;
                }
                .el-input{
                    width: 200px;
                    margin-right:10px;
                    height: 28px;
                }
                .el-select .el-input.is-focus .el-input__wrapper{
                    box-shadow: 0 0 0 1px rgba(100, 95, 239, 1) !important;
                }
                .el-select{
                    .el-input__wrapper{
                        background: none;
                    }
                    .el-input__wrapper.is-focus{
                        box-shadow: 0 0 0 1px rgba(100, 95, 239, 1) !important;
                    }
                    .el-tag{
                        background: #645fef;
                        color: #fff;
                    }
                }
                .el-date-editor {
                    height: 28px;
                    
                    background: none;
                    .el-input__icon,
                    .el-range-separator {
                        line-height: 28px;
                    }
                    .el-input__icon {
                        svg{
                            color: #fff;
                        }
                    }
                    .el-range-input, .el-range-separator, .el-range-input{
                        color: #fff;
                    }
                }
            }
            .el-button {
                height: 28px;
                padding: 0 20px;
                line-height: 5px;
            }
        }
    }
    .el-button{
        height: 30px;
        line-height: 5px;
    }
    .lineMain{
        width: calc(100% - 20px);
        padding: 10px;
        background: #edeffb;
        border-radius: 10px;
        overflow-y: auto;
        .lineStyle1{
            border-radius: 10px;
            background: #fff;
            margin-bottom: 10px;
            padding: 10px;
            box-shadow: 0 4px 8px 0 rgba(0, 0, 0, .2);
        }
        .hhhTest{
            color: #0087ca;
            cursor: pointer;
            display: inline-block;
            position: relative;
        }
        .hhhTest::after{
            content: '';
            position: absolute;
            width: 100%;
            left: 0;
            bottom: 0;
            height: 2px;
            background: #0087ca;
            transform: scale(0);
            transition: transform 0.5s ease-out;
            transform-origin: right;
        }
        .hhhTest:hover::after{
            transform: scale(1);
            transform-origin: left;
        }
    }
}
</style>