<!-- 设备报文 -->
<template>
  <div class="table-container" style="padding-top:20px;float: left;width: 100%;">
    <div class="buttons">
      <div class="title-main" style="line-height: 2rem;">报文</div>
      <div class="left">
        <div class="search">
          <el-form ref="searchForm" :model="searchForm" class="search-form" label-width="30px">
            <el-form-item class="search-parames">
              <el-select v-model="searchForm.selectVal" filterable @change="changeSelect">
                <el-option
                  v-for="item in searchForm.selectOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-form>
        <!-- 下拉框改变化，自动就刷新数据了，不需要再点击搜索按钮
          <div class="search-button">
            <el-button class="dark-button" icon="el-icon-search" size="small" @click="refreshReport()">搜索</el-button>
          </div> -->
        </div>
      </div>
      <div class="right">
        <div class="export">
          <a target="_blank" :href="`${APP_BASE_API}/test/execute/${reportParames.curPlanId}/message.xls`"><el-button icon="el-icon-download" class="light-button" size="small">导出</el-button></a>
        </div>
        <div class="refresh">
          <el-button class="light-button" icon="el-icon-refresh-left" size="small" @click="refreshReport({page:paginationNumber-1,limit:pageLimit},true)">刷新</el-button>
        </div>
        <div class="clear">
          <el-button type="primary" icon="el-icon-delete" class="dark-button" size="small" @click="clearReport()">清空</el-button>
        </div>
      </div>
    </div>
    <el-row type="flex" style="float:left;width: 100%;">
      <el-col :span="18">
        <div class="left-report">
          <!-- 表格 -->
          <el-table :data="deviceReportData" :height="tableHeight" @row-click="analysisReport">
            <!-- id隐藏不显示，作为操作数据依据 -->
            <el-table-column v-if="false" property="id" label="id" />
            <el-table-column property="occur" label="时间" width="160px" />
            <el-table-column property="channelName" label="通道号" width="100px" />
            <el-table-column property="evtName" label="事件" width="75px" />
            <el-table-column property="hex" label="报文" />
            <el-table-column
              fixed="right"
              label="操作"
              width="125px"
            >
              <template slot-scope="scope">
                <el-button v-if="scope.row.id" v-clipboard:copy="scope.row.hex" v-clipboard:success="clipboardSuccess" class="table-act" type="text" icon="el-icon-delete" size="small">复制</el-button>
                <el-button v-if="scope.row.id" class="table-act" type="text" icon="el-icon-edit" size="small">解析</el-button>
              <!-- <el-button v-clipboard:copy="copyClipData" v-clipboard:success="clipboardSuccess" class="table-act" type="text" icon="el-icon-delete" size="small" @click="copyReport(scope.row)">复制</el-button> -->
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="right-report">
          <!-- 解析结果显示 -->
          <div class="analysis-result">
            <div v-if="comonentVar.analysisResult.length<=0" class="empty-result">暂无解析结果</div>
            <div v-else>
              <ul
                v-for="item in comonentVar.analysisResult"
                :key="item.index"
                class="result"
              >
                <!-- <li class="key"> {{ item.first }} </li>
                <li class="value"> {{ item.second }} </li> -->
                <li class="oneBox">
                  <span>参数：{{ item.first }}</span>
                  <span>值：{{ item.second }}</span>
                </li>
              </ul>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
    <el-row>
      <el-col>
        <pagination
          background
          layout="pager"
          :limit="pageLimit"
          :total="paginationTotalElements"
          :current-page.sync="paginationNumber"
          @pagination="refreshReport"
        />
      </el-col>
    </el-row>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import { delRecord, download, httpGet } from '@/api/common-action'
import clipboard from '@/directive/clipboard/index.js'
import Pagination from '@/components/Pagination'

export default {
  name: 'ModelReport',
  directives: {
    clipboard
  },
  components: { Pagination },
  // report-parames
  props: {
    reportParames: {
      type: Object,
      default: function() {
        return {}
      }
    }
  },
  data() {
    return {
      APP_BASE_API: window.STATIC_CONFIG.proxyUrl,
      // 报文表格数据
      deviceReportData: [
        {
          'id': '读取中...',
          'occur': '读取中...',
          'runnerId': '读取中...',
          'channelId': '读取中...',
          'channelName': '读取中...',
          'evtId': '读取中...',
          'bytes': '读取中...'
        }
      ],
      // 组件变量
      comonentVar: {
        deviceReportTitle: '读取中...',
        analysisResult: ''
      },
      // 搜索表单
      searchForm: {
        selectOptions: [
          { id: 'pt15m', name: '最近15分钟' },
          { id: 'pt4h', name: '最近4小时' },
          { id: 'pt24h', name: '最近24小时' }
        ],
        // 查询时间范围
        // PT4H是一种时间表示格式，表示持续时间为4小时。其中“PT”代表“持续时间（duration）”，后面的“4H”代表4个小时（hours）的意思。
        // PT2H 2小时 “PT3M”（3分钟）和“PT30S”（30秒）
        selectVal: 'pt4h'
      },
      copyClipData: {
        copyTestName: '剪切板复制测试内容-name',
        copyTestValue: '剪切板复制测试内容-value'
      },
      pageLimit: 20,
      paginationNumber: 0,
      paginationTotalElements: 0,
      // 动态设置table高度
      tableHeight: 0
    }
  },
  computed: {
    ...mapGetters([
      'roles'
    ])
  },
  created() {
    // 获取后端报文数据
    // 报文查询 接口 /test/execute/:runner/message
    // 猜测 runner 应该是 planId
    // 动态设置表格高度
    const marginBottom = 440
    this.tableHeight = window.innerHeight - marginBottom

    this.refreshReport()
  },
  mounted() {
    this.comonentVar.deviceReportTitle = `[${this.reportParames.deviceName}]报文详情`
  },
  methods: {
    // 关闭model
    toggleModel() {
      // console.log('toggleModel started')
      this.$emit('toggleModel', 'ModelReport', false)
    },
    // 报文时间改变时执行
    changeSelect(selectVal) {
      // console.log('changeSelect selectVal=', selectVal)
      this.refreshReport()
      // 清空解析结果
      this.comonentVar.analysisResult = ''
    },
    // 清空报文
    // swagger 接口 删除通信日志 /test/execute/{id}/message
    // id 3200000252
    clearReport() {
      const delUrl = `/test/execute/${this.reportParames.curPlanId}/message`
      delRecord(delUrl).then(res => {
        // 删除成功
        // 刷新表格
        this.refreshReport()
        this.$message({
          message: '清空成功',
          type: 'success',
          duration: 1500,
          offset: window.screen.height / 3
        })
      })
    },
    // 刷新
    refreshReport(pageObj, isRe) {
      pageObj = pageObj || {
        page: 0,
        limit: this.pageLimit
      }

      // 报文查询 接口 /test/execute/:runner/message
      // #TODO: 这里要使用新标准，需要添加绝对时间参数的判断
      const getUrl = `/test/execute/${this.reportParames.curPlanId}/message?period=${this.searchForm.selectVal}&page=${pageObj.page}&size=${pageObj.limit}`
      // console.log('refreshReport getUrl=', getUrl)
      httpGet(getUrl).then(res => {
        // console.log('刷新后端报文数据 httpGet res=', res)
        this.deviceReportData = res.content
        this.paginationNumber = res.number + 1
        this.paginationTotalElements = res.totalElements * 1 // *1 强制转换为数字型
        if (isRe) {
          this.$message({
            message: '刷新成功',
            type: 'success',
            duration: 500,
            offset: window.screen.height / 3
          })
        }

        // 返回数据示例
        // "content": [
        //      {
        //         "id": "4",
        //         "occur": "2023-06-11 08:31:11",
        //         "runnerId": "999",
        //         "channelId": null,
        //         "channelName": "389434b4",
        //         "evtId": "READ",
        //         "bytes": "000100000003018401"
        //     }],
        //     "totalPages": 1,
        //     "totalElements": "4",
        //     "size": 20,
        //     "number": 0,
        //     "numberOfElements": 4
        //   }
      })
    },
    // 导出
    exportReport() {
      // 接口 报文导出 /test/execute/:runner/message.xls
      // :runner 3200000315

      download(`/test/execute/${this.reportParames.curPlanId}/message.xls`).then(res => {
        const link = document.createElement('a')
        const blob = new Blob([res], {
          type: 'application/vnd.ms-excel;charset=utf-8'
        })
        link.style.display = 'none'
        link.href = URL.createObjectURL(blob)
        link.setAttribute('download', `导出报文-${this.componentParames.curPlanId}.xls`)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      })
    },
    // 解析报文
    analysisReport(row) {
      // 报文解析接口 /test/message/:id
      // 猜测 这个id 应该是前面 报文查询 接口 返回的id
      httpGet(`/test/message/${row.id}`).then(res => {
        if (res.items && res.items.length > 0) {
          this.comonentVar.analysisResult = res.items
        }
      })
    },
    // 复制报文 成功回调
    clipboardSuccess(val) {
      this.$message({
        message: '复制成功:' + val.text,
        type: 'success',
        duration: 1500,
        offset: window.screen.height / 3
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.title-main {
  color: #111;
  font-weight: bold;
  float: left;
  width: auto;
}
.buttons {
  display: block;
  height: 3.5rem;
  width: 100%;
  justify-content: space-between;
  .left {
    float: left;
    width: auto;
    .search{
      display: flex;
      justify-content: left;
      .search-form {
        .search-parames {
          text-align: left;
        }
      }
      .search-button {
        padding-left: 20px;
      }
    }
  }
  .right{
    float: right;
    width: auto;
    justify-content: right;
    padding-bottom: 20px;
    .export{
      float: left;
      width: 70px;
    }
    .clear,.refresh {
      padding-left: 20px;
      float: left;
      width: 90px;
    }
  }
}
.right-report {
  height: 100%;
  // 解析结果
  .analysis-result {
    margin-left: 4px;
    border:1px #eaefef solid;
    background-color: #fcfdfd;
    width: 100%;
    height: 100%;
    padding: 0;
    // display: flex;
    // justify-content: center;
    // align-items: flex-start;
    .result {
      width: 100%;
      display: flex;
      justify-content: flex-start;
      align-items: center;
      text-align: left;
      color: #909399;
      &:nth-child(2n){
          background-color: #eee;
        }
      // .key,.value {
      //   list-style-type: none;
      // }
      // .key {
      //   width: 80px;
      //   text-align: right;
      //   padding-right:10px;
      //   ::after {
      //     width:10px;
      //   }
      // }
      .oneBox{
        width: 100%;
        list-style-type: none;
        margin: 0;
        padding: 0;
        display: flex;
        flex-direction: column;

      }

    }
    .empty-result {
      text-align: center;
      color: #ccc;
    }
  }
}

// ::v-deep .diaClass{
//  position: relative;
//  top: 10%;
//  left:25%
// }
// 按钮公用样式
.dark-button {
  background-color: #00706B;
  border: 1px #00706B solid;
  color: #fff;
}
.light-button {
  color: #00706B;
  border: 1px #00706B solid;
}
</style>
