<template>
  <div class="control-command-system">
    <!-- 查询条件区域 -->
    <el-card class="filter-card">
      <el-form :model="queryParams" ref="searchForm" :inline="true" class="search-form">
        <!-- 控制指令条件 -->
        <el-form-item label="指令ID">
          <el-input v-model="queryParams.cmdId" placeholder="请输入指令ID" clearable />
        </el-form-item>

        <el-form-item label="指令类型">
          <el-select v-model="queryParams.cmdType" placeholder="请选择指令类型" style="width: 180px;">
            <el-option label="全部" value="" />
            <el-option label="参数设置" value="SET_PARAM" />
            <el-option label="报警触发" value="TRIGGER_ALARM" />
            <el-option label="设备启停" value="START_STOP" />
            <el-option label="校准操作" value="CALIBRATE" />
            <el-option label="设备重置" value="RESET" />
          </el-select>
        </el-form-item>

        <!-- 执行状态条件 -->
        <el-form-item label="指令状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" style="width: 180px;">
            <el-option label="全部" value="" />
            <el-option label="待执行" value="PENDING" />
            <el-option label="成功" value="SUCCESS" />
            <el-option label="失败" value="FAILED" />
          </el-select>
        </el-form-item>

        <!-- 操作审计条件 -->
        <el-form-item label="操作员ID">
          <el-input v-model="queryParams.operatorId" placeholder="请输入操作员ID" clearable />
        </el-form-item>

        <!-- 响应监控条件 -->
        <el-form-item label="设备反馈">
          <el-select v-model="queryParams.feedbackStatus" placeholder="请选择反馈状态" style="width: 180px;">
            <el-option label="全部" value="" />
            <el-option label="正常" value="OK" />
            <el-option label="超时" value="TIMEOUT" />
            <el-option label="错误" value="ERROR" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleSearch">搜索</el-button>
          <el-button icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格区域 -->
    <el-card class="data-table">
      <el-table
          :data="commandList"
          border
          size="small"
          v-loading="isLoading"
          row-key="cmdId"
          @row-click="handleRowClick"
      >
        <el-table-column label="指令ID" prop="cmdId" align="center" width="140" />
        <el-table-column label="目标设备" align="center" >
          <template #default="scope">
            <el-tag
                v-for="device in scope.row.targetDevices"
                :key="device"
                size="small"
                type="info"
            >
              {{ device }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="指令类型" prop="cmdType" align="center" />
        <el-table-column label="指令状态" prop="status" align="center" width="120">
        <template #default="scope">
          <el-tag
              :type="getStatusColor(scope.row.status)"
              :effect="scope.row.status === 'SUCCESS' ? 'light' : 'dark'"
          >
            {{ mapStatus(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
        <el-table-column label="操作员" prop="operatorId" align="center" width="100" />
        <el-table-column label="执行时间" prop="timestamp" align="center" width="180" />
        <el-table-column label="执行耗时" align="center" width="120">
          <template #default="scope">
            {{ scope.row.executionTime }} ms
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      />
    </el-card>

    <!-- 详情弹窗 -->
    <el-dialog :visible.sync="detailDialogOpen" title="指令详情" width="1000px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="指令ID" span="1">{{ detailCommand.cmdId }}</el-descriptions-item>
        <el-descriptions-item label="指令类型" span="1">{{ mapCmdType(detailCommand.cmdType) }}</el-descriptions-item>
        <el-descriptions-item label="目标设备" span="2">
          <el-tag
              v-for="device in detailCommand.targetDevices"
              :key="device"
              size="medium"
              type="info"
          >
            {{ device }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="指令状态" span="1">
          <el-badge
              :text="mapStatus(detailCommand.status)"
              :type="getStatusColor(detailCommand.status)"
              :icon="getStatusIcon(detailCommand.status)"
          />
        </el-descriptions-item>
        <el-descriptions-item label="执行时间" span="1">{{ detailCommand.timestamp }}</el-descriptions-item>
        <el-descriptions-item label="操作员" span="1">{{ detailCommand.operatorId }}</el-descriptions-item>
        <el-descriptions-item label="IP地址" span="1">{{ detailCommand.ipAddress }}</el-descriptions-item>
        <el-descriptions-item label="操作详情" span="2">{{ detailCommand.operationDetail }}</el-descriptions-item>
      </el-descriptions>

      <!-- 响应监控信息 -->
      <el-card class="mt-4" title="设备响应与执行详情">
        <el-row :gutter="20">
          <el-col span="12">
            <el-card class="response-card">
              <div class="card-title">反馈状态</div>
              <div class="status-icon" :class="getStatusClass(detailCommand.feedbackStatus)"></div>
              <div>{{ mapFeedbackStatus(detailCommand.feedbackStatus) }}</div>
            </el-card>
          </el-col>
          <el-col span="12">
            <el-card class="execution-card">
              <div class="card-title">执行耗时</div>
              <div class="time-value">{{ detailCommand.executionTime }} ms</div>
              <div v-if="detailCommand.errorCode !== 'NONE'">
                <div class="error-title">异常代码</div>
                <div class="error-code">{{ detailCommand.errorCode }}</div>
                <el-tooltip content="点击查看错误详情" placement="top">
                  <el-button
                      type="text"
                      size="small"
                      @click="showErrorDialog"
                  >
                    查看详情
                  </el-button>
                </el-tooltip>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-card>

      <!-- 策略配置信息 -->
      <el-card class="mt-4" title="策略配置与联动规则">
        <el-row :gutter="16">
          <el-col span="12">
            <h4>定时任务</h4>
            <p>{{ detailCommand.scheduleTask || "无定时任务" }}</p>
          </el-col>
          <el-col span="12">
            <h4>场景模式</h4>
            <p>{{ detailCommand.sceneMode || "无场景模式" }}</p>
          </el-col>
        </el-row>
        <el-row :gutter="16" class="mt-4">
          <el-col span="24">
            <h4>联动规则</h4>
            <p>{{ detailCommand.linkageRule || "无联动配置" }}</p>
          </el-col>
        </el-row>
      </el-card>

      <!-- 错误详情弹窗 -->
      <el-dialog
          v-model="errorDialogOpen"
          title="错误详情"
          width="400px"
      >
        <p>异常代码：{{ detailCommand.errorCode }}</p>
        <p>处理建议：{{ getErrorSuggestion(detailCommand.errorCode) }}</p>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { ElMessage, ElBadge, ElDialog } from 'element-plus';
import {
  getBuildingEquipmentMonitoringCommandsList
} from "@/api/buildingEquipmentMonitoring/buildingEquipmentMonitoring";

// 查询参数
const queryParams = reactive({
  cmdId: '',
  cmdType: '',
  status: '',
  operatorId: '',
  feedbackStatus: '',
  pageNum: 1,
  pageSize: 10,
});

// 表格数据
const commandList = ref([]);
const total = ref(0);
const isLoading = ref(false);
const detailDialogOpen = ref(false);
const detailCommand = ref({});
const errorDialogOpen = ref(false);

// 指令状态映射
const mapStatus = (status) => {
  const statusMap = {
    'PENDING': '待执行',
    'SUCCESS': '成功',
    'FAILED': '失败',
    'PROCESSING': '处理中',
    'RETRYING': '重试中',
    'CANCELED': '已取消'
  };
  return statusMap[status] || status;
};

// 状态颜色映射
const getStatusColor = (status) => {
  const colorMap = {
    'PENDING': 'warning',
    'SUCCESS': 'success',
    'FAILED': 'danger',
    'PROCESSING': 'primary',
    'RETRYING': 'info',
    'CANCELED': 'info'
  };
  return colorMap[status] || 'info';
};

const mapFeedbackStatus = (status) => {
  return {
    OK: '设备正常响应',
    TIMEOUT: '响应超时',
    ERROR: '响应错误',
  }[status] || status;
};

// 指令类型映射
const mapCmdType = (type) => {
  return {
    SET_PARAM: '参数设置',
    TRIGGER_ALARM: '报警触发',
    START_STOP: '设备启停',
    CALIBRATE: '校准操作',
    RESET: '设备重置',
  }[type] || type;
};

// 状态图标与颜色
const getStatusIcon = (status) => {
  return {
    PENDING: 'el-icon-clock',
    SUCCESS: '',
    FAILED: 'el-icon-error',
  }[status] || 'el-icon-info';
};

const getStatusClass = (status) => {
  return {
    OK: 'status-ok',
    TIMEOUT: 'status-timeout',
    ERROR: 'status-error',
  }[status] || 'status-unknown';
};

// 错误处理建议
const getErrorSuggestion = (errorCode) => {
  return {
    ALARM_MODULE_FAILURE: '检查报警模块连接状态',
    COMMUNICATION_ERROR: '重启通信设备并检查网络',
    TIMEOUT: '增加指令超时时间设置',
    DEFAULT_ERROR: '联系系统管理员',
  }[errorCode] || 'DEFAULT_ERROR';
};

// 获取数据
const getList = async () => {
  isLoading.value = true;
  try {
    const response = await getBuildingEquipmentMonitoringCommandsList(queryParams);
    commandList.value = response.data.list;
    total.value = response.data.total;
  } catch (error) {
    ElMessage.error('获取指令数据失败');
    console.error(error);
  } finally {
    isLoading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  queryParams.pageNum = 1;
  getList();
};

// 重置
const resetSearch = () => {
  queryParams.cmdId = '';
  queryParams.cmdType = '';
  queryParams.status = '';
  queryParams.operatorId = '';
  queryParams.feedbackStatus = '';
  queryParams.pageNum = 1;
  getList();
};

// 分页
const handlePageChange = (newPage) => {
  queryParams.pageNum = newPage;
  getList();
};

const handleSizeChange = (newSize) => {
  queryParams.pageSize = newSize;
  queryParams.pageNum = 1;
  getList();
};

// 行点击事件
const handleRowClick = (row) => {
  detailCommand.value = { ...row };
  detailDialogOpen.value = true;
};

// 显示错误详情
const showErrorDialog = () => {
  errorDialogOpen.value = true;
};

getList();
</script>

<style scoped>
.filter-card {
  margin-bottom: 20px;
  padding: 20px;
}

.data-table {
  min-height: 500px;
}

.el-badge {
  font-size: 14px;
}

.response-card, .execution-card {
  height: 150px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.status-icon {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  margin-bottom: 12px;
}

.status-ok { background-color: #67c23a; }
.status-timeout { background-color: #e6a23c; }
.status-error { background-color: #f56c6c; }

.time-value {
  font-size: 24px;
  font-weight: 500;
  color: #333;
}

.error-title {
  color: #f56c6c;
  margin-top: 16px;
}

.error-code {
  font-size: 14px;
  color: #666;
}

.card-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 8px;
}
</style>
