<template>
  <div class="page-container">
    <!-- ========== PC 端 ========== -->
    <template v-if="!isMobile">
      <el-card shadow="hover">
        <template #header>
          <div class="card-header">
            <span>提升机查看</span>
            <el-button type="primary" size="small" :loading="refreshing" @click="loadData">
              刷新
            </el-button>
          </div>
        </template>

        <el-row :gutter="20">
          <el-col v-for="elevator in elevators" :key="elevator.id" :span="12">
            <el-card shadow="hover" class="elevator-card">
              <template #header>
                <div class="elevator-card-header">
                  <div class="elevator-title">
                    <span>提升机 #{{ elevator.id }}</span>
                    <el-tag :type="elevator.enable ? 'success' : 'danger'" size="small">
                      {{ elevator.enable ? '已启用' : '已禁用' }}
                    </el-tag>
                  </div>
                  <div v-if="!isMonitorMode" class="elevator-actions">
                    <el-button
                      v-if="elevator.enable"
                      type="warning" size="small" plain
                      @click="handleDisable(elevator)"
                    >禁用</el-button>
                    <el-button
                      v-else
                      type="success" size="small" plain
                      @click="handleEnable(elevator)"
                    >启用</el-button>
                    <el-button
                      type="danger" size="small" plain
                      @click="handleClear(elevator)"
                    >清空任务</el-button>
                  </div>
                </div>
              </template>

              <el-descriptions :column="2" border size="small">
                <el-descriptions-item label="海康出库点位">{{ elevator.hkOutPoint }}</el-descriptions-item>
                <el-descriptions-item label="海康入库点位">{{ elevator.hkInPoint }}</el-descriptions-item>
                <el-descriptions-item label="智世出库点位">{{ elevator.zsOutPoint }}</el-descriptions-item>
                <el-descriptions-item label="智世入库点位">{{ elevator.zsInPoint }}</el-descriptions-item>
              </el-descriptions>

              <el-divider content-position="left">运行状态</el-divider>

              <el-descriptions :column="1" border size="small">
                <el-descriptions-item label="当前工作任务链">
                  <template v-if="elevator.workingTask">
                    <el-link type="primary" @click="goChainDetail(elevator.workingTask)">
                      {{ elevator.workingTask }}
                    </el-link>
                  </template>
                  <template v-else>
                    <el-tag type="success" size="small">空闲</el-tag>
                  </template>
                </el-descriptions-item>
                <el-descriptions-item label="当前出库任务链">
                  <template v-if="elevator.outboundWorkingTask">
                    <el-link type="primary" @click="goChainDetail(elevator.outboundWorkingTask)">
                      {{ elevator.outboundWorkingTask }}
                    </el-link>
                  </template>
                  <template v-else>
                    <span class="text-muted">无</span>
                  </template>
                </el-descriptions-item>
                <el-descriptions-item label="出库等待任务链">
                  <template v-if="elevator.outboundWaitingTaskChains?.length">
                    <div class="task-chain-list">
                      <el-tag
                        v-for="code in elevator.outboundWaitingTaskChains"
                        :key="code"
                        size="small"
                        class="task-chain-tag"
                        @click="goChainDetail(code)"
                      >
                        {{ code }}
                      </el-tag>
                    </div>
                  </template>
                  <template v-else>
                    <span class="text-muted">无</span>
                  </template>
                </el-descriptions-item>
                <el-descriptions-item label="负载模式任务链">
                  <template v-if="elevator.taskChains?.length">
                    <div class="task-chain-list">
                      <el-tag
                        v-for="code in elevator.taskChains"
                        :key="code"
                        size="small"
                        class="task-chain-tag"
                        @click="goChainDetail(code)"
                      >
                        {{ code }}
                      </el-tag>
                    </div>
                  </template>
                  <template v-else>
                    <span class="text-muted">无</span>
                  </template>
                </el-descriptions-item>
              </el-descriptions>
            </el-card>
          </el-col>
        </el-row>

        <el-empty v-if="elevators.length === 0 && !refreshing" description="暂无提升机数据" />
      </el-card>
    </template>

    <!-- ========== 移动端 ========== -->
    <template v-else>
      <div class="m-elevator-header">
        <span class="m-elevator-title">提升机查看</span>
        <el-button type="primary" size="small" round :loading="refreshing" @click="loadData">刷新</el-button>
      </div>

      <div
        v-for="elevator in elevators"
        :key="elevator.id"
        class="m-elevator-card"
      >
        <div class="m-elevator-card-top">
          <div class="m-elevator-name-row">
            <span class="m-elevator-name">提升机 #{{ elevator.id }}</span>
            <el-tag :type="elevator.enable ? 'success' : 'danger'" size="small">
              {{ elevator.enable ? '已启用' : '已禁用' }}
            </el-tag>
          </div>
          <div class="m-elevator-status">
            <span v-if="elevator.workingTask" class="m-working" @click="goChainDetail(elevator.workingTask)">
              {{ elevator.workingTask }}
            </span>
            <el-tag v-else type="success" size="small">空闲</el-tag>
          </div>
        </div>

        <div class="m-point-row">
          <span class="m-point-label">当前出库任务链</span>
          <span
            v-if="elevator.outboundWorkingTask"
            class="m-working"
            @click="goChainDetail(elevator.outboundWorkingTask)"
          >
            {{ elevator.outboundWorkingTask }}
          </span>
          <span v-else class="m-point-value">无</span>
        </div>

        <div class="m-task-chains">
          <span class="m-point-label">出库等待任务链</span>
          <div v-if="elevator.outboundWaitingTaskChains?.length" class="m-task-chain-tags">
            <el-tag
              v-for="code in elevator.outboundWaitingTaskChains"
              :key="code"
              size="small"
              class="m-task-chain-tag"
              @click="goChainDetail(code)"
            >
              {{ code }}
            </el-tag>
          </div>
          <span v-else class="m-point-value">无</span>
        </div>

        <div v-if="elevator.taskChains?.length" class="m-task-chains">
          <span class="m-point-label">负载模式任务链</span>
          <div class="m-task-chain-tags">
            <el-tag
              v-for="code in elevator.taskChains"
              :key="code"
              size="small"
              class="m-task-chain-tag"
              @click="goChainDetail(code)"
            >
              {{ code }}
            </el-tag>
          </div>
        </div>

        <div class="m-elevator-points">
          <div class="m-point-row">
            <span class="m-point-label">海康出/入库</span>
            <span class="m-point-value">{{ elevator.hkOutPoint }} / {{ elevator.hkInPoint }}</span>
          </div>
          <div class="m-point-row">
            <span class="m-point-label">智世出/入库</span>
            <span class="m-point-value">{{ elevator.zsOutPoint }} / {{ elevator.zsInPoint }}</span>
          </div>
        </div>

        <div v-if="!isMonitorMode" class="m-elevator-card-actions">
          <el-button
            v-if="elevator.enable"
            type="warning" size="small" plain round
            @click="handleDisable(elevator)"
          >禁用</el-button>
          <el-button
            v-else
            type="success" size="small" plain round
            @click="handleEnable(elevator)"
          >启用</el-button>
          <el-button
            type="danger" size="small" plain round
            @click="handleClear(elevator)"
          >清空任务</el-button>
        </div>
      </div>

      <el-empty v-if="elevators.length === 0 && !refreshing" description="暂无提升机数据" :image-size="48" />
    </template>
  </div>
</template>

<script setup lang="ts">
defineOptions({ name: 'ElevatorList' })
import {
  clearElevator,
  disableElevator,
  enableElevator,
  getElevatorList,
  type ElevatorVO,
} from '@/api/elevator'
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useDevice } from '@/composables/useDevice'
import { useUserStore } from '@/stores/user'

const { isMobile } = useDevice()
const userStore = useUserStore()
const isMonitorMode = computed(() => userStore.isMonitorMode())
const router = useRouter()
const elevators = ref<ElevatorVO[]>([])
const refreshing = ref(false)

async function loadData() {
  refreshing.value = true
  try {
    const res = await getElevatorList()
    elevators.value = res.data || []
  } catch { /* handled by interceptor */ } finally {
    refreshing.value = false
  }
}

function goChainDetail(code: string) {
  router.push(`/task/chain/${code}`)
}

async function handleEnable(elevator: ElevatorVO) {
  try {
    await ElMessageBox.confirm(`确认启用提升机 #${elevator.id}？`, '确认')
    await enableElevator(elevator.id)
    ElMessage.success('已启用')
    loadData()
  } catch { /* cancelled */ }
}

async function handleDisable(elevator: ElevatorVO) {
  try {
    await ElMessageBox.confirm(`确认禁用提升机 #${elevator.id}？`, '警告', { type: 'warning' })
    await disableElevator(elevator.id)
    ElMessage.success('已禁用')
    loadData()
  } catch { /* cancelled */ }
}

async function handleClear(elevator: ElevatorVO) {
  try {
    await ElMessageBox.confirm(
      `确认清空提升机 #${elevator.id} 的工作任务？此操作不可恢复。`,
      '危险操作',
      { type: 'error' },
    )
    await clearElevator(elevator.id)
    ElMessage.success('已清空')
    loadData()
  } catch { /* cancelled */ }
}

onMounted(loadData)
</script>

<style scoped>
/* ===== 公共 ===== */
.page-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

/* ===== PC ===== */
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-weight: 600;
}

.elevator-card {
  margin-bottom: 20px;
}

.elevator-card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.elevator-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  font-size: 15px;
}

.elevator-actions {
  display: flex;
  gap: 8px;
}

/* ===== 移动端 ===== */
.m-elevator-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.m-elevator-title {
  font-size: 17px;
  font-weight: 600;
  color: #303133;
}

.m-elevator-card {
  background: #fff;
  border-radius: 12px;
  padding: 14px;
}

.m-elevator-card-top {
  margin-bottom: 10px;
}

.m-elevator-name-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 6px;
}

.m-elevator-name {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
}

.m-elevator-status {
  font-size: 13px;
  color: #909399;
}

.m-working {
  color: #409eff;
  cursor: pointer;
  word-break: break-all;
  -webkit-tap-highlight-color: transparent;
}

.task-chain-list {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.task-chain-tag {
  cursor: pointer;
}

.text-muted {
  color: #909399;
  font-size: 12px;
}

.m-task-chains {
  margin-bottom: 10px;
}

.m-task-chains .m-point-label {
  display: block;
  font-size: 12px;
  color: #909399;
  margin-bottom: 6px;
}

.m-task-chain-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.m-task-chain-tag {
  cursor: pointer;
}

.m-elevator-points {
  background: #f8f9fb;
  border-radius: 8px;
  padding: 10px;
  margin-bottom: 10px;
}

.m-point-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 3px 0;
}

.m-point-label {
  font-size: 12px;
  color: #909399;
}

.m-point-value {
  font-size: 12px;
  color: #303133;
  font-family: monospace;
}

.m-elevator-card-actions {
  display: flex;
  gap: 8px;
}
</style>
