<template>
  <div class="app-container home">
    <el-row :gutter="20">
      <el-col :span="24" :xs="24">
        <el-form :model="filterForm" ref="queryRef" :inline="true" label-width="68px">
<!--          <el-form-item label="能源类型" prop="week">-->
<!--            <el-select v-model="filterForm.type" placeholder="请选择" style="width: 240px">-->
<!--              <el-option label="电" value="1" />-->
<!--            </el-select>-->
<!--          </el-form-item>-->
          <el-form-item label="耗能设备" prop="week">
            <el-select v-model="filterForm.dev" 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="时段" style="width: 308px;">
            <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button class="my-btn btn1" type="primary" :class="{ active: activeIndex === 1 }" @click="handleHour">时</el-button>
            <el-button class="my-btn btn2" type="primary" :class="{ active: activeIndex === 2 }" @click="handleDay">日</el-button>
            <el-button class="my-btn btn3" type="primary" :class="{ active: activeIndex === 3 }" @click="handleMonth">月</el-button>
          </el-col>
        </el-row>
        <div class="dev_control_table">
          <el-table :data="dataTable" height="690px">
            <el-table-column label="序号" type="index" :index="indexMethod1" width="60" fixed/>
            <el-table-column label="耗能设备" align="center" prop="deviceName" width="150" fixed/>
<!--            <el-table-column label="日期" align="center" prop="dayDate" width="150" fixed/>-->
            <el-table-column v-for="item in theadList" :key="item.prop" :prop="item.prop" :label="item.label" :fixed="item.fixed" :width="item.width" align="center"/>
            <el-table-column label="操作" fixed="right">
              <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="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[5, 10, 20, 50]"
              :small="small"
              :disabled="disabled"
              :background="background"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"/>
        </div>
      </el-col>
    </el-row>



    <!-- 生成图表弹出窗 -->
    <el-dialog class="mrt" :title="title" v-model="open" width="50%" append-to-body :close-on-click-modal="false" :show-close="false">
      <div class="chartBox">
        <div id="chart"></div>
      </div>

      <el-button class="floatRight" @click=close>关闭</el-button>
    </el-dialog>
  </div>
</template>

<script setup name="Index">
import {Delete,Histogram} from '@element-plus/icons-vue'
import {ref, reactive, onMounted, watch,onBeforeUnmount} from "vue";
import {getTable} from '@/api/analyse/nhtj/nhtj'
import { getDevice } from "@/api/control/manual"
import * as echarts from "echarts";

/** 页面加载时*/
onMounted(()=>{
  formattedDateFun();
  getTableFun();
  getDeviceList()
})


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


/** 筛选处理 */
//渲染设备列表
const deviceName = ref([])
function getDeviceList(){
  getDevice().then((res)=>{
    deviceName.value = res.data
  })
}

const dateRange = ref([]);
const startDate = ref()
const endDate = ref()
const data = reactive({
  filterForm: {
    dev: '0',
  }
});
//拿到耗能设备的devid
const checkDevId = ref();
function handleDevChange(devid){
  console.log('点击的devid：',devid)
  checkDevId.value = devid
}

//监听日期选择
const wacthSelectDate = watch(()=> dateRange.value,(val) =>{
  console.log(val[0])
  startDate.value = val[0]
  console.log(val[1])
  endDate.value = val[1]
})
//搜索按钮
function handleQuery(){
  getTableFun()
}
//重置按钮
function resetQuery(){
  dateRange.value = [];
  currentPage.value = 1
  pageSize.value = 10
  data.filterForm.dev = '0'
  checkDevId.value = null
  getTable({
    "deviceId":null,
    "timeType":activeIndex.value,
    "startTime":null,
    "endTime":YYYYMMDD.value,
    "pageNum": 1,
    "pageSize": 10
  }).then((res)=>{
    total.value = res.total;
    dataTable.value = res.rows
  })
}


/** 数据表格处理 */
//公共表头
const theadList = ref([
  {prop:'dayDate', label:'日期',fixed:'fixed',width:'120px'},
  {prop:'hour00', label:'00:00'},
  {prop:'hour01', label:'01:00'},
  {prop:'hour02', label:'02:00'},
  {prop:'hour03', label:'03:00'},
  {prop:'hour04', label:'04:00'},
  {prop:'hour05', label:'05:00'},
  {prop:'hour06', label:'06:00'},
  {prop:'hour07', label:'07:00'},
  {prop:'hour08', label:'08:00'},
  {prop:'hour09', label:'09:00'},
  {prop:'hour10', label:'10:00'},
  {prop:'hour11', label:'11:00'},
  {prop:'hour12', label:'12:00'},
  {prop:'hour13', label:'13:00'},
  {prop:'hour14', label:'14:00'},
  {prop:'hour15', label:'15:00'},
  {prop:'hour16', label:'16:00'},
  {prop:'hour17', label:'17:00'},
  {prop:'hour18', label:'18:00'},
  {prop:'hour19', label:'19:00'},
  {prop:'hour20', label:'20:00'},
  {prop:'hour21', label:'21:00'},
  {prop:'hour22', label:'22:00'},
  {prop:'hour23', label:'23:00'},
])
//内容
const dataTable = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
const total = ref()
//翻页时不刷新序号
function indexMethod1(index){
  return index+(currentPage.value-1)*pageSize.value+1
}
//获取表格数据
function getTableFun(){
  getTable({
    "deviceId":checkDevId.value,
    "timeType":activeIndex.value,
    "startTime":startDate.value,
    "endTime":endDate.value,
    "pageNum": currentPage.value,
    "pageSize": pageSize.value
  }).then((res)=>{

    total.value = res.total;
    for(let i in res.rows){
      if(res.rows[i].monthDate){
        res.rows[i].monthDate=res.rows[i].monthDate.slice(0,7)
      }else if(res.rows[i].yearDate){
        res.rows[i].yearDate=res.rows[i].yearDate.slice(0,4)
      }
    }
    dataTable.value = res.rows
    console.log('发电量数据',dataTable.value)
  })
}
const handleSizeChange = (val) => {
  console.log(`${val}`)
  getTableFun()
}
const handleCurrentChange = (val) => {
  console.log(`${val}`)
  getTableFun()
}


/** 生成图表按鈕操作*/
const title = ref()
const open = ref(false)
const chartDataArr = ref([])
const showDevName = ref()
function handleChart(scope){
  console.log(scope.row)
  open.value = true;
  showDevName.value = scope.row.deviceName
  if(scope.row.dayDate){
    delete scope.row.dayDate
    delete scope.row.dayId
    delete scope.row.deviceId
    delete scope.row.deviceName
  }else if(scope.row.monthDate){
    delete scope.row.monthDate
    delete scope.row.monthId
    delete scope.row.deviceId
    delete scope.row.deviceName
  }else if (scope.row.yearDate){
    delete scope.row.yearDate
    delete scope.row.yearId
    delete scope.row.deviceId
    delete scope.row.deviceName
  }

  for(let i in scope.row){
    chartDataArr.value.push(scope.row[i])
  }
  console.log(chartDataArr.value)
  setTimeout(()=>{
    eleBarChartFun()
  },100)
};

//用电量柱状图
const barChartX = ref(['00:00','01:00','02:00','03:00','04:00','05:00','06:00','07:00','08:00','09:00','10:00','11:00','12:00','13:00','14:00','15:00','16:00','17:00','18:00','19:00','20:00','21:00','22:00','23:00'])
let myChart;
function eleBarChartFun(){
  const chartDom = document.getElementById('chart')
  myChart = echarts.init(chartDom);
  const option = {
    title: {},
    legend: {
      data: [`用电量（${showDevName.value}）`],
      // selectedMode: 'single',
      textStyle: {
        color: "#333"
      }
    },
    tooltip: {
      trigger: "axis",
      formatter: "{b0}： {c0}kWh",
      // borderColor: '#00fcff',
      borderWidth: 1
    },
    grid:{
      show: true,
      top: '10%',
      bottom:'10%',
      left:'5%',
      right:'3%',
      borderWidth: 1,
      borderColor: '#767da1',
    },
    textStyle:{
      color:'#BEC3DA'
    },
    xAxis: {
      data: barChartX.value,
      axisLine:{
        lineStyle:{
          color:'#BEC3DA',
          type:'dashed'
        }
      },
      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",
      splitLine:{
        show:true,
        lineStyle:{
          type:'dashed',
          color:'#BEC3DA'
        }
      },
      axisLine: {
        show: true,
        lineStyle:{
          type:'dashed',
          color:'#BEC3DA'
        }
      },
    },
    series: [
      {
        name: `用电量（${showDevName.value}）`,
        type: "bar",
        data: chartDataArr.value,
        itemStyle:{
          color:'#2F8EE0'
        },
      },
    ],
  };
  option && myChart.setOption(option);
  window.onresize = function () {//自适应大小
    myChart.resize();
  };
}

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

/** 日月年按钮操作 */
const activeIndex = ref(1)
function handleHour() {
  activeIndex.value = 1
  theadList.value = [
    {prop:'dayDate', label:'日期',fixed:'fixed',width:'120px'},
    {prop:'hour00', label:'00:00'},
    {prop:'hour01', label:'01:00'},
    {prop:'hour02', label:'02:00'},
    {prop:'hour03', label:'03:00'},
    {prop:'hour04', label:'04:00'},
    {prop:'hour05', label:'05:00'},
    {prop:'hour06', label:'06:00'},
    {prop:'hour07', label:'07:00'},
    {prop:'hour08', label:'08:00'},
    {prop:'hour09', label:'09:00'},
    {prop:'hour10', label:'10:00'},
    {prop:'hour11', label:'11:00'},
    {prop:'hour12', label:'12:00'},
    {prop:'hour13', label:'13:00'},
    {prop:'hour14', label:'14:00'},
    {prop:'hour15', label:'15:00'},
    {prop:'hour16', label:'16:00'},
    {prop:'hour17', label:'17:00'},
    {prop:'hour18', label:'18:00'},
    {prop:'hour19', label:'19:00'},
    {prop:'hour20', label:'20:00'},
    {prop:'hour21', label:'21:00'},
    {prop:'hour22', label:'22:00'},
    {prop:'hour23', label:'23:00'},
  ]
  getTableFun()
  barChartX.value = ['00:00','01:00','02:00','03:00','04:00','05:00','06:00','07:00','08:00','09:00','10:00','11:00','12:00','13:00','14:00','15:00','16:00','17:00','18:00','19:00','20:00','21:00','22:00','23:00']
};
function handleDay() {
  activeIndex.value = 2
  theadList.value = [
    {prop:'monthDate', label:'月份',fixed:'fixed',width:'120px'},
    {prop:'day01', label:'01日'},
    {prop:'day02', label:'02日'},
    {prop:'day03', label:'03日'},
    {prop:'day04', label:'04日'},
    {prop:'day05', label:'05日'},
    {prop:'day06', label:'06日'},
    {prop:'day07', label:'07日'},
    {prop:'day08', label:'08日'},
    {prop:'day09', label:'09日'},
    {prop:'day10', label:'10日'},
    {prop:'day11', label:'11日'},
    {prop:'day12', label:'12日'},
    {prop:'day13', label:'13日'},
    {prop:'day14', label:'14日'},
    {prop:'day15', label:'15日'},
    {prop:'day16', label:'16日'},
    {prop:'day17', label:'17日'},
    {prop:'day18', label:'18日'},
    {prop:'day19', label:'19日'},
    {prop:'day20', label:'20日'},
    {prop:'day21', label:'21日'},
    {prop:'day22', label:'22日'},
    {prop:'day23', label:'23日'},
    {prop:'day24', label:'24日'},
    {prop:'day25', label:'25日'},
    {prop:'day26', label:'26日'},
    {prop:'day27', label:'27日'},
    {prop:'day28', label:'28日'},
    {prop:'day29', label:'29日'},
    {prop:'day30', label:'30日'},
    {prop:'day31', label:'31日'},
  ]
  getTableFun()
  barChartX.value = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31']
};
function handleMonth() {
  activeIndex.value = 3
  theadList.value = [
    {prop:'yearDate', label:'年份',fixed:'fixed',width:'120px'},
    {prop:'month01', label:'01月'},
    {prop:'month02', label:'02月'},
    {prop:'month03', label:'03月'},
    {prop:'month04', label:'04月'},
    {prop:'month05', label:'05月'},
    {prop:'month06', label:'06月'},
    {prop:'month07', label:'07月'},
    {prop:'month08', label:'08月'},
    {prop:'month09', label:'09月'},
    {prop:'month10', label:'10月'},
    {prop:'month11', label:'11月'},
    {prop:'month12', label:'12月'},
  ]
  getTableFun()
  barChartX.value = ['1','2','3','4','5','6','7','8','9','10','11','12']
};


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



const { filterForm } = toRefs(data);
</script>

<style scoped lang="scss">
.dev_control_table{
  position: relative;
  width: 100%;
  min-height: 745px;
  background-color: #2F3D8A;
}
.my-btn{
  padding: 0 25px;
  background-color: #2F8EED40;
  border: 1px solid #2F8EED;
}
.btn2,.btn3{
  margin-left: -1px;
}
.btn1{
  border-top-right-radius: 0px !important;
  border-bottom-right-radius: 0px !important;
}
.btn2{
  border-radius: 0px !important;
}
.btn3{
  border-top-left-radius: 0px !important;
  border-bottom-left-radius: 0px !important;
}
.active{
  background-color: #409eff !important;
  color: #fff !important;
}
.chartBox{
  width: 100%;
  height: 300px;
  #chart{
    width: 100%;
    height: 100%;
  }
}
.floatRight{
  margin-left: 90%;
}
::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-table__body-wrapper tr td.el-table-fixed-column--left{
  background-color: #2F3D8A;
}
::v-deep .el-table__body-wrapper tr td.el-table-fixed-column--right{
  background-color: #2F3D8A;
}
::v-deep .el-input__inner{
  //color: #f3ffff !important;
  color: #606266 !important;
}
::v-deep .el-date-editor .el-range-input{
  //color: #f3ffff;
  color: #606266 !important;
}
::v-deep .el-table__row:hover td{
  background-color: #fff !important;
  color: #000 !important;
}
@media (max-width:960px) {
  .app-container{
    padding: 8px;
  }
  .chartBox{
    width: 100%;
    height: 250px;
    #chart{
      width: 100%;
      height: 100%;
    }
  }
}
</style>

