<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input v-model="areaName" placeholder="请输入区域名称" clearable size="small" prefix-icon="el-icon-search"
                    style="margin-bottom: 20px" />
        </div>
        <div class="head-container" style="height: 100vh; overflow: hidden; position: relative;">
          <el-tree :data="areaOptions" :props="defaultProps" :expand-on-click-node="false"
                   :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current
                   @node-click="handleNodeClick" style="height: calc(100vh - 50px); overflow-y: auto;" />
        </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <!-- 开始时间选择器 -->
          <el-form-item label="开始时间" prop="startRecTime">
            <el-date-picker
              v-model="queryParams.startRecTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:00:00"
              :picker-options="startPickerOptions"
              placeholder="请选择开始时间"
              @change="handleTimeChange('startRecTime')">
            </el-date-picker>
          </el-form-item>

          <!-- 结束时间选择器 -->
          <el-form-item label="结束时间" prop="endRecTime">
            <el-date-picker
              v-model="queryParams.endRecTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:00:00"
              :picker-options="endPickerOptions"
              placeholder="请选择结束时间"
              @change="handleTimeChange('endRecTime')">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button type="warning" plain icon="el-icon-download" size="mini" v-hasPermi="['ems:EmsEcoD:export']" @click="handleExport">导出</el-button>
          </el-form-item>
        </el-form>

        <el-table v-loading="loading" :data="pvSupplyHList" @selection-change="handleSelectionChange">
          <el-table-column label="日期" align="center" prop="date" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.date, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="时间" align="center" prop="time">
            <template slot-scope="scope">
              <span>{{ scope.row.time }}</span>
            </template>
          </el-table-column>
          <el-table-column label="总发电量(kW·h)" align="center" prop="genElecQuantity"/>
          <el-table-column label="自用电量(kW·h)" align="center" prop="useElecQuantity"/>
          <el-table-column label="上网电量(kW·h)" align="center" prop="upElecQuantity"/>
          <el-table-column label="上网收益(￥)" align="center" prop="upElecEarn"/>
        </el-table>
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { areaTreeByFacsCategory } from '@/api/basecfg/area'
import {listPvSupplyH} from "@/api/mgr/pgSupplyH";

export default {
  name: "EmsEcoD",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 节能计量日表格数据
      EmsEcoDList: [],
      pvSupplyHList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      areaOptions: [],
      areaName: undefined,
      facsCategory: 'E',
      facsSubCategory: 'E5',
      // 设施选项
      facsOptions: undefined,
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        areaCode: null,
        startRecTime: null,
        endRecTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        areaCode: [
          {required: true, message: "园区代码不能为空", trigger: "blur"}
        ],
        date: [
          {required: true, message: "日期不能为空", trigger: "blur"}
        ],
      },
      // 时间选择器配置
      startPickerOptions: {
        disabledDate: (time) => {
          return time.getTime() > Date.now() - 8.64e7 // 禁用未来时间
        },
        selectableRange: this.generateHourRanges()
      },
      endPickerOptions: {
        disabledDate: (time) => {
          if (this.queryParams.startRecTime) {
            return time.getTime() < new Date(this.queryParams.startRecTime).getTime() ||
              time.getTime() > Date.now() - 8.64e7
          }
          return time.getTime() > Date.now() - 8.64e7
        },
        selectableRange: this.generateHourRanges()
      }
    };
  },
  created() {
    this.getAreaList();
    this.getList();
  },
  methods: {
    /** 查询节能计量日列表 */
    getList() {
      this.loading = true;
      listPvSupplyH(this.queryParams).then(response => {
        this.pvSupplyHList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 查询区域列表
    async getAreaList () {
      await areaTreeByFacsCategory(this.facsCategory, this.facsSubCategory, false).then(response => {
        this.areaOptions = [{
          id: '-1',
          label: '全部',
          children: []
        }].concat(response.data)
        this.selectedLabel = '全部'
        this.queryParams.areaCode = '-1'
      })
    },
    // 生成整点时间范围
    generateHourRanges() {
      const ranges = []
      for (let i = 0; i < 24; i++) {
        const start = `${i.toString().padStart(2, '0')}:00:00`
        const end = `${i.toString().padStart(2, '0')}:59:59`
        ranges.push(`${start} - ${end}`)
      }
      return ranges
    },

    // 时间选择处理
    handleTimeChange(field) {
      if (this.queryParams[field]) {
        const date = new Date(this.queryParams[field])
        // 手动格式化日期（替代moment.js）
        const formatDate = (d) => {
          const pad = (n) => String(n).padStart(2, '0')
          return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:00:00`
        }
        this.queryParams[field] = formatDate(date)
      }

      // 自动同步结束时间范围
      if (field === 'startRecTime' && this.queryParams.endRecTime) {
        this.$nextTick(() => {
          this.$refs.queryForm.validateField('endRecTime')
        })
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        areaCode: null,
        date: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('ems/prod/pv/hour/export', {
        ...this.queryParams
      }, `产能报表_${new Date().getTime()}.xlsx`)
    },
    // 筛选节点
    filterNode (value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick (data) {
      this.queryParams.areaCode = data.id
      this.selectedLabel = data.label
      this.getList()
    }
  }
};
</script>
