<!-- 终端设备远程测控 -->
<template>
  <div class="app-container remote-page" v-loading="loading">
    <div class="hero-panel">
      <div>
        <div class="hero-title">终端设备远程测控</div>
        <div class="hero-subtitle">基于区域控制、手动控制和事故联动预案，模拟值班中心对终端设备的远程控制管理</div>
      </div>
      <el-button type="primary" icon="Refresh" @click="loadDashboard">刷新区域</el-button>
    </div>

    <el-row :gutter="16">
      <el-col :xs="24" :lg="6">
        <el-card shadow="never" class="panel-card">
          <template #header>
            <div class="card-header-row">
              <div class="card-title">区域控制器</div>
              <el-tag>{{ regions.length }} 个区域</el-tag>
            </div>
          </template>

          <div class="region-list">
            <div
              v-for="item in regions"
              :key="item.id"
              class="region-item"
              :class="{ active: selectedRegionId === item.id }"
              @click="selectRegion(item.id)"
            >
              <div class="region-name">{{ item.name }}</div>
              <div class="region-meta">{{ item.location }}</div>
              <div class="region-status">
                <span class="status-dot" :class="item.controlMode === 'auto' ? 'dot-auto' : 'dot-manual'"></span>
                {{ item.controlMode === "auto" ? "自动控制" : "手动控制" }}
              </div>
            </div>
          </div>
        </el-card>

        <el-card v-if="currentRegion" shadow="never" class="panel-card">
          <template #header>
            <div class="card-title">自动控制参数</div>
          </template>
          <el-form label-width="80px" size="small">
            <el-form-item label="上限阈值">
              <el-input-number v-model="autoParams.upperThreshold" :step="0.1" style="width: 100%" />
            </el-form-item>
            <el-form-item label="下限阈值">
              <el-input-number v-model="autoParams.lowerThreshold" :step="0.1" style="width: 100%" />
            </el-form-item>
            <el-form-item label="目标值">
              <el-input-number v-model="autoParams.targetValue" :step="0.1" style="width: 100%" />
            </el-form-item>
            <el-form-item label="采样周期">
              <el-input-number v-model="autoParams.samplePeriod" :step="1" style="width: 100%" />
            </el-form-item>
            <el-button type="primary" style="width: 100%" @click="saveAutoParams">保存参数</el-button>
          </el-form>
        </el-card>
      </el-col>

      <el-col :xs="24" :lg="11">
        <el-card shadow="never" class="panel-card">
          <template #header>
            <div class="card-header-row">
              <div>
                <div class="card-title">中控远程手动控制</div>
                <div class="card-subtitle">{{ currentRegion?.name || "请选择区域" }}</div>
              </div>
              <el-switch
                v-model="manualMode"
                active-text="手动模式"
                inactive-text="自动模式"
                @change="toggleControlMode"
              />
            </div>
          </template>

          <div v-if="currentDevices.length" class="device-list">
            <div v-for="item in currentDevices" :key="item.id" class="device-item">
              <div class="device-main">
                <div class="device-name">{{ item.name }}</div>
                <div class="device-meta">{{ item.type }} · {{ item.deviceId }}</div>
                <div class="device-value">目标值：{{ item.currentValue }} {{ item.unit }}</div>
              </div>
              <div class="device-actions">
                <el-tag :type="item.status === 'running' ? 'success' : 'info'">
                  {{ item.status === "running" ? "运行中" : "已停止" }}
                </el-tag>
                <el-button type="success" plain size="small" :disabled="!manualMode || item.status === 'running'" @click="sendControlCommand(item, 'start')">
                  启动
                </el-button>
                <el-button type="danger" plain size="small" :disabled="!manualMode || item.status === 'stopped'" @click="sendControlCommand(item, 'stop')">
                  停止
                </el-button>
                <el-button size="small" :disabled="!manualMode" @click="openSetValueDialog(item)">设置参数</el-button>
              </div>
            </div>
          </div>
          <el-empty v-else description="当前区域暂无可控设备" />

          <div class="quick-actions">
            <el-button type="primary" plain :disabled="!manualMode" @click="quickCommand('全部启动')">全部启动</el-button>
            <el-button type="danger" plain :disabled="!manualMode" @click="quickCommand('全部停止')">全部停止</el-button>
            <el-button type="warning" plain :disabled="!manualMode" @click="quickCommand('紧急停止')">紧急停止</el-button>
          </div>
        </el-card>

        <el-card shadow="never" class="panel-card">
          <template #header>
            <div class="card-title">设备运行方案</div>
          </template>
          <div class="scheme-list">
            <div v-for="item in operationSchemes" :key="item.id" class="scheme-item">
              <div class="scheme-name">{{ item.name }}</div>
              <div class="scheme-desc">{{ item.description }}</div>
              <div class="scheme-footer">
                <span>设备数量：{{ item.deviceIds.length }}</span>
                <el-button type="primary" link @click="applyScheme(item)">应用方案</el-button>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :lg="7">
        <el-card shadow="never" class="panel-card">
          <template #header>
            <div class="card-title">事故联动控制预案</div>
          </template>
          <div class="plan-list">
            <div v-for="item in incidentPlans" :key="item.id" class="plan-item">
              <div class="plan-name">{{ item.name }}</div>
              <div class="plan-desc">{{ item.description }}</div>
              <div class="plan-devices">联动设备：{{ item.devices.map((d) => d.name).join("、") }}</div>
              <el-button type="warning" plain size="small" @click="triggerIncident(item)">快速启动</el-button>
            </div>
          </div>
        </el-card>

        <el-card shadow="never" class="panel-card">
          <template #header>
            <div class="card-title">控制日志</div>
          </template>
          <div class="log-list">
            <div v-for="item in controlLogs" :key="item.id" class="log-item">
              <div class="log-time">{{ item.time }}</div>
              <div class="log-action">{{ item.action }}</div>
              <div class="log-target">{{ item.target }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog title="设置设备参数" v-model="setValueOpen" width="420px" append-to-body>
      <el-form label-width="90px">
        <el-form-item label="设备名称">
          <span>{{ currentSetDevice?.name || "-" }}</span>
        </el-form-item>
        <el-form-item label="目标值">
          <el-input-number v-model="setValue" :step="0.1" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitSetValue">下发指令</el-button>
          <el-button @click="setValueOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { computed, onMounted, reactive, ref } from "vue";
import { getMonitorPointDetail, listMonitorPointAll, listPipeNetworkAll } from "@/api/pipeNetwork/pdeviceInform";

const loading = ref(false);
const networkOptions = ref([]);
const regions = ref([]);
const selectedRegionId = ref();
const manualMode = ref(false);
const controlLogs = ref([]);
const setValueOpen = ref(false);
const currentSetDevice = ref();
const setValue = ref(0);

const autoParams = reactive({
  upperThreshold: 1.2,
  lowerThreshold: 0.3,
  targetValue: 0.8,
  samplePeriod: 10
});

const operationSchemes = ref([
  { id: 1, name: "高峰供给方案", description: "高峰时段优先启用区域内主要设备", deviceIds: [] },
  { id: 2, name: "低谷节能方案", description: "低谷时段保留关键设备，其余设备停机待命", deviceIds: [] },
  { id: 3, name: "夜间值守方案", description: "仅维持核心设备运行，降低夜间能耗", deviceIds: [] }
]);

const incidentPlans = ref([
  { id: 1, name: "泄漏事故联动", description: "快速停机并通知值班中心介入处理", devices: [] },
  { id: 2, name: "压力异常联动", description: "立即停止相关设备，降低区域运行风险", devices: [] },
  { id: 3, name: "养护维护预案", description: "进入维护模式，按计划逐项停机确认", devices: [] }
]);

const currentRegion = computed(() => {
  return regions.value.find((item) => item.id === selectedRegionId.value);
});

const currentDevices = computed(() => {
  return currentRegion.value?.devices || [];
});

function addLog(action, target) {
  controlLogs.value.unshift({
    id: Date.now() + Math.random(),
    time: new Date().toLocaleTimeString(),
    action,
    target
  });
  controlLogs.value = controlLogs.value.slice(0, 10);
}

function buildRegions(networks, points, detailMap) {
  return networks.map((network, index) => {
    const relatedPoints = points.filter((item) => item.networkId === network.networkId);
    const devices = relatedPoints.flatMap((point) => {
      const detail = detailMap[point.pointId] || {};
      return (detail.equipmentList || []).map((equipment, equipmentIndex) => ({
        id: `${network.networkId}-${equipment.equipmentId}-${equipmentIndex}`,
        equipmentId: equipment.equipmentId,
        name: equipment.equipmentName,
        deviceId: equipment.equipmentCode,
        type: equipment.equipmentModel || "设备",
        status: ["正常", "启用"].includes(point.status) ? "running" : "stopped",
        unit: point.pointType?.includes("压力") ? "MPa" : point.pointType?.includes("流量") ? "m3/h" : "值",
        currentValue: equipmentIndex + 1,
        pointName: point.pointName
      }));
    });
    return {
      id: index + 1,
      networkId: network.networkId,
      name: network.networkName,
      location: network.location || "未维护位置",
      controlMode: index % 2 === 0 ? "auto" : "manual",
      devices
    };
  });
}

function loadDashboard() {
  loading.value = true;
  return Promise.all([listPipeNetworkAll(), listMonitorPointAll()])
    .then(async ([networkRes, pointRes]) => {
      const networks = networkRes.data || [];
      const points = pointRes.data || [];
      networkOptions.value = networks;
      const details = await Promise.all(points.map((item) => getMonitorPointDetail(item.pointId)));
      const detailMap = {};
      details.forEach((detail, index) => {
        detailMap[points[index].pointId] = detail.data || {};
      });
      regions.value = buildRegions(networks, points, detailMap);
      selectedRegionId.value = regions.value[0]?.id;

      const allDeviceIds = regions.value.flatMap((item) => item.devices.map((device) => device.equipmentId));
      operationSchemes.value = operationSchemes.value.map((item, index) => ({
        ...item,
        deviceIds: allDeviceIds.slice(0, Math.max(1, index + 1))
      }));
      incidentPlans.value = incidentPlans.value.map((item, index) => ({
        ...item,
        devices: regions.value.flatMap((region) => region.devices).slice(index, index + 2)
      }));
      addLog("刷新远程测控页面", `共加载 ${regions.value.length} 个区域`);
    })
    .finally(() => {
      loading.value = false;
    });
}

function selectRegion(id) {
  selectedRegionId.value = id;
  manualMode.value = currentRegion.value?.controlMode === "manual";
  addLog("切换区域控制器", currentRegion.value?.name || "-");
}

function saveAutoParams() {
  addLog("保存自动控制参数", `${currentRegion.value?.name || "-"} 阈值已更新`);
}

function toggleControlMode() {
  if (!currentRegion.value) {
    return;
  }
  currentRegion.value.controlMode = manualMode.value ? "manual" : "auto";
  addLog("切换控制模式", `${currentRegion.value.name} -> ${manualMode.value ? "手动模式" : "自动模式"}`);
}

function sendControlCommand(device, command) {
  if (!manualMode.value) {
    addLog("控制拦截", "当前为自动模式，无法手动控制");
    return;
  }
  device.status = command === "start" ? "running" : "stopped";
  addLog(command === "start" ? "启动设备" : "停止设备", device.name);
}

function openSetValueDialog(device) {
  currentSetDevice.value = device;
  setValue.value = device.currentValue || 0;
  setValueOpen.value = true;
}

function submitSetValue() {
  if (currentSetDevice.value) {
    currentSetDevice.value.currentValue = setValue.value;
    addLog("下发参数设置", `${currentSetDevice.value.name} -> ${setValue.value}`);
  }
  setValueOpen.value = false;
}

function quickCommand(command) {
  if (!manualMode.value) {
    addLog("快捷指令拦截", "请先切换到手动模式");
    return;
  }
  currentDevices.value.forEach((device) => {
    device.status = command === "全部启动" ? "running" : "stopped";
  });
  addLog("执行快捷指令", command);
}

function applyScheme(scheme) {
  const targetIds = new Set(scheme.deviceIds);
  regions.value.forEach((region) => {
    region.devices.forEach((device) => {
      if (targetIds.has(device.equipmentId)) {
        device.status = scheme.name.includes("节能") ? "stopped" : "running";
      }
    });
  });
  addLog("应用设备运行方案", scheme.name);
}

function triggerIncident(plan) {
  plan.devices.forEach((device) => {
    const found = regions.value.flatMap((item) => item.devices).find((item) => item.id === device.id);
    if (found) {
      found.status = "stopped";
    }
  });
  addLog("启动事故联动预案", plan.name);
}

onMounted(() => {
  loadDashboard();
});
</script>

<style scoped>
.remote-page {
  background: linear-gradient(180deg, #f3f7fd 0%, #f8fafc 100%);
}

.hero-panel {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
  margin-bottom: 16px;
  padding: 20px 24px;
  border-radius: 18px;
  background: linear-gradient(135deg, #0f2742, #1d4f7d);
  color: #fff;
}

.hero-title {
  font-size: 24px;
  font-weight: 700;
}

.hero-subtitle {
  margin-top: 8px;
  font-size: 13px;
  color: rgba(255, 255, 255, 0.84);
}

.panel-card {
  border-radius: 16px;
  margin-bottom: 16px;
}

.card-header-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 12px;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

.card-subtitle {
  margin-top: 4px;
  font-size: 12px;
  color: #6b7280;
}

.region-list,
.scheme-list,
.plan-list,
.log-list,
.device-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.region-item,
.scheme-item,
.plan-item,
.log-item,
.device-item {
  padding: 12px;
  border-radius: 12px;
  background: #f8fafc;
  border: 1px solid #edf2f7;
}

.region-item {
  cursor: pointer;
}

.region-item.active {
  border-color: #60a5fa;
  background: #eef6ff;
}

.region-name,
.device-name,
.scheme-name,
.plan-name,
.log-action {
  font-size: 14px;
  font-weight: 600;
  color: #111827;
}

.region-meta,
.region-status,
.device-meta,
.device-value,
.scheme-desc,
.scheme-footer,
.plan-desc,
.plan-devices,
.log-time,
.log-target {
  margin-top: 4px;
  font-size: 12px;
  color: #6b7280;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  display: inline-block;
  margin-right: 6px;
}

.dot-auto {
  background: #16a34a;
}

.dot-manual {
  background: #2563eb;
}

.device-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  margin-top: 10px;
}

.quick-actions {
  display: flex;
  gap: 8px;
  margin-top: 16px;
  flex-wrap: wrap;
}

.scheme-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

@media (max-width: 768px) {
  .hero-panel,
  .card-header-row {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>
