<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" label-width="68px">
          <el-form-item label="设备代码" prop="deviceCode">
            <el-input v-model="queryParams.deviceCode" placeholder="请输入设备代码" clearable @keyup.enter.native="handleQuery" />
          </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-loading="loading" :data="deviceList">
          <el-table-column label="计量对象" align="left" prop="objName" width="300px">
            <template slot-scope="scope">
              <span>{{ "（" + getObjTypeName(scope.row.objType) + "）"+ scope.row.objName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="设备代码" align="center" prop="deviceCode" />
          <el-table-column label="计量标签" align="center" prop="objTag">
            <template slot-scope="scope">
              <span>{{ getObjTagName(scope.row.objTag) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="抄表周期" align="center" prop="colCycle">
            <template slot-scope="scope">
              <span>{{ getColCycleName(scope.row.colCycle) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="上次抄表日期" align="center" prop="lastTime" />
          <el-table-column label="上次抄表示数" align="center" prop="lastReading" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" :disabled="!canFill(scope.row.lastTime)" icon="el-icon-info" @click="handleRecord(scope.row)">
                填报</el-button>
              <el-button size="mini" type="text"  icon="el-icon-document" @click="handleViewRec(scope.row)">
                查看</el-button>

            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
          @pagination="getList" />
        <el-dialog :title="fillTitle" :visible.sync="fillFormOpen" width="500px" append-to-body>
          <el-form ref="fillForm" :model="fillForm" label-width="150px">
            <el-form-item label="设备编码">
              <el-input disabled :value="fillForm.deviceCode" />
            </el-form-item>
            <el-form-item label="上次抄表日期">
              <el-input disabled :value="fillForm.lastTime" />
            </el-form-item>
            <el-form-item label="上次抄表示数">
              <el-input disabled :value="fillForm.lastReading" />
            </el-form-item>
            <hr>
            <el-form-item label="本次抄表月份">
              <el-input disabled :value="currentMonth" />
            </el-form-item>
            <el-form-item required :rules="[{required:true,message:'请输入本次抄表示数'}]" label="本次抄表示数" prop="meterReading">
              <el-input v-model="fillForm.meterReading" oninput="value=value.replace(/[^\d]/g,'')" placeholder="请输入本次抄表示数" />
            </el-form-item>
            <el-form-item label="综合倍率" prop="magnification">
              <el-input disabled :value="fillForm.magnification" />
            </el-form-item>
            <el-form-item :label="`参考增量(${activeTab==='first'?'度':'吨'})`">
              <el-input disabled :value="increase" />
            </el-form-item>
          </el-form>

          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitFillForm">确 定</el-button>
            <el-button @click="fillCancel">取 消</el-button>
          </div>
        </el-dialog>
        <!-- 历史抄表记录 -->
        <el-dialog :title="title" :visible.sync="recListOpen" width="1200px" append-to-body>
          <el-form ref="recListForm" :model="recListForm" label-width="80px">
            <el-form-item label="年份" prop="year">
              <el-date-picker v-model="recListForm.year" :clearable="false" @change="getHistoryList" value-format="yyyy" type="year"
                placeholder="选择年份">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="计量设备" prop="year">
              <el-input disabled :value="recListForm.deviceCode" />
            </el-form-item>
            <el-form-item label="抄表历史" prop="recList">
              <el-table v-loading="loading" :data="recListForm.recList" max-height="280px">
                <el-table-column label="年份" align="center" prop="year" />
                <el-table-column label="月份" align="center" prop="meterMonth" >
                  <template slot-scope="scope">
                    <!-- 使用 JavaScript 字符串方法截取月份部分 -->
                    {{ scope.row.meterMonth.slice(-2) }}
                  </template>
                </el-table-column>
                <el-table-column label="抄表示数" align="center" prop="meterReading" />
                <el-table-column label="用量" align="center" prop="increase" />
                <el-table-column label="抄表日期" align="center" prop="meterTime" />
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                  <template slot-scope="scope">
                    <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="!canEdit(scope.row.meterMonth)"
                      @click="updateRecord(scope.row)">修改</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="closeRecList">关 闭</el-button>
          </div>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { listDevice } from '@/api/device/meterDevice'
import { listMeterReadingByParam, getLastRecord, addMeterReading, updateMeterReading, delMeterReading } from '@/api/device/meterRead'
import { areaTreeSelect, areaTreeSelectByTag } from '@/api/basecfg/area'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { dateFormat } from '@/utils/index.js'
export default {
  name: 'Device',
  components: { Treeselect },
  data() {
    const nowDay = new Date()
    return {
      currentMonth: dateFormat(nowDay, 'yyyyMM'),
      activeTab: 'first',
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 计量设备表格数据
      deviceList: [],
      // 弹出层标题
      title: '',
      // 记录表单开启
      recListOpen: false,
      // 填报表单开启
      fillFormOpen: false,
      // 区域名称
      areaName: undefined,
      areaOptions: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 能源分类树
      emsClsOptions: [
        { code: 45, name: '电表' },
        { code: 70, name: '水表' }
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        areaCode: null,
        deviceCode: null,
        meterCls: 45
      },
      // 电表表单参数
      recListForm: {
        year: '',
        deviceCode: '',
        recList: []
      },
      fillTitle: '',
      fillForm: {
        id: '',
        deviceCode: '',
        areaCode: '',
        lastTime: '',
        lastReading: '',
        meterTime: '',
        meterReading: '',
        increase: '',
        magnification: 1
      },
      curRow: {},
      ifAdd: true // 判断 新增还是修改
    }
  },
  computed: {
    increase() {
      const { meterReading, magnification, lastReading } = this.fillForm
      if (meterReading && magnification) {
        return (meterReading - (lastReading || 0)) * magnification
      }
      return ''
    }
  },
  created() {
    this.getAreaTreeByTag('Area', 'Area_01')
    this.getList()
  },

  methods: {
    /** 查询计量设备列表 */
    getList() {
      this.loading = true
      listDevice(this.queryParams).then(response => {
        this.deviceList = response.rows.map(item=>({
          ...item,
          meterMonth:'',
          lastTime:'',
          lastReading:'',
        }))
        this.total = response.total
        this.loading = false
        this.deviceList.forEach(async item => {
          await getLastRecord(item.areaCode, item.deviceCode).then(({ data }) => {
            if (data) {
              item.lastTime = data.meterTime
              item.meterMonth = data.meterMonth
              item.lastReading = data.meterReading
            }
          })
        })
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    handleTabChange() {
      // 根据newTabName给someParam赋值
      if (this.activeTab === 'first') {
        // 电表抄表
        this.queryParams.meterCls = '45'
      } else if (this.activeTab === 'second') {
        // 水表抄表
        this.queryParams.meterCls = '70'
      }
      this.handleQuery()
    },
    getObjTypeName(objType) {
      const typeMap = {
        1: '区块',
        2: '设备'
      }
      return typeMap[objType] || '未知'
    },
    getColCycleName(colCycle) {
      const cycleMap = {
        0: '实时',
        1: '分钟',
        2: '小时',
        3: '天',
        4: '月'
      }
      return cycleMap[colCycle] || ''
    },
    getObjTagName(objTag) {
      const tagMap = {
        0: '公摊表',
        1: '个户表'
      }
      return tagMap[objTag] || '未知'
    },
    async getAreaTreeByTag(tier, tagCode) {
      await areaTreeSelectByTag(tier, tagCode).then(response => {
        this.areaOptions = response.data
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.areaCode = data.id
      this.handleQuery()
    },
    handleViewRec(row) {
      this.recListForm = this.$options.data().recListForm
      this.resetForm('recListForm')
      this.title = '（' + this.getObjTypeName(row.objType) + '）' + row.objName
      this.curRow = row
      this.recListForm.year = dateFormat(new Date(), 'yyyy')
      this.recListForm.deviceCode = row.deviceCode
      this.getHistoryList()
      this.recListOpen = true
    },
    getHistoryList() {
      const { areaCode, deviceCode } = this.curRow
      listMeterReadingByParam({
        areaCode,
        deviceCode,
        year: this.recListForm.year,
        orderFlag: 'desc'
      }).then(response => {
        this.recListForm.recList = response.data || []
      })
    },
    async handleRecord(row) {
      this.fillForm = this.$options.data().fillForm
      this.resetForm('fillForm')
      this.fillTitle = '（' + this.getObjTypeName(row.objType) + '）' + row.objName
      this.fillForm.deviceCode = row.deviceCode
      this.fillForm.areaCode = row.areaCode
      this.fillForm.magnification = row.magnification
      this.fillForm.lastTime = row.lastTime
      this.fillForm.lastReading = row.lastReading
      this.ifAdd = true
      // let existFlag = false
      // // 获取上次填报记录
      // await getLastRecord(row.areaCode, row.deviceCode).then(({ data }) => {
      //   if (data) {
      //     if (data.meterMonth === this.currentMonth) {
      //       existFlag = true
      //     } else {
      //       this.fillForm.lastTime = data.meterTime
      //       this.fillForm.lastReading = data.meterReading
      //     }
      //   }
      // })
      // if (row.meterMonth===this.currentMonth) {
      //   this.$modal.msgError('当前月份已填报')
      // } else {
        this.fillFormOpen = true
      // }
    },
    canEdit(meterMonth) {
      return meterMonth === this.currentMonth
    },
    canFill (lastTime) {
      return dateFormat(new Date(lastTime),'yyyyMM')!==this.currentMonth
    },
    updateRecord(row) {
      this.ifAdd = false
      this.fillFormOpen = true
      this.fillForm = this.$options.data().fillForm
      this.resetForm('fillForm')
      this.fillTitle = this.curRow.objName
      this.fillForm.deviceCode = this.curRow.deviceCode
      this.fillForm.areaCode = this.curRow.areaCode
      this.fillForm.magnification = this.curRow.magnification
      this.fillForm.id = row.id
      this.fillForm.lastTime = row.lastTime
      this.fillForm.lastReading = row.lastReading
      this.fillForm.meterReading = row.meterReading
    },
    submitFillForm() {
      this.$refs['fillForm'].validate(valid => {
        if (valid) {
          this.fillForm.increase = this.increase
          if (this.ifAdd) {
            addMeterReading(this.fillForm).then(({ code, msg }) => {
              if (code === 200) {
                this.$modal.msgSuccess('填报成功')
                this.fillFormOpen = false
              } else {
                this.$modal.msgError(msg)
              }
            })
          } else {
            updateMeterReading(this.fillForm).then(({ code, msg }) => {
              if (code === 200) {
                this.$modal.msgSuccess('修改成功')
                this.getHistoryList()
                this.fillFormOpen = false
              } else {
                this.$modal.msgError(msg)
              }
            })
          }
        }
      })
    },
    fillCancel() {
      this.fillFormOpen = false
    },
    closeRecList() {
      this.recListOpen = false
    }
  }
}
</script>
