<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">
          <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"
          />

        </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-tabs v-model="activeTab" @tab-click="handleTabChange">
          <el-tab-pane label="电表读数" name="first">
          </el-tab-pane>
          <el-tab-pane label="水表读数" name="second">
          </el-tab-pane>
        </el-tabs>
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="68px">
          <el-form-item label="记录时间">
            <el-date-picker
              v-model="daterangeRecordTime"
              style="width: 240px"
              value-format="yyyy-MM-dd HH:mm"
              type="datetimerange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="handleQuery"
            ></el-date-picker>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-table v-if="activeTab === 'first'" v-loading="loading" :data="elecMeterHList">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="表计名称" align="left" prop="deviceName" width="250px"/>
          <el-table-column label="表计编号" align="left" prop="deviceCode"/>
          <el-table-column label="抄表时间" align="center" prop="recordTime" width="180">
            <template slot-scope="scope">
              <span>{{ formatDateTime(scope.row.recordTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="计量类型" align="center" prop="meterType">
            <template slot-scope="scope">
              <span>{{ getElecMeterType(scope.row.meterType) + "( "+scope.row.meterUnitPrice + " )"}}</span>
            </template>
          </el-table-column>

          <el-table-column label="用电量(kW·h)" align="center" prop="elecQuantity"/>
          <el-table-column label="小时电费" align="center" prop="useElecCost"/>
        </el-table>

        <el-table v-if="activeTab === 'second'" v-loading="loading" :data="waterMeterHList">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="表计名称" align="left" prop="deviceName" width="250"/>
          <el-table-column label="表计编号" align="left" prop="deviceCode"/>
          <el-table-column label="抄表时间" align="center" prop="recordTime" width="180">
            <template slot-scope="scope">
              <span>{{ formatDateTime(scope.row.recordTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="时间序列" align="center" prop="timeIndex"/>
          <el-table-column label="用水量(t)" align="center" prop="waterQuantity"/>
          <el-table-column label="单位水价" align="center" prop="meterUnitPrice"/>
          <el-table-column label="小时水费" align="center" prop="useWaterCost"/>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getElecList"
        />
        <!-- 添加或修改用电计量-小时对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="园区代码" prop="areaCode">
              <el-input v-model="form.areaCode" placeholder="请输入园区代码"/>
            </el-form-item>
            <el-form-item label="计量设备" prop="deviceCode">
              <el-input v-model="form.deviceCode" placeholder="请输入计量设备"/>
            </el-form-item>
            <el-form-item label="记录时间" prop="recordTime">
              <el-input v-model="form.recordTime" placeholder="记录时间"/>
            </el-form-item>
            <el-form-item label="日期" prop="date">
              <el-date-picker clearable
                              v-model="form.date"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择日期 yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="时间" prop="time">
              <el-time-picker clearable
                              v-model="form.time"
                              type="date"
                              value-format="HH:mm:ss"
                              placeholder="请选择时间 HH:mm:ss"
              >
              </el-time-picker>
            </el-form-item>
            <el-form-item label="时间序列" prop="timeIndex">
              <el-input v-model="form.timeIndex" placeholder="请输入时间序列"/>
            </el-form-item>
            <el-form-item label="用电量" prop="elecQuantity">
              <el-input v-model="form.elecQuantity" placeholder="请输入用电量 单位：kW-h"/>
            </el-form-item>
            <el-form-item label="单位电价" prop="meterUnitPrice">
              <el-input v-model="form.meterUnitPrice" placeholder="请输入单位电价"/>
            </el-form-item>
            <el-form-item label="小时电费" prop="useElecCost">
              <el-input v-model="form.useElecCost" placeholder="请输入小时电费"/>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  listElecMeterH,
  delElecMeterH,
  addElecMeterH,
  updateElecMeterH,
  listWaterMeterH
} from '@/api/device/elecMeterH'
import { areaTreeSelect } from '@/api/basecfg/area'
import { getDeviceTree } from '@/api/device/meterDevice'

export default {
  name: 'ElecMeterH',
  data() {
    return {
      activeTab: 'first',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用电计量-小时表格数据
      elecMeterHList: [],
      // 用水计量-小时表格数据
      waterMeterHList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 小时电费时间范围
      daterangeRecordTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        areaCode: null,
        deviceCode: null,
        recordTime: null,
        startRecTime: null,
        endRecTime: null,
        meterCls: 45,
        orderFlag: 'desc'
      },
      // 区域名称
      areaName: undefined,
      areaOptions: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        areaCode: [
          { required: true, message: '园区代码不能为空', trigger: 'blur' }
        ],
        deviceCode: [
          { required: true, message: '计量设备不能为空', trigger: 'blur' }
        ],
        recordTime: [
          { required: true, message: '记录时间不能为空', trigger: 'blur' }
        ],
        date: [
          { required: true, message: '日期 yyyy-MM-dd不能为空', trigger: 'blur' }
        ],
        time: [
          { required: true, message: '时间 HH:mm:ss不能为空', trigger: 'blur' }
        ],
        timeIndex: [
          { required: true, message: '时间序列不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
     this.getAreaTreeSelect()
    this.getElecList()
  },
  methods: {

    handleTabChange() {
      // 根据newTabName给someParam赋值
      if (this.activeTab === 'first') {
        // 电表读数
        this.queryParams.meterCls = '45'
        this.getElecList()
      } else if (this.activeTab === 'second') {
        // 水表读数
        this.queryParams.meterCls = '70'
        this.getWaterList()
      }
      this.getAreaTreeSelect()
      this.handleQuery()
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      if (data.id === null) {
        this.$message.warning('该节点不是设备不可点击');
        return;
      }
      this.queryParams.deviceCode = data.id
      this.handleQuery()
    },
    /**树结构*/
    async getAreaTreeSelect() {
      await getDeviceTree(0, this.queryParams.meterCls, 0).then(response => {
        this.areaOptions = response.data
      })
    },

    formatDateTime(dateTime) {
      if (!dateTime) return ''
      const date = new Date(dateTime)
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}`
    },
    /** 查询用电计量-小时列表 */
    getElecList() {
      this.loading = true
      listElecMeterH(this.queryParams).then(response => {
        this.elecMeterHList = response.rows
        this.total = response.total
        this.loading = false
      })
    },

    /** 查询用水计量-小时列表 */
    getWaterList() {
      this.loading = true
      listWaterMeterH(this.queryParams).then(response => {
        this.waterMeterHList = response.rows
        this.total = response.total
        this.loading = false
      })
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.Elecreset()
    },
    // 表单重置
    Elecreset() {
      this.form = {
        id: null,
        areaCode: null,
        deviceCode: null,
        recordTime: null,
        date: null,
        time: null,
        timeIndex: null,
        elecQuantity: null,
        meterType: null,
        meterUnitPrice: null,
        useElecCost: null,
        createTime: null
      }
      this.resetForm('form')
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.startRecTime = this.daterangeRecordTime[0]
      this.queryParams.endRecTime = this.daterangeRecordTime[1]
      if (this.activeTab === 'first') {
        this.queryParams.meterCls = '45'
        this.queryParams.pageNum = 1
        this.getElecList()
      } else if (this.activeTab === 'second') {
        this.queryParams.meterCls = '70'
        this.queryParams.pageNum = 1
        this.getWaterList()
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeRecordTime = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.Elecreset()
      this.open = true
      this.title = '添加用电计量-小时'
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateElecMeterH(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getElecList()
            })
          } else {
            addElecMeterH(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getElecList()
            })
          }
        }
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('ems/elecMeterH/export', {
        ...this.queryParams
      }, `elecMeterH_${new Date().getTime()}.xlsx`)
    },
    getElecMeterType(meterType) {
      const meterTypeMap = {
        '-1': '低谷电',
        '0': '平峰电',
        '1': '高峰电',
        '2': '尖峰电'
      }
      return meterTypeMap[meterType] || '未知'
    }
  }
}
</script>
