<!--suppress ALL -->
<template>
  <div class="common-layout">
    <el-container>
      <el-header
          style="height: 250px; background-color: rgba(255,0,0,50%); display: flex; flex-direction: column; justify-content: center; align-items: center;">
        <div class="demo-image" style="text-align: center;"> <!-- 注意这里添加了 text-align: center; 但对于块级元素这不是必需的 -->
          <img src="../assets/pji-logo.jpg" alt="" style="width:200px;height: 200px">
          <!-- 推荐使用 max-width 保持图片比例 -->
        </div>
      </el-header>
      <el-main style="background-color:white;">
        <el-breadcrumb separator="/" style="margin-bottom: 10px;">
          <el-breadcrumb-item :to="{ path: '/' }">主页</el-breadcrumb-item>
          <el-breadcrumb-item>测试仿真记录</el-breadcrumb-item>
        </el-breadcrumb>
        <div class="topbar">
          <el-form style=" background-color: rgba(0,0,0,0%);" :inline="true" :model="queryLine"
                   class="demo-form-inline">
            <el-form-item label="设备名称">
              <el-input v-model="queryLine.equipmentName" placeholder="请输入设备名称" clearable/>
            </el-form-item>
            <el-form-item label="设备类型">
<!--              <el-input v-model="queryLine.equipmentType" placeholder="请输入设备类型" clearable/>-->
              <el-select
                  v-model="queryLine.equipmentType"
                  placeholder="请选择"
                  size="default"
                  style="width: 180px; "
                  clearable
              >
                <el-option
                    v-for="item in equipmentTypes"
                    :key="item"
                    :label="item"
                    :value="item"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="算法版本">
              <el-input v-model="queryLine.algorithmVersion" placeholder="请输入算法版本" clearable/>
<!--              <el-select-->
<!--                  v-model="queryLine.algorithmVersion"-->
<!--                  placeholder="请选择"-->
<!--                  size="default"-->
<!--                  @click.native="getKeywordsByField('algo_image_name')"-->
<!--                  style="width: 180px; "-->
<!--                  clearable-->
<!--              >-->
<!--                <el-option-->
<!--                    v-for="item in algorithmVersions"-->
<!--                    :key="item"-->
<!--                    :label="item"-->
<!--                    :value="item"-->
<!--                />-->
<!--              </el-select>-->
            </el-form-item>

            <el-form-item label="算法评价等级">
              <!--            <el-input v-model="queryLine.algorithmLevel" placeholder="请输入算法评价等级" clearable/>-->
              <el-select
                  v-model="queryLine.algorithmLevel"
                  placeholder="请选择"
                  size="default"
                  style="width: 180px; "
                  clearable
              >
                <el-option
                    v-for="item in algoLevels"
                    :key="item"
                    :label="item"
                    :value="item"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="danger" @click="queryRecordByCondition">查询</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="danger" @click="onSubmit">重置</el-button>
            </el-form-item>
            <div style="float: right">
              <el-form-item>
                <el-button type="danger" @click="downloadFile('bag')" :disabled="multipleSelection.length == 0">下载测试bag</el-button>
              </el-form-item>
              <el-form-item>
                <el-button type="danger" @click="downloadFile('report')" :disabled="multipleSelection.length == 0">下载算法评价报告</el-button>
              </el-form-item>
            </div>

          </el-form>

        </div>
        <el-table stripe style="background-color: rgba(255,0,0,99%);width: 100%" border :data="tableData"
                  @selection-change="handleSelectionChange"
                  fixed ref="multipleTableRef" :cell-style="{ textAlign: 'center'}" :header-cell-style="{ textAlign: 'center'}">
          <el-table-column type="selection" width="55"/>
          <el-table-column prop="device_name" label="设备名称" width="300"/>
          <el-table-column prop="device_type" label="设备类型"/>
          <el-table-column prop="algo_image_name" label="算法版本"/>
          <el-table-column prop="test_time" :formatter="formatDate" label="测试时间"/>
          <el-table-column prop="round" label="轮次"/>
          <el-table-column prop="pgm_path" :formatter="(row) => formatPath(row, 'pgm_path')" label="pgm文件"/>
          <el-table-column prop="world_path" :formatter="(row) => formatPath(row, 'world_path')" label="world文件"/>
          <el-table-column prop="test_bag_path" :formatter="(row) => formatPath(row, 'test_bag_path')"  label="测试bag"/>
          <el-table-column prop="test_duration" label="测试时长"/>
          <el-table-column prop="test_distance" label="测试里程"/>
          <el-table-column prop="algo_evaluation_level" label="算法评价等级"/>
          <el-table-column prop="algo_evaluation_report" :formatter="(row) => formatPath(row, 'algo_evaluation_report')" label="算法评价报告"/>
        </el-table>

        <p></p> <!--空行-->
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 15, 20, 50]"
            :small="small"
            :disabled="disabled"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
        <!--        <el-pagination background layout="prev, pager, next" :total="1000"/>-->
      </el-main>
      <!--      <el-footer style="background-color: rgba(255,0,0,99%)">国家智能网联汽车创新中心</el-footer>-->
    </el-container>
  </div>
</template>

<script lang="ts" setup>
import {onBeforeMount, reactive, ref} from "vue";
import axios from "axios";
import {ElMessage, ElTable} from "element-plus";
import path from 'path-browserify';
import moment from "moment";

const queryLine = reactive({
  equipmentName: '',
  equipmentType: '',
  algorithmVersion: '',
  algorithmLevel: ''
})

const onSubmit = () => {
  page()
}

const total = ref(0)
const tableData = ref([]);
const resetTableData = ref([]);
const algorithmVersions =ref()
const equipmentTypes =ref(["引导服务机器人"])
const equipmentNames =ref()
onBeforeMount(() => {
  page()
})
const multipleTableRef = ref<InstanceType<typeof ElTable>>
const multipleSelection = ref<[]>([])

const algoLevels = ['较差', '一般', '良好', '优秀']

const handleSelectionChange = (rows: []) => {
  multipleSelection.value = rows
  console.log("multipleSelection", multipleSelection.value)
}

// 表格 - 格式化路径
const formatPath = (row, name) => {
  return path.basename(row[name])
}

const formatDate =  (row) => {
  return moment(+row.test_time).format("YYYY-MM-DD HH:mm:ss")
}

const getKeywordsByField = (field) => {
  if (resetTableData.value.length > 0) {
    let keywords = new Set(resetTableData.value.map((d) => d[field]))
    if (field === "algo_image_name") {
      algorithmVersions.value = keywords
    }
    // else if (field === "device_type") {
    //   equipmentTypes.value = keywords
    // } else if (field === "device_name") {
    //   equipmentNames.value = keywords
    // }

  }
}
const downloadFile = async (typeName) => {
  // object key
  let keys
  // 文件名(区分1个文件/多个文件)
  let fileName

  if (typeName === "bag") {
    keys = multipleSelection.value.map(item => item["test_bag_path"])
    fileName = multipleSelection.value.length > 1 ? typeName + ".zip" : "test.bag"
  } else if(typeName === "report") {
    keys = multipleSelection.value.map(item => item["algo_evaluation_report"])
    fileName = multipleSelection.value.length > 1 ?  typeName + ".zip" : "report.pdf"
  }
  console.log("keys", keys)
  console.log("typeName", typeName)
  console.log("fileName", fileName)

  // 下载记录
  const url = "http://127.0.0.1:8888/simulation/download/oss/key?typeName=" + typeName
  const result = await window.electronAPI.downloadFile(url, fileName, "", true, true, "post", keys);
  if (!result.success) { // 下载失败
    console.error('File download failed:', result.error);
    ElMessage.error("文件下载失败！");
  } else { // 下载成功
    console.log('File downloaded successfully:', result.filePath);
    ElMessage.success("文件下载成功！");
  }
}

// 根据条件筛选结果
const queryRecordByCondition = async () => {
  let response = await axios.post('/local/simulation/query/test/record?page=' + currentPage.value + '&pageSize=' + pageSize.value, {
    "device_name": queryLine.equipmentName,
    "device_type": queryLine.equipmentType,
    "algo_image_name": queryLine.algorithmVersion,
    "algo_evaluation_level": queryLine.algorithmLevel
  })

  if (!response.data.status){ // 不存在
    ElMessage.error("仿真测试记录查询失败！");
    return
  }
  // 解析结果
  tableData.value = JSON.parse(response.data.data)
  total.value = response.data.total
}

async function page() {
  // axios.get('http://1.202.169.139:8081/open/scene/list?equipmentType=YI_DAO_JI_QI_REN&page=' + currentPage.value + '&size=' + pageSize.value,
  //     {
  //       headers: {
  //         "Authorization": "4773hd92ysj54paflw2jem3onyhywxt2"
  //       }
  //     }
  // ).then(function (response) {
  //   tableData.value = response.data.data.content
  //   total.value = response.data.data.totalElements
  //   // total.value = tableData.value.length
  //   // console.log(tableData);
  //   // console.log(response.data.data);
  // }).catch(function (error) {
  //   console.log(error);
  // });

  // 查询算法评价记录
  let response = await axios.post('/local/simulation/query/test/record?page=' + currentPage.value + '&pageSize=' + pageSize.value)

  if (!response.data.status){ // 不存在
    ElMessage.error("仿真测试记录查询失败！");
    return
  }
  // 解析结果
  tableData.value = JSON.parse(response.data.data)
  console.log("tableData.value", tableData.value)
  resetTableData.value = tableData.value // for reset purpose
  total.value = response.data.total
}

const currentPage = ref(1)
const pageSize = ref(10)
const small = ref(false)
const disabled = ref(false)

const handleSizeChange = (val: number) => {
  pageSize.value = val
  // page()
  queryRecordByCondition()
  if (tableData.value.length == 0) {
    // page()
    queryRecordByCondition()
  }
}
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  // page()
  queryRecordByCondition()
}

</script>
<style scoped>

.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}

.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}


.demo-form-inline .el-input {
  --el-input-width: 200px;
}

.demo-form-inline .el-select {
  --el-select-width: 400px;
}

.demo-image .block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  display: inline-block;
  width: 20%;
  box-sizing: border-box;
  vertical-align: top;
}

.demo-image .block:last-child {
  border-right: none;
}

.demo-image .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}

.topbar {
  margin-bottom: 15px;
}

/* 假设 .el-pager__item 是分页按钮的类名，这可能需要你根据实际的 Element UI 版本和源码进行调整 */
.el-pager__item {
  background-color: rgba(255, 0, 0, 50%) !important; /* 修改背景色 */
  color: #fff; /* 可能需要修改文本颜色以在红色背景上可见 */
  border-color: transparent; /* 如果需要，修改边框颜色 */
}

/* 修改当前选中页码的按钮样式 */
.el-pager__item.is-active {
  background-color: rgba(255, 0, 0, 70%) !important; /* 选中时的背景色 */
  color: #fff; /* 选中时的文本颜色 */
}
</style>
