<!-- 采样表格
返回数据示例
{
  "id": "24577",
  "name": "A相电压",
  "offset": 0,
  "value": null,
  "occur": null,
  "iec104": 24577,
  "modbus": 40001,
  "range": "HOLDING_REGISTER"
},
无法分页 采样表格无法分页，数据在内存中
微信聊天记录 边缘代理2开发沟通 - 2023-06-27 采样表格无法分页，数据在内存中
-->
<template>
  <div class="table-container">
    <!-- 采样模块 -->
    <div class="device-values">
      <!-- 采样 -->
      <div class="title-container">
        <div class="title-main">采样值</div>
        <div class="title-right">
          <div class="check-resaults">
            <el-button
              icon="el-icon-refresh-left"
              class="light-button"
              size="mini"
              @click="refreshManual(true)"
            >刷新</el-button>
          </div>
          <div class="check-resaults">
            <!-- 导入即是上传文件 -->
            <el-upload
              ref="upload"
              :action="importCsvActionStr"
              :show-file-list="false"
              :auto-upload="false"
              accept=".csv"
              :on-change="submitUpload"
            >
              <el-button
                class="light-button"
                icon="el-icon-upload2"
                size="mini"
              >导入</el-button>
            </el-upload>
          </div>
          <div class="check-resaults">
            <el-button
              class="light-button"
              icon="el-icon-download"
              size="mini"
              @click="getPlanExport"
            >导出</el-button>
          </div>
          <div class="check-resaults">
            <el-button
              icon="el-icon-plus"
              type="primary"
              size="mini"
              :disabled="componentParames.isDisable"
              @click="editRow()"
            >添加</el-button>
          </div>
          <div class="check-resaults" style="margin-left: 20px;">
            <el-button
              icon="el-icon-postcard"
              :type="cardModelTag"
              size="mini"
              @click="swicthCardModel(true)"
            >卡片</el-button>
          </div>
          <div class="check-resaults">
            <el-button
              icon="el-icon-s-grid"
              size="mini"
              :type="tableModelTag"
              @click="swicthCardModel(false)"
            >列表</el-button>
          </div>
        </div>
      </div>
      <!-- 采样卡片 -->
      <div v-if="showCard == true" class="table-container">
        <div v-for="(item, index) in carddata" :key="index">
          <div class="card">{{ item }}</div>
        </div>
      </div>
      <!-- 采样表格 -->
      <div v-if="showCard == false" class="table-container">
        <el-table :key="tableIsUpdate" v-loading="vLoading" :data="tableData" stripe max-height="300">
          <el-table-column prop="iec104" label="104点号" width="100px" />
          <el-table-column prop="name" label="测点名称" />
          <el-table-column prop="groupingName" label="设备名称" />
          <el-table-column prop="rangeName" label="点号类型" width="175px">
            <template slot-scope="scope">
              <span class="range">{{ scope.row.rangeName }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="offset" label="点号" width="100px" />
          <el-table-column prop="value" label="值" width="100px" />
          <el-table-column prop="occur" label="时间" width="175px" />
          <el-table-column fixed="right" label="操作" width="250px">
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.range=='COIL_STATUS' && scope.row.relationTag!=''"
                class="table-act"
                type="text"
                icon="el-icon-setting"
                size="small"
                @click="editRow(scope.$index)"
              >遥控操作</el-button>
              <el-button
                v-if="scope.row.range=='COIL_SHOLDING_REGISTERTATUS' && scope.row.relationTag!=''"
                class="table-act"
                type="text"
                icon="el-icon-edit"
                size="small"
                @click="editRow(scope.$index)"
              >遥调操作</el-button>
              <el-button
                class="table-act"
                type="text"
                icon="el-icon-edit"
                size="small"
                @click="editRow(scope.$index)"
              >编辑</el-button>
              <el-button
                class="table-act"
                type="text"
                icon="el-icon-delete"
                size="small"
                @click="delRow(scope.$index)"
              >删除</el-button>
              <el-button
                class="table-act"
                type="text"
                icon="el-icon-data-line"
                size="small"
                @click="sampleEchart(scope.row)"
              >曲线</el-button>
            </template>
          </el-table-column>
          <!-- 隐藏 列 这里不用显示，但是在编辑的时候需要获取此数据 -->
          <el-table-column
            v-if="false"
            prop="deviceCheckId"
            label="序号"
          />
          <!-- 隐藏 列 -->
        </el-table>
      </div>
      <!-- 采样分页
      <div class="page-bar">
        <pagination
          background
          layout="pager"
          :limit="tablePrames.pageLimit"
          :total="tablePrames.paginationTotalElements"
          :current-page.sync="tablePrames.paginationNumber"
          @pagination="getTableData"
        />
      </div>
      -->
    </div>
    <!-- 添加/编辑 采样 model -->
    <ModelFormSample
      v-if="showModelForm"
      :model-parames="{
        'curPlanId':componentParames.curPlanId,
        'productId':componentParames.productId,
        'deviceName':componentParames.deviceName,
        'curSuiteId':componentParames.curSuiteId,
        'modelFormData':modelFormData
      }"
      :sample-data="tableData"
      @toggleModel="closeModel"
    />
    <!-- #TODO: 以后做成公用 dialog ，不再使用 toggleModel 关闭 dialog -->
    <el-dialog
      :visible="showEchart"
      :before-close="closeSampleEchart"
      :title="curPointName"
    >
      <!-- 采样 曲线  model -->
      <ModelSampleEchart
        v-if="showEchart"
        :model-parames="{
          'curPlanId':componentParames.curPlanId,
          'curPointId':curPointId,
          'curPointName':curPointName
        }"
      />
    </el-dialog>
  </div>
</template>

<script>
import {
  httpGet,
  delRecord,
  download
} from '@/api/common-action'
// 分页
// import Pagination from '@/components/Pagination'
// 显示采样曲线
import ModelSampleEchart from '../components/ModelSampleEchart'
// 添加/编辑 采样
import ModelFormSample from '../components/ModelFormSample'
// 导入总线
import { EventBus } from '@/main.js'
export default {
  name: 'Sample',
  components: {
    // Pagination,
    ModelSampleEchart,
    ModelFormSample
  },
  props: {
    componentParames: {
      type: Object,
      default: function() {
        return {}
      }
    }
  },
  data() {
    return {
      vLoading: true,
      showCard: true, // 卡片显示模式。false时为表格显示模式
      cardModelTag: 'primary',
      tableModelTag: 'default',
      carddata: [],
      tableData: [],
      // 采样
      tablePrames: {
        pageLimit: 5,
        paginationNumber: 1,
        paginationTotalElements: 1
      },
      // 是否显示 添加/编辑 采样
      showModelForm: false,
      // 是否显示曲线
      showEchart: false,
      // 当前采样id
      curPointId: '0',
      // 当前采样名称
      curPointName: '0',
      // 导入csv 请求参数
      importCsvActionStr: '#',
      // 表格是否更新标示,用于解决表格内数据变化了不会刷新的问题
      tableIsUpdate: '0'
    }
  },
  // watch: {
  //   componentParames: {
  //     handler() {
  //       // 监听传入的值 是否有变化 ，如有 刷新表格数据
  //       // console.log('刷新表格数据 componentParames')
  //       // this.refreshTableData()
  //     }
  //   }
  // },
  created() {
    const envUrl = process.env.VUE_APP_BASE_API
    // 网页加载完成后执行
    // 接口 导入测点 /test/plan/:plan/points.csv
    this.importCsvActionStr = envUrl + `/test/plan/${this.componentParames.curPlanId}/points.csv`
    // console.log('this.importCsvActionStr=', this.importCsvActionStr)
    // 在bus上挂载刷新事件
    EventBus.$on('refreshManualSample', this.refreshManual)
  },
  mounted() {
    this.$nextTick(() => {
      // 网页加载完成后执行
      this.initFunctions()
    })
  },
  methods: {
    swicthCardModel(flag) {
      this.showCard = flag
      if (flag) {
        this.cardModelTag = 'primary'
        this.tableModelTag = 'default'
      } else {
        this.cardModelTag = 'default'
        this.tableModelTag = 'primary'
      }
    },
    //
    async initFunctions() {
      // 所有需要加载时初始化的函数都放这里
      // 获取用例列表数据 ，不传分页信息，即采集默认分页获取第一页数据
      this.getTableData()
    },
    // 导出
    async getPlanExport() {
      // 接口 导出测点 /test/plan/:plan/points.csv

      download(`/test/plan/${this.componentParames.curPlanId}/points.csv`).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}.csv`)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      })
    },
    // 格式化bool值
    formatBool(val) {
      const rs = val.not.toString()
      return rs
    },
    // 格式化 测试状态
    formatState(val) {
      return '未获取'
    },

    // 获取采样表格数据
    getTableData(pageObj) {
      this.vLoading = true
      pageObj = pageObj || {
        page: 0,
        limit: this.tablePrames.pageLimit
      }
      // 获取表格数据
      // 接口 采样数据查询 /test/execute/:runner/values
      // :runner 例:3200000208
      httpGet(`/test/execute/${this.componentParames.curPlanId}/values?page=${pageObj.page}&size=${pageObj.limit}`).then((response) => {
        this.vLoading = false
        delete response.code
        this.tableData = response
        this.tablePrames.paginationTotalElements = response.totalElements * 1
        // this.requestData.deviceProtocolOptions = response
        // 刷新一次状态
        this.refreshManual(false)
      })
    },
    // 编辑
    editRow(index) {
      // console.log('this.tableData[index]=', this.tableData[index].id)
      // 如果是添加，则index为空，modelFormData也为空
      this.modelFormData = this.tableData[index]
      this.showModelForm = true
    },
    // 删除
    delRow(index) {
      this.$confirm(
        '此操作将永久删除该记录, 是否继续?',
        `删除`,
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          // console.log('delRow index=', index)
          // 接口 删除测点 /product/model/:product/:tag
          // :product 1100000645
          // :tag 6386 tag id 为采样列表序号id

          const delUrl = `/product/model/${this.componentParames.productId}/${this.tableData[index].id}`
          // console.log('delRow delUrl=', delUrl)
          delRecord(delUrl).then(res => {
            this.$message({
              message: '删除成功',
              type: 'success',
              offset: window.screen.height / 3
            })
            // 后端成功执行后，前端再删除选中行
            this.tableData.splice(index, 1)
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
            offset: window.screen.height / 3
          })
        })
    },
    // 采样值数据获取
    // 手动刷新时，通过models接口获取实时数据信息
    // isHand: 是否手动刷新。false表示自动触发 true表示界面刷新按钮操作
    refreshManual(isHand) {
      // 默认接口 采样数据（高频刷新） /test/execute/:runner/models
      var getUrl = `/test/execute/${this.componentParames.curPlanId}/models`
      httpGet(getUrl).then(res => {
        if (this.tableData.length > 0) {
          this.tableData.forEach(item => {
            res.forEach(ritem => {
              if (item.id === ritem.id) {
                item.value = ritem.value
                item.occur = ritem.occur
                // 解决tableData无法刷新的问题
                this.tableIsUpdate = 'sample-' + new Date().getTime()
              }
            })
          })
        }
        if (isHand != null && isHand) {
          this.$message({
            message: '采样值刷新成功',
            type: 'success',
            duration: 500,
            offset: window.screen.height / 3
          })
        }
        // console.log('this.tableData', this.tableData)
      })
    },
    // 导入
    submitUpload() {
      // 上传文件
      this.$refs.upload.submit()
      // 上传之后刷新页面查看上传结果
      this.getTableData()
    },
    // 关闭 model
    closeModel(modelName, modelShow) {
      // console.log('closeModel modelName=', modelName)
      // console.log('closeModel modelShow=', modelShow)
      switch (modelName) {
        // case 'ModelAddStep':
        //   this.deviceDetail.showModelAddStep = modelShow
        //   break
        case 'ModelFormSample':
          this.showModelForm = modelShow
          // 操作过用例模态框 刷新一次表格数据
          this.getTableData()
          break
        case 'ModelSampleEchart':
          this.showEchart = modelShow
          break
        default:
          console.log('未获取到 modelName')
          break
      }
    },
    // 曲线
    sampleEchart(row) {
      // 接口 /test/execute/:runner/point/:point/chart?period=pt4h
      // :runner 示例 3200000235
      // :point 示例 24755

      // const getUrl = `/test/execute/${this.componentParames.curPlanId}/point/0/chart?period=pt4h`
      // httpGet(getUrl).then(res => {
      //   // const sampleEchartData = {
      //   //   xAxis: res.xAxis[0],
      //   //   yAxis: res.yAxis[0],
      //   //   series: res.series[0]
      //   // }
      //   // const sampleEchartData = {
      //   //   xAxis: { type: 'category', min: '2023-06-14 06:52:46', max: '2023-06-14 10:52:46' },
      //   //   yAxis: res.yAxis[0],
      //   //   series: { data: [820, 932, 901, 934, 1290, 1330, 1320], type: 'line' }
      //   // }
      //   const sampleEchartData = res

      //   const chart = this.$refs.chart
      //   const myChart = echarts.init(chart)
      //   myChart.setOption(sampleEchartData)
      //   // window.addEventListener('resize', function() {
      //   //   myChart.resize()
      //   // })
      //   // this.$on('hook:destroyed', () => {
      //   //   window.removeEventListener('resize', function() {
      //   //     myChart.resize()
      //   //   })
      //   // })
      //   console.log('sampleEchart 数据获取成功 res=', res)
      //   console.log('sampleEchart 数据获取成功 sampleEchartData=', sampleEchartData)
      // })
      // console.log('sampleEchart started 展示方式待定', row.id)
      this.curPointId = row.id
      this.curPointName = row.name
      this.showEchart = true
    },
    // 关闭Echart弹窗
    closeSampleEchart() {
      this.showEchart = false
    }
  }
}
</script>
<style lang="scss" scoped>
.card{
  float: left;
  width: 10rem;
  height: 5rem;
  border-radius: 5px;
  border: 1px solid #ccc;
}
.card_opt{
  background-color: #ededed;
}
.title-container {
  display: flex;
  justify-content: space-between;
  padding: 20px 0;
  .title-right {
    display: flex;
    align-items: center;
    .check-resaults {
      padding-right: 16px;
      .success {
        color: #00706b;
      }
      .faild {
        color: #f00;
        padding-right: 6px;
      }
      span {
        font-weight: bold;
      }
    }
  }
}
.title-main {
  color: #111;
  font-weight: bold;
}
// 用例表格样式
.table-container {
  // padding: 20px 0;
  .el-table {
    font-size: 12px;
  }
  .range {
    white-space: nowrap;
  }
}
// 底部按钮
.bottom-button {
  display: flex;
  justify-content: center;
  padding-bottom: 20px;
  .cancel-plan {
    padding-right: 20px;
  }
}
// 按钮公用样式
.dark-button {
  background-color: #00706B;
  border: 1px #00706B solid;
  color: #fff;
}
.light-button {
  color: #00706B;
  border: 1px #00706B solid;
}
</style>
