<template>
  <div class="table-container">
    <!-- 用例模块 -->
    <div class="deviceExamples">
      <!-- 用例 -->
      <div class="title-container">
        <div class="title-main">用例</div>
        <div class="title-right">
          <div class="check-resaults">
            总数：
            <span class="total">
              {{ unitsData.total }}
            </span>
          </div>
          <div class="check-resaults">
            成功数：
            <span class="success">
              {{ unitsData.successful }}
            </span>
          </div>
          <div class="check-resaults">
            失败数：
            <span class="faild">
              {{ unitsData.failed }}
            </span>
          </div>
          <div class="check-resaults">
            <el-button
              icon="el-icon-refresh"
              class="light-button"
              size="mini"
              @click="refreshManual(true)"
            >刷新</el-button>
          </div>
          <div class="check-resaults">
            <el-button class="light-button" icon="el-icon-file" size="mini" @click="openFileTransfer()">文件传输</el-button>
          </div>
          <div class="check-resaults">
            <el-button
              icon="el-icon-document"
              class="light-button"
              size="mini"
              @click="checkReport()"
            >查看报文</el-button>
          </div>
          <div class="check-resaults">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              :disabled="componentParames.isDisable"
              @click="editRow()"
            >添加</el-button>
          </div>
        </div>
      </div>
      <!-- 用例表格 -->
      <div class="table-data">
        <!-- {
                    "id": "2300000037",
                    "name": null,
                    "suiteId": null,
                    "planId": "3200000028",
                    "ruleId": 102,
                    "ruleName": "读开关量",
                    "not": null,
                    "value": null,
                    "error": null,
                    "params": {}
                  } -->
        <el-table :key="tableIsUpdate" v-loading="vloading" :data="tableData" stripe>
          <el-table-column prop="id" label="序号" width="100px" />
          <el-table-column prop="name" label="用例名称" width="150px" />
          <el-table-column prop="state" label="测试状态" width="120px">
            <template slot-scope="scope">
              <span :style="{'color':scope.row.stateStyle}">{{ scope.row.state }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="false" prop="ruleName" label="测试规则" width="135px" />
          <el-table-column prop="occur" label="执行时间" width="160px" />
          <el-table-column prop="duration" label="持续时间(ms)" width="135px" />
          <!-- 鲜总说不要了 06.测试/20230704/设备检测用例相关改动.png
          <el-table-column prop="not" label="规则取反" width="75px" :formatter="formatBool" />
          <el-table-column prop="value" label="期望值" width="75px" />
          <el-table-column prop="error" label="误差范围" width="75px" /> -->
          <el-table-column prop="unit" label="循环次数" width="150px">
            <template slot-scope="scope">
              <!-- 总数/成功数/失败数 -->
              <ul v-if="scope.row.unit" class="unit">
                <li>
                  <div class="unit-title">总数:</div>
                  <div class="unit-value total">{{ scope.row.unit.total }}</div>
                </li>
                <li>
                  <div class="unit-title">成功数:</div>
                  <div class="unit-value successful">{{ scope.row.unit.successful }}</div>
                </li>
                <li>
                  <div class="unit-title">失败数:</div>
                  <div class="unit-value failed">{{ scope.row.unit.failed }}</div>
                </li>
              </ul>
            </template>
          </el-table-column>
          <el-table-column prop="params" label="参数设置">
            <template slot-scope="scope">
              <ul class="setting-json">
                <li
                  v-for="(settingItem) in scope.row.params"
                  :key="settingItem.id "
                >
                  <div>{{ settingItem.id }}({{ settingItem.name }})：{{ settingItem.value || 0 }}</div>
                  <!-- <span v-if="index < scope.row.params.length - 1">,</span> -->
                </li>
              </ul>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="120px">
            <template slot-scope="scope">
              <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>

            </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="deviceExamples.pageLimit"
          :total="deviceExamples.paginationTotalElements"
          :current-page.sync="deviceExamples.paginationNumber"
          :page="deviceExamples.paginationNumber"
          :auto-scroll="false"
          @pagination="getDeviceExamples"
        />
      </div>
    </div>
    <!-- 查看报文 model -->
    <ModelReport
      v-if="showModelReport"
      :report-parames="{
        'deviceName':componentParames.deviceName,
        'curPlanId':componentParames.curPlanId
      }"
      @toggleModel="closeModel"
    />
    <!-- 添加/编辑用例 model -->
    <ModelFormExample
      v-if="showModelForm"
      :model-parames="{
        'curPlanId':componentParames.curPlanId,
        'deviceName':componentParames.deviceName,
        'curSuiteId':componentParames.curSuiteId,
        'modelFormData':modelFormData
      }"
      @toggleModel="closeModel"
    />
    <ModelFormFileTransferOpt104
      v-if="showFileTransferOpt104ModelForm"
      :model-parames="{
        'curPlanId':componentParames.curPlanId,
        'productId':componentParames.productId,
        'deviceName':componentParames.deviceName,
        'curSuiteId':componentParames.curSuiteId
      }"
      @toggleModel="closeModel"
    />
  </div>
</template>

<script>
import {
  httpGet,
  delRecord,
  json2ArrayContext
} from '@/api/common-action'
// 分页
import Pagination from '@/components/Pagination'
// 查看报文
import ModelReport from '../components/ModelReport'
// 添加用例
import ModelFormExample from '../components/ModelFormExample'
import ModelFormFileTransferOpt104 from '../components/ModelFormFileTransferOpt104'
// 导入总线
import { EventBus } from '@/main.js'
export default {
  name: 'Example',
  components: {
    Pagination,
    ModelReport,
    ModelFormExample,
    ModelFormFileTransferOpt104
  },
  props: {
    componentParames: {
      type: Object,
      default: function() {
        return {}
      }
    }
  },
  data() {
    return {
      showFileTransferOpt104ModelForm: false,
      vloading: true,
      tableData: [],
      tableIsUpdate: 0,
      unitsData: {},
      // 用例
      deviceExamples: {
        pageLimit: 5,
        paginationNumber: 1,
        paginationTotalElements: 1
      },
      // 是否显示 查看报文
      showModelReport: false,
      // 编辑用例数据
      modelFormData: {},
      // 是否显示 添加/编辑用例
      showModelForm: false
    }
  },
  // watch: {
  //   componentParames: {
  //     handler() {
  //       // 监听传入的值 是否有变化 ，如有 刷新表格数据
  //       // console.log('刷新表格数据 componentParames', this.componentParames)

  //       // // 获取用例列表数据 ，不传分页信息，即采集默认分页获取第一页数据
  //       // this.getDeviceExamples()

  //       // // 刷新一次用例状态
  //       this.refreshManual()
  //     }
  //   }
  // },

  created() {
  },
  mounted() {
    EventBus.$off('refreshManualFn')
    EventBus.$on('refreshManualFn', this.refreshManual)
    this.$nextTick(() => {
      // 网页加载完成后执行
      this.initFunctions()
    })
  },
  methods: {
    // 初始化
    async initFunctions() {
      // 所有需要加载时初始化的函数都放这里
      // console.log('Example initFunctions componentParames=', this.componentParames)
      // 获取用例列表数据 ，不传分页信息，即采集默认分页获取第一页数据
      this.getDeviceExamples()
    },
    // 文件传输
    openFileTransfer() {
      this.showFileTransferOpt104ModelForm = true
    },
    // 手动刷新状态  manual
    refreshManual(isHand) {
      // 接口 用例状态（高频刷新） /test/execute/:runner/results
      const getUrl = `/test/execute/${this.componentParames.curPlanId}/results`
      // const getUrl = `/test/execute/${this.componentParames.curPlanId}/models`
      // console.log('手动刷新 getUrl=', getUrl)
      httpGet(getUrl).then(res => {
        this.unitsData = res
        if (this.tableData.length > 0) {
          // this.tableData.filter(item)
          this.tableData.forEach(item => {
            res.units.forEach(uitem => {
              // console.log('item.id=', item.id)
              // console.log('uitem.id=', uitem.id)
              if (item.id === uitem.id) {
                // console.log('uitem.stateName=', uitem.stateName)
                item.state = uitem.stateName
                item.stateStyle = uitem.stateStyle
                item.occur = uitem.occur || '-'
                item.duration = uitem.duration || '-'
                item.unit = uitem
              }
            })
          })
          // 解决tableData无法刷新的问题
          this.tableIsUpdate = 'example' + new Date().getTime()
        }
        // console.log('this.tableData', this.tableData)
        if (isHand) {
          this.$message({
            message: '用例刷新成功',
            type: 'success',
            duration: 500,
            offset: window.screen.height / 3
          })
        }
      })
    },
    // 格式化bool值
    formatBool(val) {
      const rs = val.not.toString()
      return rs
    },

    // 获取用例
    getDeviceExamples(pageObj) {
      this.vloading = true
      // 翻页时pageObj对象才会有值，属性分别为page和limit
      if (pageObj == null) {
        pageObj = {
          page: 0,
          limit: this.deviceExamples.pageLimit
        }
        this.deviceExamples.paginationNumber = 0
      } else {
        this.deviceExamples.pageLimit = pageObj.limit
      }
      // 获取用例表格数据
      httpGet(`/test/plan/${this.componentParames.curPlanId}/units?page=${pageObj.page}&size=${pageObj.limit}`).then((response) => {
        this.vloading = false
        this.tableData = response.content
        // 格式化参数设置显示
        this.tableData.forEach(item => {
          item.params = json2ArrayContext(item.params)
          item.units = []
        })
        this.deviceExamples.paginationTotalElements = response.totalElements * 1
        this.deviceExamples.paginationNumber = response.number * 1 + 1
        // 刷新一次用例状态
        this.refreshManual(false)
      }).catch((res) => {
        this.vloading = false
      })
    },
    // 编辑
    editRow(index) {
      // console.log('this.tableData[index]=', this.tableData[index])
      // 如果是添加，则index为空，modelFormData也为空
      this.modelFormData = this.tableData[index]
      this.showModelForm = true
    },
    // 删除
    delRow(index) {
      this.$confirm(
        '此操作将永久删除该记录, 是否继续?',
        `删除`,
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        // console.log('delRow index=', index)
        // 接口 删除用例 /test/unit/:unit
        // :unit 例：2300000036
        const delUrl = `/test/unit/${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
        })
      })
    },

    // 查看报文
    checkReport() {
      // console.log('checkReport 查看报文 开始')
      this.showModelReport = true
    },
    // 关闭 model
    closeModel(modelName, modelShow) {
      // console.log('closeModel modelName=', modelName)
      // console.log('closeModel modelShow=', modelShow)
      switch (modelName) {
        // case 'ModelAddStep':
        //   this.deviceDetail.showModelAddStep = modelShow
        //   break
        case 'ModelReport':
          this.showModelReport = modelShow
          break
        case 'ModelFormExample':
          this.showModelForm = modelShow
          // 操作过用例模态框 刷新一次用例数据 保持页数不变
          this.getDeviceExamples({
            page: this.deviceExamples.paginationNumber - 1,
            limit: this.deviceExamples.pageLimit
          })
          break
        case 'ModelFormFileTransferOpt104':
          this.showFileTransferOpt104ModelForm = false
          break
        default:
          console.log('未获取到 modelName')
          break
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.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: 0;
  .el-table {
    font-size: 12px;
  }
  .unit {
    list-style: none;
    padding-left: 0;
    li {
      display: flex;
      // 总数使用默认颜色
      // .total {
      //   // color: #00706b;
      // }
      .successful {
        color: #00706b;
      }
      .failed {
        color: #c51437;
      }
    }
  }
  .setting-json {
    padding: 0;
    margin: 0;
    list-style: none;
    li {
      display: inline;
    }
  }
}
// 底部按钮
.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>
