<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="巷道id" prop="plcId">
        <el-input
          v-model="queryParams.plcId"
          placeholder="请输入巷道id"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['logistics:street:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['logistics:street:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="巷道标识符" align="center" prop="plcId" />
      <el-table-column label="巷道ip" align="center" prop="plcIp" />
      <!--<el-table-column label="左货架类型" align="center" prop="leftType">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.SHELVES_TYPE" :value="scope.row.leftType" />
        </template>
      </el-table-column>
       <el-table-column label="左货架列数量" align="center" prop="leftColumn" />
      <el-table-column label="左货架行数量" align="center" prop="leftRow" />
      <el-table-column label="右货架类型" align="center" prop="rightType">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.SHELVES_TYPE" :value="scope.row.rightType" />
        </template>
      </el-table-column>
      <el-table-column label="右货架列数量" align="center" prop="rightColumn" />
      <el-table-column label="右货架行数量" align="center" prop="rightRow" />
      <el-table-column label="球机" align="center" prop="camera1Id" />
      <el-table-column label="球机" align="center" prop="camera2Id" />
      <el-table-column
        label="修改时间"
        align="center"
        prop="updateTime"
        :formatter="dateFormatter"
        width="180px"
      /> -->
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['logistics:street:update']"
          >
            编辑
          </el-button>
           <el-button
            link
            type="primary"
            @click="showConnectionStatus(scope.row.id)"
            v-hasPermi="['logistics:street:link']"
          >
            连接
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['logistics:street:delete']"
          >
            删除
          </el-button>
         
        </template>
      </el-table-column>
    </el-table>
    
    <el-dialog
      v-model="dialogVisible"
      title="连接状态详情"
      width="500px"
      @close="handleDialogClose"
      
    >
      <div 
      height="700px" v-if="connectionStatusData && connectionStatusData.length > 0">
        <el-alert
          v-loading="loadingLink"
          v-for="(item, index) in connectionStatusData"
          :key="index"
          :title="formatConnectionStatus(item)"
          :type="item.connect ? 'success' : 'error'"
          :closable="false"
          class="mb-10px"
        />
      </div>
      
    </el-dialog>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <StreetForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import download from '@/utils/download'
import { StreetApi, StreetVO } from '@/api/logistics/street'
import StreetForm from './StreetForm.vue'

/** 巷道 列表 */
defineOptions({ name: 'Street' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

// 连接状态相关
const connectionStatusData = ref<any[]>([])
const currentStreetId = ref<number | null>(null)

const loadingLink = ref(true) // 列表的加载中
const dialogVisible = ref(false)
const loading = ref(true) // 列表的加载中
const list = ref<StreetVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  plcId: undefined,
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await StreetApi.getStreetPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}


// /** 连接查看操作 */
// const linkCheck = async (id: number) => {
//   try {
//     // 发起连接检查
//     await StreetApi.linkCheck(id)
//     message.success('连接检查已发起')
//     // 刷新列表
//     await getList()
//   } catch (err) {
//     message.error('连接检查失败')
//   }
// }

/** 显示连接状态详情 */
const showConnectionStatus = async (id: number) => {
  try {
    
    dialogVisible.value = true
    loadingLink.value = true // 开始加载
    const data = await StreetApi.linkCheck(id)
    connectionStatusData.value = data
    currentStreetId.value = id
  } catch (err) {
    message.error('获取连接状态失败')
  } finally {
    loadingLink.value = false // 结束加载
  }
}

/** 格式化连接状态显示 */
const formatConnectionStatus = (item: any) => {
  if (!item.ip || !item.port) {
    return `${item.type} 连接状态异常！配置信息不完整`
  }
  
  return `${item.type} 连接${item.connect ? '正常' : '异常'}！ip：${item.ip}，端口：${item.port}`
}

// /** 获取连接状态文本 */
// const getConnectionStatusText = (id: number) => {
//   return '查看状态'
// }

// /** 获取连接状态类型 */
// const getConnectionStatusType = (id: number) => {
//   // 这里可以根据实际需求返回不同的按钮类型
//   return 'primary'
// }

/** 关闭对话框 */
const handleDialogClose = () => {
  connectionStatusData.value = []
  currentStreetId.value = null
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await StreetApi.deleteStreet(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await StreetApi.exportStreet(queryParams)
    download.excel(data, '巷道.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>