<template>
  <div class="iot-child-device">
    <div class="event-box">
      <!-- 左侧事件类型列表 -->
      <div :span="4" class="event-tabs">
        <el-tabs v-model="activeEventType" style="min-height: 200px;width: 150px;height: 100%" tab-position="left" @tab-click="handleTabClick">
          <el-tab-pane
            v-for="item in eventTypeList"
            :key="item.id"
            :label="item.name"
            :name="item.id">
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 右侧内容区域 -->
      <div class="event-main">
        <el-form
          v-show="showSearch"
          ref="queryForm"
          :inline="true"
          :model="queryParams"
          label-width="68px"
        >
          <el-form-item label="时间">
            <el-date-picker
              v-model="pickerValue"
              :default-time="['00:00:00', '23:59:59']"
              end-placeholder="结束日期"
              range-separator="至"
              size="small"
              start-placeholder="开始日期"
              type="datetimerange"
              @change="pickerChange"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" size="mini" type="primary" @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="eventList"
          :default-sort="{ prop: 'timestamp', order: 'descending' }"
          @sort-change="sortChange">
          <el-table-column :index="indexFormatter" align="center" label="序号" type="index" width="80px"/>
          <el-table-column
            v-for="(item,index) in activeEventObj.valueType.properties"
            :key="index"
            :label="item.name"
            :prop="item.id"
            align="center"
          />
          <el-table-column
            :formatter="dateFormat"
            align="center"
            label="时间"
            prop="timestamp"
            sortable="custom"
            width="160px"
          />
          <el-table-column align="center" label="操作" width="100">
            <template slot-scope="scope">
              <el-button circle icon="el-icon-search" type="text" @click="openDetail(scope.row)"></el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :limit.sync="queryParams.pageSize"
          :page.sync="queryParams.pageNum"
          :total="total"
          @pagination="getDeviceLogList"
        />
      </div>
    </div>

    <el-dialog
      :visible.sync="eventContentShow"
      class="params-eldialog"
      title="详情"
      top="5vh"
      width="800px"
    >
      <json-viewer
        :expand-depth="10"
        :value="eventContent"
        copyable
        style="max-height: calc(100vh - 400px); overflow: auto"
      >
      </json-viewer>
      <template #footer>
        <el-button type="primary" @click="eventContentShow = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { listDeviceEventLogList } from "@/api/iot/device";
import {formatDate} from "@/utils";
import JsonViewer from "vue-json-viewer";
import "vue-json-viewer/style.css";

export default {
  name: 'EventLog',
  props: ['sourceId', 'pDevcieInfo'],
  components: {
    JsonViewer
  },
  data() {
    return {
      // 查询参数
      pickerValue: null,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderType: 2,
        deviceId: null,
        deviceName: null,
        eventType: '',
        beginTime: null,
        endTime: null
      },
      showSearch: true,
      // 设备表格数据
      eventList: [],
      total: 0,
      eventTypeList: [],
      activeEventType: '',
      activeEventObj: {
        id: '',
        name: '',
        valueType:{
          type: 'object',
          properties: []
        }
      },
      eventContentShow:false,
      eventContent:'',
    }
  },
  created() {
    this.getProdEventList();
  },
  methods: {
    handleTabClick(tab) {
      console.log("tab",tab)
      this.eventTypeList.forEach(item => {
        if (item.id === tab.name) {
          this.activeEventObj = item;
        }
      });
      this.handleQuery();
    },
    getProdEventList(){
      this.eventTypeList = [];
      let eventTypeList = [];
      try {
        let json = JSON.parse(this.pDevcieInfo.prodJson);
        eventTypeList = json.events || [];
      } catch (error) {
        console.log(error);
      }
      console.log("当前事件列表",eventTypeList);
      this.eventTypeList = eventTypeList || [];
      if(eventTypeList.length>0){
        this.handleTabClick({name:eventTypeList[0].id});
        this.activeEventType = eventTypeList[0].id;
      }
    },
    indexFormatter(val) {
      return val + 1 + ((this.queryParams.pageNum - 1) * this.queryParams.pageSize);
    },
    getDeviceLogList() {
      this.loading = true;
      this.queryParams.deviceId = this.sourceId;
      this.queryParams.eventType = this.activeEventType;
      listDeviceEventLogList(this.queryParams).then(res => {
        this.eventList = res.data.records;
        this.total = res.data.total;
        this.loading = false;
      });
    },
    handleQuery() {
      let pickerValue = this.pickerValue
      if (pickerValue != null) {
        this.queryParams.beginTime = Date.parse(pickerValue[0]);
        this.queryParams.endTime = Date.parse(pickerValue[1]);
      }
      this.queryParams.pageNum = 1;
      this.getDeviceLogList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.resetPicker();
      this.handleQuery();
    },
    resetPicker() {
      this.pickerValue = null
      this.queryParams.beginTime = null
      this.queryParams.endTime = null
    },
    pickerChange(val) {
      console.log("pickerChange", val)
      if (val == null) {
        this.resetPicker();
      }
    },
    dateFormat(val) {
      return formatDate(val.timestamp)
    },
    sortChange(column) {
      const sort = {
        orderType: column.order === "descending" ? 1 : 2,
      };
      this.queryParams = Object.assign(this.queryParams, sort);
      this.handleQuery();
    },
    openDetail(item){
      let eventContent = '';
      try {
        eventContent = JSON.parse(item.raw_data);
      } catch (error) {
        console.log(error);
      }
      this.eventContent = eventContent;
      this.eventContentShow = true;
    },
  },
}
</script>

<style lang="scss" scoped>
.iot-child-device {
  .event-box{
    display: flex;
    .event-tabs {
      width: 130px;
      /* 调整标签栏样式 */
      ::v-deep .is-left.el-tabs__header {
        width: 130px;
      }

      ::v-deep .el-tabs--left .el-tabs__item {
        width: 100%;
        text-align: center;
        padding: 0 20px;
      }
    }
    .event-main{
      flex: 5;
      padding: 0 20px;
    }
  }
}
</style>
