<template>
  <div class="app-container home">
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleTabClick">
      <el-tab-pane label="同比分析" name="同比分析">
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item label="耗能设备" prop="week">
            <el-select v-model="selectDevice" placeholder="请选择" @change="handleDevChange" style="width: 240px">
<!--              <el-option label="所有" value="0" />-->
              <el-option v-for="item in deviceName" :key="item.deviceId" :label="item.deviceName" :value="item.deviceId" />
            </el-select>
          </el-form-item>
            <el-form-item label="日期"><el-date-picker v-model="dateValue1" format="YYYY" value-format="YYYY" type="year" placeholder="请选择日期" size="default"/></el-form-item>
            <el-form-item><el-button type="primary" @click="lastYear"><el-icon><ArrowLeft /></el-icon>上一年</el-button></el-form-item>
            <el-form-item><el-button type="primary" @click="nextYear">下一年<el-icon><ArrowRight /></el-icon></el-button></el-form-item>
            <el-form-item><el-button type="primary" icon="Search" @click="handleQuery1">查询</el-button></el-form-item>
        </el-form>
        <div class="chartBox" ref="container">
          <div v-show="isShow1" id="tongbiChart"></div>
          <el-empty v-show="isShow2" description="暂无数据"/>
        </div>
        <div class="tableBox1">
          <el-table :data="tbfxDataTable" height="345px">
            <el-table-column label="月份" align="center" prop="month" width="100"/>
            <el-table-column label="本期/kWh" align="center" prop="year"/>
            <el-table-column label="同期/kWh" align="center" prop="toYear"/>
            <el-table-column label="同比" align="center" prop="compute"/>
            <el-table-column label="累计同比" align="center" prop="addUp"/>
          </el-table>
        </div>
      </el-tab-pane>




      <el-tab-pane label="环比分析" name="环比分析">
<!--        @submit.native.prevent阻止默认提交事件-->
        <el-form :inline="true" class="demo-form-inline" @submit.native.prevent>
          <el-form-item class="mr0"><button class="myBtn btn1" :class="{active : activeIndex === 0}" @click="handleDaily">按日</button></el-form-item>
          <el-form-item ><button class="myBtn btn2" :class="{active : activeIndex === 1}" @click="handleMonthly">按月</button></el-form-item>
          <el-form-item label="日期"><el-date-picker v-model="dateValue2" :type="dateType" :format="format" :value-format="valueFormat" placeholder="请选择日期" size="default"/></el-form-item>
          <el-form-item><el-button type="primary" icon="Search" @click="handleQuery2">查询</el-button></el-form-item>
        </el-form>
        <div class="tableBox2">
          <el-table :data="hbfxDataTable">
            <el-table-column label="用能设备" align="center" prop="deviceName"/>
            <el-table-column :label="label1" align="center" :prop="prop1"/>
            <el-table-column :label="label2" align="center" :prop="prop2"/>
            <el-table-column label="增加值/kWh" align="center" prop="addUp"/>
            <el-table-column label="环比" align="center" prop="compute"/>
            <el-table-column label="操作" align="center">
              <template v-slot="scope">
                <el-button type="primary" size="small" :icon="Histogram" @click="handleChart(scope)">图表</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
              v-model:current-page="hbfxCurrentPage"
              v-model:page-size="hbfxPageSize"
              :page-sizes="[5, 10, 20, 50]"
              :small="hbfxSmall"
              :disabled="hbfxDisabled"
              :background="hbfxBackground"
              layout="total, sizes, prev, pager, next, jumper"
              :total="hbfxDataTable.length"
              @size-change="hbfxHandleSizeChange"
              @current-change="hbfxHandleCurrentChange"/>
        </div>
        <!-- 生成图表弹出窗 -->
        <el-dialog class="mrt" :title="title" v-model="open" width="1000px" append-to-body :close-on-click-modal="false" :show-close="false">
          <div class="chartBox">
            <div id="huanbiChart"></div>
          </div>
          <el-button class="floatRight" @click=close>关闭</el-button>
        </el-dialog>
      </el-tab-pane>

    </el-tabs>
  </div>
</template>

<script setup name="Index">


import {Histogram} from '@element-plus/icons-vue'
import {ref, reactive, onMounted, nextTick, onBeforeUnmount} from "vue";
import { getHuanbiFx,getTongbiFx } from "@/api/analyse/nhfx/nhfx"
import { getDevice } from "@/api/control/manual"
import * as echarts from "echarts";

onMounted(async () => {
  await nextTick();
  // 在这里进行el-tabs的初始化操作
  formattedDateFun()
  getDeviceList()
  getTongbiFxFun()
})

/** 格式化日期*/
let year, month ,day;
function formattedDateFun(){
  let date = new Date()
  year = date.getFullYear()
  month = (date.getMonth()+1).toString().padStart(2, '0');
  day = date.getDate().toString().padStart(2, '0');
  dateValue2.value = `${year}-${month}-${day}`
  // let hours = date.getHours()
  // let minutes = date.getMinutes()
  // let seconds = date.getSeconds()
  // timer.value = `${hours}:${minutes}:${seconds}`
  // console.log(dateValue2.value)
  // console.log(timer.value)
}

/** 切换按钮操作*/
const activeName = ref('同比分析')

/** ------------------------------同比分析------------------------------*/
/** ------------------------------------------------------------------*/
/** 过滤查询*/
//渲染设备列表
const selectDevice = ref(1)
const deviceName = ref([])
function getDeviceList(){
  getDevice().then((res)=>{
    deviceName.value = res.data
  })
}
//拿到设备id
const checkedDevId = ref(1)
function handleDevChange(id){
  console.log(id)
  checkedDevId.value = id
}

//切换年份处理
//本期年份
const dateValue1 = ref(new Date().getFullYear().toString());
//上一年
function lastYear(){
  const year = parseInt(dateValue1.value);
  dateValue1.value = (year - 1).toString();
  console.log('上一年',dateValue1.value)
}
//下一年
function nextYear(){
  const year = parseInt(dateValue1.value);
  dateValue1.value = (year + 1).toString();
  console.log('下一年',dateValue1.value)
}
//查询
function handleQuery1(){
  getTongbiFxFun()
}

/** echart处理*/
//空状态
const isShow1 = ref(true)
const isShow2 = ref(false)
//获取渲染echart数据和表格数据
const tongbiBenqi = ref([])
const tongbiTongqi = ref([])
const tbfxDataTable = ref([])
function getTongbiFxFun(){
  getTongbiFx({
    "deviceId": checkedDevId.value,
    "year": parseInt(dateValue1.value),
    "toYear": dateValue1.value - 1
  }).then((res)=>{
    //渲染柱状图
    if(res.code == 200 && res.data.StatisticsToYear != null && res.data.StatisticsYear != null){
      isShow1.value = true
      isShow2.value = false

        //本期
        let benqiArr = []
        console.log(res)
        delete res.data.StatisticsYear.yearId
        delete res.data.StatisticsYear.deviceId
        delete res.data.StatisticsYear.deviceName
        delete res.data.StatisticsYear.yearDate
        for(let i in res.data.StatisticsYear){
          benqiArr.push(res.data.StatisticsYear[i])
        }
        tongbiBenqi.value = benqiArr

        //同期
        let tongqiArr = []
        delete res.data.StatisticsToYear.yearId
        delete res.data.StatisticsToYear.deviceId
        delete res.data.StatisticsToYear.deviceName
        delete res.data.StatisticsToYear.yearDate
        for(let i in res.data.StatisticsToYear){
          tongqiArr.push(res.data.StatisticsToYear[i])
        }
        tongbiTongqi.value = tongqiArr
        tongbiChartFun()
    }else {
      isShow1.value = false
      isShow2.value = true
    }

    //渲染表格
    if(res.data.yearOnYear && res.data.yearOnYear.length > 0){
      tbfxDataTable.value = res.data.yearOnYear
    }else{
      tbfxDataTable.value = []
    }


  })
}
let tongbiChart;
function tongbiChartFun(){
  const chartDom = document.getElementById('tongbiChart')
  tongbiChart = echarts.init(chartDom);
  const option = {
    legend: {
      data: [dateValue1.value,dateValue1.value - 1],
      // selectedMode: 'single',
      textStyle: {
        color: "#f3ffff"
      }
    },
    tooltip: {
      trigger: "axis",
      // borderColor: '#00fcff',
      borderWidth: 1
    },
    grid:{
      show: true,
      top: '20%',
      bottom:'6%',
      left:'3%',
      right:'2%',
      borderWidth: 1,
      borderColor: '#767da1',
    },
    xAxis: {
      type: 'category',
      name:'月',
      data: ['01','02','03','04','05','06','07','08','09','10','11','12'],
      nameTextStyle: {
        color: "#f3ffff",
        nameLocation: "start"
      },
      axisLabel: {
        textStyle: {
          color: "#f3ffff"
        }
      },
      axisLine: {
        lineStyle: {
          color: '#767da1' // 设置x轴的线条颜色
        }
      },
      axisTick: {
        show: false // 去掉x轴刻度
      },
      splitArea: {
        show: true,
        interval:0,
        areaStyle: {
          color: ['rgb(54,68,148,.8)', 'rgb(37,51,133,.8)'] //这里重点，用于设置颜色的数组，
          //（有了这个属性，那我们完全可以自己在根据某些条件来生成这样一个数组）
        }
      }
    },
    yAxis: {
      type: 'value',
      name:'kWh',
      nameTextStyle: {
        color: "#f3ffff",
        nameLocation: "start"
      },
      axisLabel: {
        textStyle: {
          color: "#f3ffff"
        }
      },
      splitLine: {
        show: true,
        lineStyle: {color: "#767da1", type: "solid"} //dashed
      } //s是否显示为虚线的条纹背景
    },
    series: [
      {
        name: dateValue1.value,
        data:  tongbiBenqi.value,
        type: 'bar',
        smooth: true,
        symbol: "none", //去掉圆点
        itemStyle: { //线条颜色
          color: 'rgba(51,221,223)',
        },
        markPoint: {
          data: [
            {
              type: "max",
              name: "最大值",
              symbol: 'circle',
              symbolSize: 18,
              label:{
                color:'#fff',
                fontSize:12,
                formatter: function(params){
                  return 'Max：' + params.value;
                },
                // textBorderWidth:3,
                // textBorderColor:"#1490fc",
                position: 'top',
                // offset: [0, 0]
              }
            },
            {
              type: "min",
              name: "最小值",
              symbol: 'circle',
              symbolSize: 18,
              label:{
                color:'#fff',
                fontSize:12,
                position: 'top',
                formatter: function(params){
                  return 'Min：' + params.value;
                },
              }
            }
          ]
        },
      },
      {
        name: dateValue1.value - 1,
        data:  tongbiTongqi.value,
        type: 'bar',
        smooth: true,
        symbol: "none", //去掉圆点
        itemStyle: { //线条颜色
          color: 'rgba(182,162,222)',
        },
        markPoint: {
          data: [
            {
              type: "max",
              name: "最大值",
              symbol: 'circle',
              symbolSize: 18,
              label:{
                color:'#fff',
                fontSize:12,
                formatter: function(params){
                  return 'Max: ' + params.value;
                },
                // textBorderWidth:3,
                // textBorderColor:"#1490fc",
                position: 'top',
                // offset: [0, 0]
              }
            },
            {
              type: "min",
              name: "最小值",
              symbol: 'circle',
              symbolSize: 18,
              label:{
                color:'#fff',
                fontSize:12,
                position: 'top',
                formatter: function(params){
                  return 'Min: ' + params.value;
                },
              }
            }
          ]
        },
      },
    ],
  };
  option && tongbiChart.setOption(option);
}

/** 数据表格处理*/
//内容
const tbfxCurrentPage = ref(1)
const tbfxPageSize = ref(5)
const tbfxSmall = ref(false)
const tbfxBackground = ref(false)
const tbfxDisabled = ref(false)
const tbfxHandleSizeChange = (val) => {
  console.log(`${val}`)
}
const tbfxHandleCurrentChange = (val) => {
  console.log(`${val}`)
}




/** ------------------------------环比分析------------------------------*/
/** ------------------------------------------------------------------*/
/** 点击环比分析*/
function handleTabClick(e){
  console.log(e.paneName)
  if(e.paneName == '环比分析'){
    handleDaily()
  }

}

/** 过滤查询*/
const activeIndex = ref(0)
const dateValue2 = ref()
const dateType = ref('date')
const format = ref('YYYY-MM-DD')
const valueFormat = ref('YYYY-MM-DD')
const timeType = ref(1)
const echartLegend = ref([])
//按日
function handleDaily(){
  activeIndex.value = 0;
  prop1.value = 'thisMonthTotal'
  label1.value = '当日用电/kWh'
  prop2.value = 'lastMonthTotal'
  label2.value = '上日用电/kWh';
  dateType.value = 'date'
  format.value = 'YYYY-MM-DD'
  valueFormat.value = 'YYYY-MM-DD'
  timeType.value = 1
  dateValue2.value = `${year}-${month}-${day}`
  echartLegend.value = ['当日','上日']
  console.log(dateValue2.value)
  getHuanbiFxFun()
}
//按月
function handleMonthly(){
  activeIndex.value = 1;
  prop1.value = 'thisMonthTotal'
  label1.value = '当月用电/kWh'
  prop2.value = 'lastMonthTotal'
  label2.value = '上月用电/kWh';
  dateType.value = 'month'
  format.value = 'YYYY-MM'
  valueFormat.value = 'YYYY-MM'
  timeType.value = 2
  dateValue2.value = `${year}-${month}`
  echartLegend.value = ['本月','上月']
  console.log(dateValue2.value)
  getHuanbiFxFun()
}
//查询
function handleQuery2(){
  getHuanbiFxFun()
}

/** 数据表格处理*/
//内容
const hbfxDataTable = ref([])
const prop1 = ref('toDay')
const label1 = ref('当日用电/kWh')
const prop2 = ref('lastDay')
const label2 = ref('上日用电/kWh')
const hbfxCurrentPage = ref(1)
const hbfxPageSize = ref(5)
const hbfxSmall = ref(false)
const hbfxBackground = ref(false)
const hbfxDisabled = ref(false)
const hbfxHandleSizeChange = (val) => {
  console.log(`${val}`)
}
const hbfxHandleCurrentChange = (val) => {
  console.log(`${val}`)
}
//获取环比分析表格数据
function getHuanbiFxFun(){
  getHuanbiFx({
    "timeType":timeType.value,
    "datetime":dateValue2.value
  }).then((res)=>{
    if(res.code == 200){
      hbfxDataTable.value = res.data
    }
  })
}

/** 生成图表按鈕操作*/
const title = ref()
const open = ref(false)
//生成图表按钮
const lastMonthData = ref([])
const thisMonthData = ref([])
function handleChart(scope){
  open.value = true;
  lastMonthData.value = scope.row.lastMonthTotal
  thisMonthData.value = scope.row.thisMonthTotal
  setTimeout(()=>{
    huanbiChartFun()
  },100)

};
//关闭弹框按钮
function close(){
  open.value = false;
}

/** echart处理*/
let huanbiChart;
function huanbiChartFun(){
  dateValue2.value = dateValue2.value.toString()
  // console.log('X轴：',dateValue2.value)
  // console.log('本月：',thisMonthData.value,'上月：',lastMonthData.value)
  let thisMonthDataArr = []
  let lastMonthDataArr = []
  thisMonthDataArr.push(thisMonthData.value)
  lastMonthDataArr.push(lastMonthData.value)
  const chartDom = document.getElementById('huanbiChart')
  tongbiChart = echarts.init(chartDom);
  const option = {
    legend: {
      data: echartLegend.value,
      // selectedMode: 'single',
      textStyle: {
        color: "#333"
      }
    },
    tooltip: {
      trigger: "axis",
      // borderColor: '#00fcff',
      borderWidth: 1
    },
    grid:{
      show: true,
      top: '20%',
      bottom:'6%',
      left:'4%',
      right:'3%',
      borderWidth: 1,
      borderColor: '#767da1',
    },
    xAxis: {
      type: 'category',
      name:'',
      data: [dateValue2.value],
      nameTextStyle: {
        color: "#333",
        nameLocation: "start"
      },
      axisLabel: {
        textStyle: {
          color: "#333"
        }
      },
      axisLine: {
        lineStyle: {
          color: '#767da1' // 设置x轴的线条颜色
        }
      },
      axisTick: {
        show: false // 去掉x轴刻度
      },
      splitArea: {
        show: true,
        interval:0,
        areaStyle: {
          color: ['rgb(54,68,148,.8)', 'rgb(37,51,133,.8)'] //这里重点，用于设置颜色的数组，
          //（有了这个属性，那我们完全可以自己在根据某些条件来生成这样一个数组）
        }
      }
    },
    yAxis: {
      type: 'value',
      name:'kWh',
      nameTextStyle: {
        color: "#333",
        nameLocation: "start"
      },
      axisLabel: {
        textStyle: {
          color: "#333"
        }
      },
      splitLine: {
        show: true,
        lineStyle: {color: "#767da1", type: "solid"} //dashed
      } //s是否显示为虚线的条纹背景
    },
    series: [
      {
        name: echartLegend.value[0],
        data:  thisMonthDataArr,
        type: 'bar',
        smooth: true,
        symbol: "none", //去掉圆点
        itemStyle: { //线条颜色
          color: 'rgba(51,221,223)',
        },
      },
      {
        name: echartLegend.value[1],
        data:  lastMonthDataArr,
        type: 'bar',
        smooth: true,
        symbol: "none", //去掉圆点
        itemStyle: { //线条颜色
          color: 'rgba(182,162,222)',
        },
      },
    ],
  };
  option && tongbiChart.setOption(option);
}



/** 页面销毁时*/
onBeforeUnmount(() => {
  if(tongbiChart){
    tongbiChart.dispose(); // 销毁实例，防止内存泄漏
  }
  if(huanbiChart){
    huanbiChart.dispose();
  }
});

</script>

<style scoped lang="scss">
.home{
  width: 100%;
  height: calc(100vh - 84px);
  overflow: auto;
}
.chartBox{
  width: 100%;
  height: 300px;
  margin-bottom: 18px;
  overflow: hidden;
  #tongbiChart{
    width: 100%;
    height: 100%;
  }
  #huanbiChart{
    width: 100%;
    height: 100%;
  }
}
.tableBox1{
  width: 100%;
  height: 402px;
  overflow: hidden;
  background-color: #2F3D8A;
}
.tableBox2{
  width: 100%;
  height: 717px;
  background-color: #2F3D8A;
  overflow: hidden;
}

.mr0{
  margin-right: 0px !important;
}
.myBtn{
  padding: 7px 25px;
  background-color: #1B2965;
  border: 1px solid #409EFF;
  color: #fff;
  cursor: pointer;
}
.btn1{
  border-top-left-radius: 2px;
  border-bottom-left-radius: 2px;
}
.btn2{
  margin-left: -1px;
  border-top-right-radius: 2px;
  border-bottom-right-radius: 2px;
}
.active{
  background-color: #409EFF !important;
  color: #fff !important;
}
.floatRight{
  margin-left: 90%;
}
::v-deep .el-dialog{
  background-color: rgba(47,61,138) !important;
}

::v-deep .el-tabs__item{
  color: #fff;
}
::v-deep .el-tabs__item.is-active{
  color: #409EFF;
}
::v-deep .el-tabs__nav-wrap::after{
  background-color: #313d70;
}


::v-deep .el-button{
  border-radius: 2px;
}
::v-deep .el-pagination{
  position: absolute;
  bottom: 10px;
  left: 50%;
  transform: translateX(-50%);
}
::v-deep .el-pagination__total{
  color: #f3ffff;
}
::v-deep .el-pagination__jump{
  color: #f3ffff;
}
::v-deep .el-pager{
  margin: 0 5px;
}
::v-deep .el-table .el-table__body-wrapper{
  background-color: #2F3D8A;
}
::v-deep .el-form--inline .el-form-item{
  margin-right: 12px;
}
::v-deep .el-input__inner{
  //color: #f3ffff !important;
  color: #606266 !important;
}
::v-deep .el-date-editor .el-range-input{
  //color: #f3ffff;
  color: #606266 !important;
}
</style>

