<template>
  <div>
    <div class="title">环境记录</div>
    <div class="line-charts">
      <div class="header">
        <div class="header-title">环境监控图</div>
        <div class="header-sub">
          <el-select v-model="client_id" placeholder="请选择柜体" @change="(val) => valueChange('id',val)">
            <el-option
              v-for="item in $store.getters.clientOptions"
              :key="item.id"
              :label="item.client_name"
              :value="item.client_id"
            />
          </el-select>
          <el-select v-model="client_date" placeholder="请选择" @change="(val) => valueChange('date',val)">
            <el-option
              v-for="(item,index) in options"
              :key="index"
              :label="item"
              :value="index+1"
            />
          </el-select>
          <el-radio-group v-model="radio1" @change="(val) => valueChange('radio',val)">
            <el-radio-button :label="1">温度</el-radio-button>
            <el-radio-button :label="2">湿度</el-radio-button>
            <el-radio-button :label="3">VOC含量</el-radio-button>
          </el-radio-group>
        </div>
      </div>
      <div
        id="line"
        v-loading="loadingLine"
        element-loading-text="拼命加载中"
      />
      <div />
    </div>
    <div class="line-charts">
      <div class="header">
        <div class="header-title">每日温度记录</div>
        <div class="header-sub">
          <el-select v-model="daily_client_id" placeholder="请选择柜体">
            <el-option
              v-for="item in $store.getters.clientOptions"
              :key="item.id"
              :label="item.client_name"
              :value="item.client_id"
            />
          </el-select>
          <el-date-picker
            v-model="value"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
          <el-button type="primary" icon="el-icon-search" @click="getDailyData">搜索</el-button>
          <el-button type="primary" icon="el-icon-download" plain>导出报表</el-button>
          <el-button icon="el-icon-refresh" circle @click="getDailyData" />
        </div>
      </div>
      <el-table
        v-loading="loading"
        stripe
        element-loading-text="拼命加载中"
        :header-cell-style="headerStyle"
        :data="tableData"
        height="40vh"
      >
        <el-table-column align="center" type="index" width="50" label="序号" />
        <el-table-column align="center" property="client_name" label="柜体名称" />
        <el-table-column align="center" property="place" label="所处位置" />
        <el-table-column align="center" property="day_date" label="日期" />
        <el-table-column
          align="center"
          property="avg_wd"
          label="温度（取平均值）"
          :formatter="(row, column) => row.avg_wd + ' °C'"
        />
        <el-table-column
          align="center"
          property="avg_sd"
          label="湿度（取平均值）"
          :formatter="(row, column) => row.avg_sd + ' RH%'"
        />
        <el-table-column
          align="center"
          property="avg_voc"
          label="VOC含量（取平均值）"
          :formatter="(row, column) => row.avg_voc + ' ppm'"
        />
        <el-table-column align="center" property="client_id" label="操作">
          <template slot-scope="scope">
            <el-button @click="handleOpt(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="my-pagination" style="text-align: center">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page.sync="page"
          :total="total"
          :page-size.sync="page_size"
          @current-change="pageChange"
        />
      </div>
    </div>
    <el-dialog :visible.sync="dialogVisible" :close-on-click-modal="false" title="温度记录详情" @close="handleClose">
      <div class="env-header">
        <el-time-picker
          v-model="record_value"
          is-range
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          placeholder="选择时间范围"
          value-format="HH:mm:ss"
          @change="changeValue"
        />
        <el-button style="float: right" type="primary" icon="el-icon-download" plain>导出报表</el-button>
      </div>
      <el-table
        v-loading="recordLoading"
        stripe
        element-loading-text="拼命加载中"
        :header-cell-style="headerStyle"
        :data="recordData"
        height="40vh"
      >
        <el-table-column align="center" type="index" width="50" label="序号" />
        <el-table-column align="center" property="day_date" label="时间" />
        <el-table-column
          align="center"
          property="wd"
          label="温度（取平均值）"
          :formatter="(row, column) => row.wd + ' °C'"
        />
        <el-table-column
          align="center"
          property="sd"
          label="湿度（取平均值）"
          :formatter="(row, column) => row.sd + ' RH%'"
        />
        <el-table-column
          align="center"
          property="voc"
          label="VOC含量（取平均值）"
          :formatter="(row, column) => row.voc + ' ppm'"
        />
      </el-table>
      <div class="my-pagination" style="text-align: center">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page.sync="record_page"
          :total="record_total"
          :page-size.sync="record_page_size"
          @current-change="recordPageChange"
        />
      </div>
    </el-dialog>
  </div>

</template>

<script>
import { get_monitoring_info } from '@/api/reagent/overView'
import stringify from '@/utils/stringify'
import { day_monitor, day_monitor_info } from '@/api/reagent/envrecord'
import { parseTime } from '@/utils'

export default {
  name: 'EnvRecord',
  data() {
    return {
      page: 1,
      page_size: 15,
      total: 0,
      client_id: undefined,
      radio1: '1',
      client_date: 1,
      options: ['近24小时', '近七天', '近一个月'],
      myChart2: undefined,
      linechartData: [],
      headerStyle: { 'background': '#E6E6E6' },
      // 每日温度记录
      tableData: [],
      loading: true,
      daily_client_id: undefined,
      value: '',
      // 温度记录详情
      dialogVisible: false,
      recordLoading: true,
      record_client_id: undefined,
      recordData: [],
      record_page: 1,
      record_page_size: 15,
      record_total: 0,
      record_value: '',
      record_day: undefined,
      start_time: undefined,
      end_time: undefined,
      loadingLine: true
    }
  },
  created() {
    this.client_id = this.$store.getters.clientOptions[0].client_id
    this.daily_client_id = this.client_id
    this.getMonitoringData()
    this.getDailyData()
    this.initCharts()
  },
  beforeDestroy() {
    window.removeEventListener('resize', () => {
      this.myChart2.resize()
    })
  },
  methods: {
    valueChange(t, value) {
      this.getMonitoringData()
      this.lineCharts(t)
    },
    getDailyData() {
      const data = {
        client_id: this.daily_client_id,
        start_time: this.value ? this.value[0] : '',
        end_time: this.value ? this.value[1] : '',
        page: this.page,
        page_size: this.page_size
      }
      this.loading = true
      day_monitor(stringify(data)).then(res => {
        this.tableData = res.data.data_list
        this.total = res.data.total_count
      }).finally(() => {
        this.loading = false
      })
    },
    getMonitoringData() {
      const data = {
        client_id: this.client_id,
        time_type: this.client_date,
        obj_type: this.radio1
      }
      this.loadingLine = true
      get_monitoring_info(stringify(data)).then(
        res => {
          this.linechartData = res.data
        }
      ).finally(() => {
        this.loadingLine = false
      })
    },
    initCharts() {
      this.lineCharts()
      window.addEventListener('resize', () => {
        this.myChart2.resize()
      })
    },
    lineCharts(t) {
      if (t) {
        this.myChart2.clear()
      } else {
        this.myChart2 = this.$echarts.init(
          document.getElementById('line')
        )
      }
      const raOption = ['温度', '湿度', 'VOC含量']
      const tmp = ['°C', 'RH%', 'ppm']
      const option = {
        title: {
          text: this.options[this.client_date - 1] + raOption[this.radio1 - 1] + '变化',
          textStyle: { fontSize: 15, color: '#606266' }
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {},
        toolbox: {
          show: true,
          feature: {
            magicType: { type: ['line', 'bar'] },
            saveAsImage: {}
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.linechartData.map(item => item.record_date)
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value} ' + tmp[[this.radio1 - 1]]
          }
        },
        series: [
          {
            name: this.$store.getters.clientOptions.find(item => item.client_id === this.client_id).client_name,
            type: 'line',
            smooth: true,
            data: this.linechartData.map(item => item.data_value),
            markPoint: {
              data: [
                { type: 'max', name: 'Max' },
                { type: 'min', name: 'Min' }
              ]
            },
            markLine: {
              data: [{ type: 'average', name: 'Avg' }]
            },
            areaStyle: {
              normal: {
                color: new this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                  offset: 0, color: '#409EFF' // 0% 处的颜色
                }, {
                  offset: 1, color: '#E9EDF3' // 100% 处的颜色
                }]
                ) // 背景渐变色
              }
            }
          }
        ]
      }
      this.myChart2.setOption(option)
    },
    pageChange(page) {
      this.page = page
      this.getDailyData()
    },
    recordPageChange() {
      this.getRcordData()
    },
    getRcordData() {
      const data = {
        client_id: this.record_client_id,
        start_time: this.start_time,
        end_time: this.end_time,
        page: this.record_page,
        page_size: this.record_page_size
      }
      this.recordLoading = true
      day_monitor_info(stringify(data)).then(
        res => {
          this.recordData = res.data.data_list
          this.record_total = res.data.total_count
        }
      ).finally(() => {
        this.recordLoading = false
      })
    },
    handleOpt(row) {
      this.record_client_id = row.client_id
      this.start_time = row.day_date
      this.record_day = row.day_date
      this.end_time = parseTime(new Date(new Date(this.start_time).getTime() + 86400000), '{y}-{m}-{d}')
      this.dialogVisible = true
      this.getRcordData()
    },
    handleClose() {
      this.record_page = 1
      this.record_page_size = 15
      this.record_total = 0
      this.record_value = ''
      this.start_time = undefined
      this.end_time = undefined
    },
    changeValue(val) {
      if (val[0]) {
        this.start_time = this.record_day + ' ' + val[0]
        this.end_time = this.record_day + ' ' + val[1]
        this.getRcordData()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.title {
  font-size: 1.75rem;
  font-weight: bold;
  color: #303133;
  text-align: center;
  margin-top: 2rem;
}

.line-charts {
  margin: 1rem;
  background: white;
  padding: 1rem;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .header-sub {
      .el-select {
        margin-right: 1rem;
      }

      .el-date-editor {
        margin-right: 1rem;
      }
    }
  }

  .header-title {
    font-size: 1.25rem;
    font-weight: bold;
    color: #303133;
  }

  #line {
    height: 30vh;
  }

  .el-table {
    margin-top: 1rem;
  }
}

.env-header {
  margin-bottom: 1rem;
}

</style>
