<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;">
        <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.dataName" placeholder="请输入数据名称" clearable/>
            </el-form-item>
            <!--          <el-form-item label="数据标签">-->
            <!--            <el-input v-model="queryLine.teamName" placeholder="请输入数据标签" clearable/>-->
            <!--          </el-form-item>-->
            <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.triggerName" placeholder="请输入触发器名称" clearable/>
            </el-form-item>
<!--            <el-form-item label="触发器类型">-->
<!--              <el-input v-model="queryLine.triggerTypeName" placeholder="请输入触发器类型" clearable/>-->
<!--            </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>
          </el-form>
          <el-button type="primary" @click="updateMap">地图更新</el-button>
          <el-button type="primary" @click="goToUpdateStat">地图更新统计</el-button>
          <el-button type="primary" @click="getThreshold">地图重采提醒阈值</el-button>
          <el-button type="primary" @click="goToMapRescan">地图重采提醒</el-button>
<!--          <el-button type="primary" @click="goToMapUpdate">地图更新</el-button>-->

          <el-dialog
              v-model="updateDialogVisible"
              v-if="updateDialogVisible"
              title="地图更新"
              width="400"
              :before-close="handleClose"
              :close-on-click-modal="false"
          >
            <el-steps style="max-width: 600px" :active="update_active" finish-status="success">
              <el-step title="数据拉取"/>
              <el-step title="地图生成"/>
            </el-steps>

            <template #footer>
              <el-button @click="goToUpdateStat" :disabled="update_active !== 2">上传地图</el-button>
            </template>
          </el-dialog>

          <el-dialog
              v-model="mapDialogVisible"
              title="地图重采提醒"
              width="400"
              :before-close="handleMapClose"
              :close-on-click-modal="false"
          >
            <el-form :model="mapRescanForm">
              <el-form-item label="请输入地图重采提醒阈值" label-width="170">
<!--                <el-input v-model="mapRescanForm.value">-->
<!--                  <template #suffix>-->
<!--                    <i slot="suffix" style="color: #181818">%</i>-->
<!--                  </template>-->
<!--                </el-input>-->

                <el-input-number style="width: 90%; margin-right: 5px; float: left" v-model="mapRescanForm.value" :controls="false" :precision="2" />
                <span>%</span>
              </el-form-item>
            </el-form>
            <template #footer>
              <div class="dialog-footer">
                <el-button type="primary" @click="setThreshold">
                  确认
                </el-button>
              </div>
            </template>
          </el-dialog>
          <div style="float: right">
<!--            <el-switch-->
<!--                style="margin-left: 10px;"-->
<!--                v-model="value"-->
<!--                size="large"-->
<!--                inactive-text="算法容器"-->
<!--            />-->
            <span class="el-form-item__label" style="font-size: 14px;">算法镜像选择：</span>
            <el-select
                v-model="selectImageName"
                placeholder="请选择"
                size="default"
                @click.native="getDockerImages('pji_nav')"
                clearable
                style="width: 180px; "
            >
              <el-option
                  v-for="item in imageNames"
                  :key="item"
                  :label="item"
                  :value="item"
              />
            </el-select>
            <el-button type="primary"  @click="algorithmDialogVisible = true" style="margin-left: 10px;">算法镜像导入</el-button>
            <el-dialog
                v-model="algorithmDialogVisible"
                title="请输入算法版本"
                width="300"
                :before-close="handleClose"
                :close-on-click-modal="false"
            >
              <template #footer>
                <div class="dialog-footer">
                  <el-form :model="algorithmForm" label-width="auto">
                    <el-form-item style="margin-bottom: 10px" label="算法版本：" required>
                      <el-input v-model="algorithmForm.tag"/>
                    </el-form-item>
                  </el-form>
                  <!--            -->
                  <!--            <el-button @click="algorithmDialogVisible = false">取消</el-button>-->
                  <el-button type="primary" @click="algorithmImport" :disabled="algorithmForm.tag == ''">选择镜像文件</el-button>
                </div>
              </template>
            </el-dialog>
<!--            <el-button style="margin-left: 10px;"  type="primary" @click="getDockerImages('pji_nav')">算法镜像选择</el-button>-->

            <el-button style="margin-left: 10px;" type="primary" @click="goToTestRecord">仿真测试记录</el-button>
          </div>
        </div>

        <el-dialog
            v-model="worldDialogVisible"
            v-if="worldDialogVisible"
            title="生成world"
            width="400"
            :before-close="handleWorldClose"
            :close-on-click-modal="false"
        >
          <el-steps style="max-width: 600px" :active="world_active" finish-status="success">
            <el-step title="数据准备"/>
            <el-step title="world生成"/>
            <el-step title="world上传"/>
          </el-steps>

          <template #footer>
            <el-button @click="nextToUpload" v-if="world_active != 2" :disabled="world_active !== 1">下一步</el-button>
            <el-upload
                v-if="world_active == 2"
                ref="upload"
                class="upload-demo"
                :action="worldUploadUrl"
                :limit="1"
                :before-upload="beforeUpload"
                :on-exceed="handleExceed"
                :auto-upload="true"
                :multiple="false"
                :on-success="uploadSuccess"
                :on-error="errorMessage"
            >
              <el-button @click="nextToUpload" >上传</el-button>
            </el-upload>
          </template>
        </el-dialog>

        <el-dialog
            v-model="simulationDialogVisible"
            v-if="simulationDialogVisible"
            title="启动仿真测试环境"
            width="400"
            :before-close="handleSimulationClose"
            :close-on-click-modal="false"
        >
          <el-steps style="max-width: 600px" :active="simulation_active" finish-status="success">
            <el-step title="数据拉取"/>
            <el-step title="环境准备"/>
          </el-steps>
          <template #footer>
            <el-button @click="goToDetail" :disabled="simulation_active !== 2">开启仿真配置</el-button>
          </template>
        </el-dialog>

        <el-table stripe style="background-color: rgba(255,0,0,99%);width: 100%" border :data="tableData"
                  fixed ref="multipleTableRef" @selection-change="handleSelectionChange" :cell-style="{ textAlign: 'center'}" :header-cell-style="{ textAlign: 'center'}">
          <el-table-column type="selection" width="55"/>
          <el-table-column prop="dataName" label="数据名称"/>
          <el-table-column prop="dataSize" label="数据容量" :formatter="dataSizeFormatter"/>
          <el-table-column prop="equipmentName" label="设备名称"/>
          <el-table-column prop="equipmentNo" label="设备sn码" :formatter="equipmentNoFormatter"/>
          <el-table-column prop="equipmentTypeName" label="设备类型"/>
          <el-table-column prop="triggerName" label="触发器名称"/>
          <el-table-column prop="triggerTypeName" label="触发器类型"/>
          <el-table-column prop="callbackTime" label="上报时间"/>
          <el-table-column prop="dataStateName" label="数据状态"/>
          <el-table-column width="300" fixed="right" label="操作">
            <template v-slot="scope">
              <el-button size="small" type="danger" @click="generateWorld(scope.row)">生成world</el-button>
              <el-button size="small" type="danger" @click="startSimulation(scope.row)">仿真测试</el-button>
              <!--            <el-button size="small" type="danger" @click="goToDetail">算法评价</el-button>-->
            </template>

          </el-table-column>
        </el-table>
        <p></p> <!--空行-->
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 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, ref, nextTick} from "vue";
import axios from "axios";
import {reactive} from 'vue'
import {ElTable, ElLoading, ElMessage} from "element-plus";
import {useRouter} from 'vue-router'; // 导入 Vue Router 的 useRouter 钩子
import { genFileId } from 'element-plus'
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'

const value
    = ref(true)
const update_active = ref(0)
const world_active = ref(0)
const simulation_active = ref(0)
const router = useRouter();

const multipleTableRef = ref<InstanceType<typeof ElTable>>

const algorithmDialogVisible = ref(false)
const mapDialogVisible = ref(false)
const updateDialogVisible = ref(false)
const worldDialogVisible = ref(false)
const simulationDialogVisible = ref(false)

const upload = ref<UploadInstance>()
const worldUploadUrl = ref<string>()
const stlUploadUrl = ref<string>()

const selectImageName = ref("")
const imageNames = ref([])
const currentRow = ref()
const worldUrl = ref("")

const PJI_SCRIPT_PATH_PREFIX = import.meta.env.VITE_PJI_SCRIPT_PATH_PREFIX

const goToMapUpdate = () => {
  router.push('/map_update')
}

const goToUpdateStat = () => {
  router.push('/update_stat')
}

const setThreshold = async () =>{
  try {
    const response =  await axios.get('/local/config/update/rescanReminderThreshold?threshold=' + mapRescanForm.value)
    // console.log(response.data)

    if (!response.data.status) {
      ElMessage.error("更新地图重采阈值失败")
      return
    }
    mapDialogVisible.value = false
  } catch (error) {
    ElMessage.error("更新地图重采阈值失败")
    console.log("Error updating the threshold:", error)
  }
}

// console.log("path:", import.meta.env.VITE_PJI_SCRIPT_PATH_PREFIX)

const getThreshold = async () => {
  try {
    const response =  await axios.get('/local/config/query/rescanReminderThreshold')
    // console.log(response.data)

    if (!response.data.status) {
      ElMessage.error("获取地图重采阈值失败")
      return
    }
    mapRescanForm.value = +response.data.data
    mapDialogVisible.value = true
  } catch (error) {
    ElMessage.error("获取地图重采阈值失败")
    console.log("Error querying the threshold:", error)
  }
}


const goToDetail = () => {
  router.push({
    name: 'about',
    query: {
      "scene_id": currentRow.value.id,
      "device_type": currentRow.value.equipmentTypeName,
      "device_id": currentRow.value.equipmentId,
      "device_no":  currentRow.value.equipmentNo,
      "device_name": currentRow.value.equipmentName,
      "world_path": worldUrl.value,
      "algo_image_name": selectImageName.value
    }
  })
}

const goToMapRescan = () => {
  router.push('/map_rescan')
}

const goToTestRecord = () => {
  router.push('/test_record')
}

const handleClose = (done: () => void) => {
  algorithmForm.tag = ""
  done()
}
const handleWorldClose = (done: () => void) => {
  world_active.value = 0
  done()
}
const handleSimulationClose = (done: () => void) => {
  simulation_active.value = 0
  done()
}
const handleMapClose = (done: () => void) => {
  done()
}
const nextToUpload = () => {
  world_active.value = 2
}

const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
}

const beforeUpload = (file) => {
  const isWorld = file.name.endsWith(".world")
  if(!isWorld) {
    ElMessage.error("请上传world文件（以.world结尾）！")
    return false
  } else {
    return true
  }
}

//上传文件失败
const errorMessage = (response) => {
  return ElMessage({
    message: "文件上传失败",
    type: "error",
    offset: 60
  })
}

//上传文件成功
const uploadSuccess = (response, file, fileList) => { // world 文件上传成功
  // 继续上传map.stl文件
  uploadStlFile(() => {
    // 更新步骤条状态
    world_active.value = 3
    ElMessage({
      message: "文件上传成功，请关闭对话框",
      type: "success",
      offset: 60
    })
  })
}

const uploadStlFile = (callback) => {
  // stl文件路径
  const filePath =  PJI_SCRIPT_PATH_PREFIX + "simulation/catkin_map2gazebo/src/models/map/meshes/map.stl"
  if(stlUploadUrl.value !== "") { // 上传路径不为空
    // 执行脚本 - 上传文件
    window.electronAPI.uploadFile(filePath, stlUploadUrl.value);
    // 监听脚本执行状态
    window.electronAPI.onUploadFileResponse( (event, result) => {
      if (result.success) { // 脚本执行成功
        console.log('Script execution completed successfully.')
        // 执行回调 - 状态变更及提醒
        callback()
      } else { // 脚本执行失败
        console.error('Script execution failed.');
      }
    })
  }
}

const getDockerImages = (filter_prefix) => {
  axios.get('/docker/v1.43/images/json').then(function (response) {
    // console.log(response.data);
    var images = response.data
        .filter(d => d["RepoTags"].length > 0)
        .map(d => d["RepoTags"][0])
        .filter(d => d.startsWith(filter_prefix))
    // console.log("images", images)
    imageNames.value = images
  }).catch(function (error) {
    console.log(error);
  });
}
const multipleSelection = ref<[]>([])

// do not use same name with ref
const algorithmForm = reactive({
  sudoPassword: '',
  tag: '',
  // date1: '',
  // date2: '',
  // delivery: false,
  // type: [],
  // resource: '',
  // desc: '',
})

const mapRescanForm = reactive({
  value: 0
})

const algorithmImport = async () => {
  try {
    const result = await window.electronAPI.openFileManager();
    if (result == null) {
      ElMessage.info("未选择文件")
      return
    }
    console.log('用户选择的文件路径为:', result, '，版本为：', algorithmForm.tag);
    // 开启loading
    let loadingInstance = ElLoading.service({fullscreen: false, target: '.el-dialog', text: '算法镜像导入中...'})

    // 导入镜像
    window.electronAPI.dockerImport(result, algorithmForm.tag)
    // 监听脚本执行状态
    window.electronAPI.onDockerImportResponse( (event, result) => {
      loadingInstance.close()

      algorithmDialogVisible.value = false
      if (result.success) { // 脚本执行成功
        console.log('Script execution completed successfully.')
        ElMessage.success("镜像导入成功！");
      } else { // 脚本执行过程中发生错误
        console.error('Script execution failed.');
        ElMessage.error("镜像导入发生错误！");
      }
    })
  } catch (error) {
    console.error('打开文件管理器时出错:', error);
  }
};

// 数据容量单位从B转成MB
const dataSizeFormatter = (row, column, cellValue, index) => {
  // 假设 1MB = 1024 * 1024 字节
  if (cellValue) {
    const mb = (cellValue / (1024 * 1024)).toFixed(2); // 保留两位小数
    return `${mb}MB`;
  }
  return cellValue; // 如果cellValue为null或undefined，则返回原值或你想要的默认值
}

const equipmentNoFormatter = (row, column, cellValue, index) => {
  return removePerfix(cellValue, "pjibot-");
}

const isPropertySame= (array, propertyName) => {
  if (array.length <= 1) {
    return true; // 空数组或但个元素视为所有值相同
  }

  const firstValue = array[0][propertyName];

  for (let i = 1; i < array.length; i++) {
    if (array[i][propertyName] !== firstValue) {
      return false; // 发现不同的值
    }
  }

  return true; // 所有值都是相同的
}

const getTimeByDataName = (dataName) => {
  const parts = dataName.split("-");

  const year = parseInt(parts[0], 10);
  const month = parseInt(parts[1], 10) - 1;
  const day = parseInt(parts[2], 10);
  const hours = parseInt(parts[3], 10) + 8;
  const minutes = parseInt(parts[4], 10);
  const seconds = parseInt(parts[5], 10);
  return new Date(year, month, day, hours, minutes, seconds).getTime()
}

const getLatestTime = (reocrds) => {

  let latestTime = getTimeByDataName(reocrds[0].dataName)
  console.log("1", latestTime)
  for (let i = 1; i < reocrds.length; i++) {
    let time = getTimeByDataName(reocrds[i].dataName)
    if ( time > latestTime) {
      latestTime = time
    }
  }
  return latestTime.toString()
}


// 地图更新
const updateMap = async () => {
  // 检查选择的记录数量
  if (multipleSelection.value.length < 3) {
    ElMessage.error("请至少选择三条属于同一设备的记录！")
    return
  }

  // 检查记录是否属于同一机器人
  const isEquipmentSame = isPropertySame(multipleSelection.value, "equipmentId")
  if (!isEquipmentSame) { // 属于多个设备
    ElMessage.error("所选择的记录属于多个设备，请进行检查！")
    return
  }

  // 检查记录的mapBuf是否一致
  let ids = multipleSelection.value.map(item => item["id"])
  console.log("ids:",ids)
  let response = await checkMapbufConsistency(ids)
  console.log("response", response)
  if(!response.status) {
    ElMessage.error("所选择的记录mapBuf不一致，请重新选择！")
    return
  }

  // 更新设备地图记录
  response = await updateDeviceMap()
  console.log("response", response)
  if(!response.status) {
    ElMessage.error("数据更新失败，请重试！")
    return
  }

  // 准备数据
  const currentRow = multipleSelection.value[0]
  const id = currentRow.id
  const device_id = currentRow.equipmentId
  const device_no = currentRow.equipmentNo
  const device_name = currentRow.equipmentName
  const device_type = currentRow.equipmentTypeName
  const updateTime = Date.now()
  const updateFlag = 0

  const recordTime = getLatestTime(multipleSelection.value)
  console.log("recordTime", recordTime)

  console.log(device_id, device_no, device_name, device_type, device_no, updateTime, updateFlag)
  // 检查地图状态（是否可以更新）
  response = await checkDeviceMapStatus(id, removePerfix(device_no, "pjibot-"), device_name, device_type, recordTime)

  if (!response.status) {
    if (response.code != "") {
      ElMessage.error(response.msg)
    } else {
      ElMessage.error("地图状态查询失败")
    }
    return
  }

  // 开启对话框
  updateDialogVisible.value = true
  await nextTick()

  // 保证相同场景id列表下载压缩包文件名一致
  ids = ids.sort()

  // 根据id下载地图更新需要的数据（压缩包）
  const idList = ids.reduce((acc, id) => {return acc + "+" + id}, "")
  const url = "http://localhost:8888/map/download/zip?id=" + ids.flat() + "&deviceNo=" + removePerfix(device_no, "pjibot-")  // 此处url不受配置的代理规则影响，应传递后端完整url地址

  const fileName = "data" + idList + ".zip"
  const savePath = PJI_SCRIPT_PATH_PREFIX + "tmp_download/map_zip/"
  const filePath = savePath + fileName
  const containerName = " map_update_20240923"

  // 开启loading
  let loadingInstance = ElLoading.service({fullscreen: false, target: '.el-dialog', text: '依赖数据拉取中...'})

  // 保证朴津地图压缩包及map.pgm已上传到oss，从而正确拉取地图更新所需压缩包
  response = await uploadOriginalMapById(id, removePerfix(device_no, "pjibot-"))
  console.log("response", response)
  if(!response.status) {
    ElMessage.error("数据更新失败，请重试！")
    return
  }


  const result = await window.electronAPI.downloadFile(url, fileName, savePath, false, false, "get", {});
  if (!result.success) { // 下载失败
    console.error('File download failed:', result.error);
    loadingInstance.close()
    ElMessage.error("地图更新数据拉取失败！");
  } else { // 下载成功
    console.log('File downloaded successfully:', result.filePath);
    // 关闭loading
    loadingInstance.close()
    // 更新步骤条状态
    update_active.value = 1
    console.log("Updating map...")
    // 执行脚本 - 生成world，启动gazebo
    window.electronAPI.updateMap(containerName, filePath);
    // 开启loading
    loadingInstance = ElLoading.service({fullscreen: false, target: '.el-dialog', text: '地图更新中...'})
    // 监听脚本执行状态
    window.electronAPI.onUpdateMapResponse( async (event, result) => {
      if (result.success) { // 脚本执行成功
        console.log('Script execution completed successfully.')
        // 关闭loading
        loadingInstance.close()
        // 更新步骤条状态
        update_active.value = 2
        // // 使用 Electron 进行文件删除操作
        // window.electronAPI.deleteFile(fileName, savePath)
        // // 监听删除文件的响应
        // window.electronAPI.onDeleteFileResponse((event, response) => {
        //   if (response.success) { // 删除成功
        //     console.log("File deleted successfully.")
        //   } else { // 删除失败
        //     console.log(`Error: ${response.message}`)
        //   }
        // })

        const res = await window.electronAPI.processMapUpdateFiles();
        console.log("res", res)
        if (res.success) {
          let data = res.data
          // 拼接待上传数据
          let map_update_data = {
            "map_id": data["jsonData"]["origin_pgm_id"],
            "device_id": device_id,
            "device_sn": removePerfix(device_no, "pjibot-"),
            "device_name": device_name,
            "device_type": device_type,
            "pre_pgm_url": data["prePgmUrl"],
            "pre_png_url": data["prePngUrl"],
            "current_pgm_url": data["updatePgmUrl"],
            "current_png_url": data["updatePngUrl"],
            "update_rate": data["jsonData"]["update_perecent"],
            "cumulative_update_rate": data["jsonData"]["origin_update_perecent"],
            "update_time": String(updateTime),
            "from_scene_list": JSON.stringify(ids.flat()),
            "update_flag": updateFlag,
            "update_map_url": data["updateMapUrl"]
          }
          console.log("map_update_data", map_update_data)
          // 上传数据
          let response = await axios.post('/local/map/add/record', map_update_data)
          console.log("res", response)
        } else {
          ElMessage.error("地图更新数据保存失败！");
          loadingInstance.close()
        }
      } else { // 脚本执行过程中发生错误
        console.error('Script execution failed.');
        loadingInstance.close()
        ElMessage.error("地图更新发生错误！");
      }
    })
  }
}

const removePerfix = (str, prefix) => {
  const regex = new RegExp("^" + prefix)
  return str.replace(regex, "")
}

const checkMapbufConsistency = async (ids) => {
 try {
   const response =  await axios.post('/local/map/check/mapbuf/consistency', ids)
   console.log(response.data)
   return response.data
 } catch (error) {
   console.log("Error checking the mapBufs' onsistency:", error)
 }
}

const updateDeviceMap = async () => {
  try {
    const response =  await axios.get('/local/map/update/deviceMap/record')
    console.log(response.data)

    return response.data
  } catch (error) {
    console.log("Error updating the device-map:", error)
  }
}

const uploadOriginalMapById = async (sceneId, deviceNo) => {
  try {
    const response =  await axios.get('/local/map/upload/originalMap/oneRecord?sceneId=' + sceneId + '&deviceNo=' + deviceNo)
    console.log(response.data)

    return response.data
  } catch (error) {
    console.log("Error uploading the original map:", error)
  }
}

const checkDeviceMapStatus = async (sceneId, deviceNo, deviceName, deviceType, recordTime) => {
  try {
    const response =  await axios.get('/local/map/check/deviceMap/status?sceneId=' + sceneId + '&deviceNo='
        + deviceNo + '&deviceType=' + deviceType + '&deviceName=' + deviceName + '&recordTime=' + recordTime)
    console.log(response.data)

    return response.data
  } catch (error) {
    console.log("Error checking the device map's status:", error)
  }
}

const handleSelectionChange = (rows: []) => {
  multipleSelection.value = rows
  // 检查记录是否属于同一机器人
  const isEquipmentSame = isPropertySame(rows, "equipmentId")
  if (!isEquipmentSame) {
    ElMessage.error("所选择的记录属于多个设备，请进行检查！");
  } else {
    // console.log(JSON.stringify(multipleSelection.value))
  }
}

// world文件生成
const generateWorld = async (row) => {
  const id = row.id
  const equipmentNo = row.equipmentNo
  const sceneNo = id
  const url = "http://127.0.0.1:8888/map/download/mapbag?id=" + id
  const fileName = "map-" + id + ".bag"
  const savePath = PJI_SCRIPT_PATH_PREFIX + "tmp_download/map_bag"
  console.log("id", id)

  // 拼接world文件上传url
  worldUploadUrl.value = "http://127.0.0.1:8888/world/upload/world?equipmentNo=" + equipmentNo + "&sceneNo=" + sceneNo
  console.log("worldUploadUrl.value=" + worldUploadUrl.value)

  // 拼接map.stl文件上传url
  stlUploadUrl.value = "http://127.0.0.1:8888/world/upload/stl?equipmentNo=" + equipmentNo + "&sceneNo=" + sceneNo
  console.log("stlUploadUrl.value=" + stlUploadUrl.value)

  console.log("Downloading file: map.bag...")
  // 开启对话框
  worldDialogVisible.value = true
  // 开启loading
  let loadingInstance = ElLoading.service({fullscreen: false, target: '.el-dialog', text: "依赖数据拉取中..."})
  // 下载map.bag
  const result = await window.electronAPI.downloadFile(url, fileName, savePath, false, false, "get", {});
  if (!result.success) { // 下载失败
    console.error('File download failed:', result.error);
    // 关闭loading
    loadingInstance.close()
    ElMessage.error("地图bag数据拉取失败！");
  } else { // 下载成功
    // 关闭loading
    loadingInstance.close()
    console.log('File downloaded successfully:', result.filePath);
    // 更新步骤条状态
    world_active.value = 1
    console.log("Starting world generation...")
    // 执行脚本 - 生成world，启动gazebo
    window.electronAPI.generateWorld(result.filePath);
    // 开启loading
    loadingInstance = ElLoading.service({fullscreen: false, target: '.el-dialog', text: "world文件生成中..."})
    // 监听脚本执行状态
    window.electronAPI.onGenerateWorldResponse( (event, result) => {
      if (result.success) { // 脚本执行成功
        console.log('Script execution completed successfully.')
        // 关闭loading
        loadingInstance.close()
        // 使用 Electron 进行文件删除操作
        window.electronAPI.deleteFile(fileName, savePath)
        // 监听删除文件的响应
        window.electronAPI.onDeleteFileResponse((event, response) => {
          if (response.success) { // 删除成功
            console.log("File deleted successfully.")
          } else { // 删除失败
            console.log(`Error: ${response.message}`)
          }
        })
      } else { // 脚本执行过程中发生错误
        console.error('Script execution failed.');
        // 关闭loading
        loadingInstance.close()
        ElMessage.error("world生成发生错误！");
      }
    })
  }
}

// 仿真测试环境准备
const startSimulation = async (row) => {
  // 保存row
  currentRow.value = row
  // console.log("currentRow.value", currentRow.value)
  // 检查是否已选择算法镜像
  let imageName = selectImageName.value
  let containerName = imageName.replace(':', '_')
  if (imageName === "") { // 未选择
    ElMessage.error("请选择算法镜像！")
    return
  }

  // 检查data目录是否存在
  let response = await axios.get('/local/simulation/check/file/data/status?id=' + row.id);
  if (!response.data.status){ // 不存在
    ElMessage.error("data目录不存在，无法执行仿真测试！")
    return
  }

  // 检查world文件是否存在
  response = await axios.get('/local/world/check/file/world/status?id=' + row.id)

  if (!response.data.status){ // 不存在
    ElMessage.error("world文件不存在，请先生成并上传world文件！")
    return
  }
  worldUrl.value = response.data.details

  // 开启对话框
  simulationDialogVisible.value = true
  await nextTick()

  // 根据id下载仿真测试需要的数据（压缩包）
  const id = row.id
  const url = "http://localhost:8888/simulation/download/zip?id=" + id // 此处url不受配置的代理规则影响，应传递后端完整url地址
  const fileName = "data-" + id + ".zip"
  const savePath = PJI_SCRIPT_PATH_PREFIX + "tmp_download/simulation_zip"

  console.log("Starting download files...")
  // 开启loading
  let loadingInstance = ElLoading.service({fullscreen: false, target: '.el-dialog', text: "依赖数据拉取中..."})
  const result = await window.electronAPI.downloadFile(url, fileName, savePath, false, false, "get", {});
  if (!result.success) { // 下载失败
    console.error('File download failed:', result.error);
    loadingInstance.close()
    ElMessage.error("仿真测试数据拉取失败！");
  } else { // 下载成功
    console.log('File downloaded successfully:', result.filePath);
    loadingInstance.close()
    // 更新步骤条状态
    simulation_active.value = 1
    // // 延时
    // setTimeout(() => {}, 500)
    // 开启loading
    loadingInstance = ElLoading.service({fullscreen: false, target: '.el-dialog', text: "仿真环境启动中..."})
    // 执行脚本 - 数据准备，启动容器
    window.electronAPI.startContainer(result.filePath, imageName, containerName);
    // 监听脚本执行状态
    window.electronAPI.onStartContainerResponse( (event, result) => {
      if (result.success) { // 脚本执行成功
        console.log('Script execution completed successfully.')
        // 关闭loading
        loadingInstance.close()
        // 更新步骤条状态
        simulation_active.value = 2
        // // 使用 Electron 进行文件删除操作
        // window.electronAPI.deleteFile(fileName, savePath)
        // // 监听删除文件的响应
        // window.electronAPI.onDeleteFileResponse((event, response) => {
        //   if (response.success) { // 删除成功
        //     console.log("File deleted successfully.")
        //   } else { // 删除失败
        //     console.log(`Error: ${response.message}`)
        //   }
        // })
      } else { // 脚本执行过程中发生错误
        console.error('Script execution failed.');
        ElMessage.error("仿真测试环境发生错误！");
      }
    })

  }
}

const queryLine = reactive({
  dataName: '',
  equipmentName: '',
  equipmentTypeName: '',
  triggerName: '',
  triggerTypeName: '',
  equipmentType: '',
})
const equipmentTypes =ref(["引导服务机器人"])
const onSubmit = () => {
  page()
}

let total = ref(0)
let tableData = ref([]);
onBeforeMount(() => {
  page()
})

// 根据条件筛选结果
const queryRecordByCondition = async () => {
  axios.get('/pji/open/scene/list?equipmentType=YI_DAO_JI_QI_REN&page=' + currentPage.value + '&size=' + pageSize.value
      + '&dataName=' + queryLine.dataName + '&equipmentName=' + queryLine.equipmentName + '&triggerName=' + queryLine.triggerName ,
      {
        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.value);
    // console.log(response.data.data);
  }).catch(function (error) {
    console.log(error);
  });
}

function page() {
  axios.get('/pji/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.value);
    // console.log(response.data.data);
  }).catch(function (error) {
    console.log(error);
  });
}

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

const handleSizeChange = (val: number) => {
  pageSize.value = val
  page()
  if (tableData.value.length == 0) {
    page()
  }
}
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  page()
}
const handleClick = () => {
  console.log('click')
}


</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>
