
<template>
  <div class="app-container">
    <!-- 搜索操作栏 -->
    <div class="search-action-bar">
      <!-- 搜索区域 -->
      <div class="search-area" v-show="showSearch">
        <el-input
          v-model="queryParams.deviceCode"
          placeholder="请输入设备编号"
          clearable
          class="search-input"
          @keyup.enter="handleQuery"
        />
        <el-input
          v-model="queryParams.intersectionId"
          placeholder="请输入路口ID"
          clearable
          class="search-input"
          @keyup.enter="handleQuery"
        />
        <el-button class="search-btn" @click="handleQuery">搜索</el-button>
        <el-button class="reset-btn" @click="resetQuery">重置</el-button>
      </div>
      
      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button
          class="add-btn"
          @click="handleAdd"
          v-hasPermi="['road:trafficLight:add']"
        >新增</el-button>
        <el-button
          class="delete-btn"
          @click="handleExport"
          v-hasPermi="['road:trafficLight:export']"
        >导出</el-button>
      </div>
    </div>

    <!-- 表格数据 -->
    <el-table v-loading="loading" :data="trafficLightList" @selection-change="handleSelectionChange" class="custom-table">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="红绿灯ID" align="center" prop="id" />
      <el-table-column label="设备名称" align="center" prop="deviceName" />
      <el-table-column label="设备编号" align="center" prop="deviceId" />
      <el-table-column label="IP地址" align="center" prop="ipAddress" />
      <el-table-column label="路口ID" align="center" prop="intersectionId" />
      <el-table-column label="是否在线" align="center" prop="isOnline">
        <template #default="scope">
          <el-tag :type="scope.row.isOnline ? 'success' : 'info'">{{ scope.row.isOnline ? '在线' : '离线' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否激活" align="center" prop="isActive">
        <template #default="scope">
          <el-tag :type="scope.row.isActive ? 'success' : 'info'">{{ scope.row.isActive ? '已激活' : '未激活' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createdTime" width="180">
      <template #default="scope">
<span>
  {{
    parseTime(
      new Date(scope.row.createdTime?.replace(/\.\d{3}\d{3}$/, '') ?? ''),
      '{y}-{m}-{d}'
    ) || '-'
  }}
</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['road:trafficLight:edit']">修改</el-button>
          <el-button link type="primary" @click="handleDelete(scope.row)" v-hasPermi="['road:trafficLight:remove']">删除</el-button>
        </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-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="trafficLightRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备名称" prop="deviceName">
          <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="设备编号" prop="deviceId">
          <el-input v-model="form.deviceId" placeholder="请输入设备编号" />
        </el-form-item>
        <el-form-item label="IP地址" prop="ipAddress">
          <el-input v-model="form.ipAddress" placeholder="请输入IP地址" />
        </el-form-item>
        <el-form-item label="路口ID" prop="intersectionId">
          <el-select v-model="form.intersectionId" placeholder="请选择路口" filterable>
            <el-option
              v-for="opt in intersectionOptions"
              :key="opt.value"
              :label="opt.label"
              :value="opt.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否在线" prop="isOnline">
          <el-radio-group v-model="form.isOnline">
            <el-radio :label="true">在线</el-radio>
            <el-radio :label="false">离线</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否激活" prop="isActive">
          <el-radio-group v-model="form.isActive">
            <el-radio :label="true">已激活</el-radio>
            <el-radio :label="false">未激活</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { listTrafficLight, getTrafficLight, delTrafficLight, addTrafficLight, updateTrafficLight } from "@/api/road/trafficLight";
import { listIntersection } from "@/api/road/intersection.js";

const { proxy } = getCurrentInstance();
const { sys_normal_disable } = proxy.useDict("sys_normal_disable");

const trafficLightList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const intersectionOptions = ref([]);

async function loadIntersections() {
  try {
    const res = await listIntersection();
    const list = Array.isArray(res) ? res : Array.isArray(res?.rows) ? res.rows : Array.isArray(res?.data) ? res.data : [];
    intersectionOptions.value = list.map(item => ({ label: item.intersectionName || String(item.intersectionId), value: item.intersectionId }));
  } catch (e) {
    intersectionOptions.value = [];
  }
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deviceId: undefined,
    intersectionId: undefined
  },
  rules: {
    deviceName: [{ required: true, message: "设备名称不能为空", trigger: "blur" }],
    deviceId: [{ required: true, message: "设备编号不能为空", trigger: "blur" }],
    intersectionId: [{ required: true, message: "路口ID不能为空", trigger: "blur" }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询红绿灯列表 */
function getList() {
  loading.value = true;
  listTrafficLight().then(response => {
    console.log('获取红绿灯列表数据:', response);
    if (Array.isArray(response)) {
      trafficLightList.value = response;
      total.value = response.length;
    } else if (response.rows && Array.isArray(response.rows)) {
      trafficLightList.value = response.rows;
      total.value = response.total || response.rows.length;
    } else {
      trafficLightList.value = [];
      total.value = 0;
    }
    loading.value = false;
  }).catch(error => {
    console.error('获取红绿灯列表失败:', error);
    trafficLightList.value = [];
    total.value = 0;
    loading.value = false;
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    id: undefined,
    deviceName: undefined,
    deviceId: undefined,
    ipAddress: undefined,
    intersectionId: undefined,
    isOnline: false,
    isActive: true,
    isEdit: false
  };
  proxy.resetForm("trafficLightRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.deviceId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  form.value.isEdit = false; // 标识为新增操作
  open.value = true;
  title.value = "添加红绿灯";
  if (!intersectionOptions.value.length) loadIntersections();
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  // 检查 row.deviceId 是否存在且不为 undefined
  if (!row || !row.deviceId) {
    proxy.$modal.msgError("请选择一个有效的设备进行修改");
    return;
  }
  const deviceId = row.deviceId; // 确保使用 deviceId 而不是 id
  getTrafficLight(deviceId).then(response => {
    console.log('获取设备详情数据:', response);
    form.value = response;
    form.value.isEdit = true; // 标识为修改操作
    open.value = true;
    title.value = "修改红绿灯";
  }).catch(error => {
    console.error('获取设备详情失败:', error);
    proxy.$modal.msgError("获取设备详情失败，请稍后再试");
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["trafficLightRef"].validate(valid => {
    if (valid) {
      if (form.value.isEdit) {
        // 修改操作，deviceId用于URL路径，请求体中不包含deviceId
        const updateData = {
          deviceName: form.value.deviceName,
          intersectionId: form.value.intersectionId
        };
        // 调用更新接口，deviceId仅用于构建URL，不在请求体中
        updateTrafficLight({ ...updateData, deviceId: form.value.deviceId }).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).catch(error => {
          console.error('修改红绿灯失败:', error);
          proxy.$modal.msgError("修改失败，请稍后再试");
        });
      } else {
        // 新增操作，数据体中包含 deviceId
        const addData = {
          deviceId: form.value.deviceId,
          deviceName: form.value.deviceName,
          intersectionId: form.value.intersectionId
        };
        ensureUniqueDeviceId(form.value.deviceId).then(unique => {
          if (!unique) {
            proxy.$modal.msgError("设备编号已存在");
            return;
          }
          addTrafficLight(addData).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
          }).catch(error => {
            console.error('新增红绿灯失败:', error);
            proxy.$modal.msgError("新增失败，请稍后再试");
          });
        });
      }
    }
  });
}

async function ensureUniqueDeviceId(deviceId) {
  try {
    await getTrafficLight(deviceId);
    return false;
  } catch (e) {
    return true;
  }
}

/** 删除按钮操作 */
function handleDelete(row) {
  const trafficLightIds = row.deviceId || ids.value;
  proxy.$modal.confirm('是否确认删除红绿灯编号为"' + trafficLightIds + '"的数据项？').then(function() {
    return delTrafficLight(trafficLightIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('road/trafficLight/export', {
    ...queryParams.value
  }, `trafficLight_${new Date().getTime()}.xlsx`)
}

getList();
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  background-color: #292c38;
  color: #ffffff;
  height: calc(100vh - 150px);
  overflow-y: auto;
  border-radius: 10px;
}

.search-action-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  .search-area {
    display: flex;
    gap: 10px;
    .search-input {
      width: 250px;
    }
    .search-btn,
    .reset-btn {
      border-radius: 8px;
      font-size: 15px;
      height: 36px;
      min-width: 80px;
    }
    .search-btn {
      background: #347ae2;
      color: #fff;
      border: none;
    }
    .reset-btn {
      background: #343744;
      color: #96a0b5;
      border: none;
    }
  }
  .action-buttons {
    margin-left: auto;
    display: flex;
    gap: 10px;
    .add-btn,
    .delete-btn {
      border-radius: 8px;
      font-size: 15px;
      height: 36px;
      min-width: 80px;
    }
    .add-btn {
      background: #347ae2;
      color: #fff;
      border: none;
    }
    .delete-btn {
      background: #343744;
      color: #96a0b5;
      border: none;
    }
  }
}

.custom-table {
  background-color: #292c38 !important;
  color: #ffffff;
  margin-bottom: 20px;
  border-radius: 4px;
  overflow: hidden;
  :deep(.el-loading-mask) {
    background-color: rgba(41, 44, 56, 0.7) !important;
  }
  :deep(.el-table__empty-block) {
    background-color: #292c38 !important;
  }
  :deep(.el-table__empty-text) {
    color: #96a0b5 !important;
  }
  :deep(.el-table) {
    background-color: #292c38 !important;
  }
  :deep(.el-table__body) {
    background-color: #292c38 !important;
  }
  :deep(.el-table__inner-wrapper::before) {
    display: none;
  }
  :deep(.el-table__header) {
    border-top-left-radius: 4px;
    border-top-right-radius: 4px;
    overflow: hidden;
  }
  :deep(.el-table__header-wrapper) {
    th {
      background-color: #343744 !important;
      color: #96a0b5 !important;
      font-weight: normal;
      border-bottom: none;
    }
    tr th.el-table__cell:first-child {
      border-top-left-radius: 6px;
      .cell {
        border-top-left-radius: 6px;
      }
    }
    tr th.el-table__cell:last-child {
      border-top-right-radius: 4px;
      .cell {
        border-top-right-radius: 4px;
      }
    }
    .el-table__header th.el-table__cell {
      background-color: #343744 !important;
      color: #96a0b5;
    }
    tr {
      background-color: #343744 !important;
    }
  }
  :deep(.el-table__body-wrapper) {
    td {
      height: 68px !important;
      background-color: #292c38;
      color: #ffffff;
      border-bottom: 1px solid #4c4f5f;
    }
  }
  :deep(.el-table__body tr:hover > td) {
    background: #2b3b5a !important;
  }
  :deep(.el-button--link) {
    border: none;
    background: transparent;
    color: #347ae2;
    padding: 0;
    margin: 0 5px;
  }
  :deep(.el-button.is-text) {
    background-color: transparent !important;
    border-color: transparent;
    color: #347ae2;
    &:hover,
    &:focus,
    &:active {
      background-color: transparent !important;
      color: #347ae2;
    }
  }
  :deep(.el-button.el-button--primary.is-text) {
    background-color: transparent !important;
    color: #347ae2;
    &:hover {
      background-color: transparent !important;
      color: #347ae2;
    }
  }
  :deep(.el-table__body tr:hover .el-button--link.is-text) {
    background-color: transparent !important;
    color: #347ae2;
  }
}
</style>
