<template>
  <div class="app-container">
    <!-- 搜索操作栏 -->
    <div class="search-action-bar">
      <!-- 搜索区域 -->
      <div class="search-area" v-show="showSearch">
        <el-input
          v-model="queryParams.intersectionName"
          placeholder="请输入路口名称"
          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:intersection:add']"
        >新增</el-button>
        <el-button
          class="delete-btn"
          @click="handleExport"
          v-hasPermi="['road:intersection:export']"
        >导出</el-button>
      </div>
    </div>

    <!-- 表格数据 -->
    <div class="table-container">
      <el-table v-loading="loading" :data="intersectionList" @selection-change="handleSelectionChange" class="custom-table">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="路口ID" align="center" prop="intersectionId" />
        <el-table-column label="路口名称" align="center" prop="intersectionName" />
        <!-- <el-table-column label="路口编号" align="center" prop="intersectionId" /> -->
        <el-table-column label="经度" align="center" prop="longitude" />
        <el-table-column label="纬度" align="center" prop="latitude" />
        <el-table-column label="区域编码" align="center" prop="areaCode" />
        <el-table-column label="描述" align="center" prop="description" />
        <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="createTime" width="180">
          <template #default="scope">
            <span>
              {{ parseTime(new Date(scope.row.createTime), '{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:intersection:edit']">修改</el-button>
            <el-button link type="primary" @click="handleDetail(scope.row)" v-hasPermi="['road:intersection:detail']">详情</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"
      />
    </div>

    <!-- 添加或修改路口对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="intersectionRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="路口名称" prop="intersectionName">
          <el-input v-model="form.intersectionName" placeholder="请输入路口名称" />
        </el-form-item>
        <el-form-item label="路口ID" prop="intersectionId">
          <el-input v-model="form.intersectionId" placeholder="请输入路口ID" />
        </el-form-item>
        <el-form-item label="经度" prop="longitude">
          <el-input v-model="form.longitude" placeholder="请输入经度" />
        </el-form-item>
        <el-form-item label="纬度" prop="latitude">
          <el-input v-model="form.latitude" placeholder="请输入纬度" />
        </el-form-item>
        <el-form-item label="区域编码" prop="areaCode">
          <el-input v-model="form.areaCode" placeholder="请输入区域编码" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入描述" type="textarea" />
        </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>

    <!-- 路口详情弹窗 -->
    <el-dialog title="路口详情" v-model="detailVisible" width="500px" append-to-body>
      <div class="detail-content">
        <div class="detail-item">
          <span class="detail-label">路口ID：</span>
          <span class="detail-value">{{ detailData.intersectionId }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">路口名称：</span>
          <span class="detail-value">{{ detailData.intersectionName }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">经度：</span>
          <span class="detail-value">{{ detailData.longitude }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">纬度：</span>
          <span class="detail-value">{{ detailData.latitude }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">区域编码：</span>
          <span class="detail-value">{{ detailData.areaCode }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">描述：</span>
          <span class="detail-value">{{ detailData.description }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">状态：</span>
          <span class="detail-value">
            <el-tag :type="detailData.isActive ? 'success' : 'info'">
              {{ detailData.isActive ? '已激活' : '未激活' }}
            </el-tag>
          </span>
        </div>
        <div class="detail-item">
          <span class="detail-label">创建时间：</span>
          <span class="detail-value">{{ detailData.createdTime }}</span>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailVisible = false" type="primary">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { listIntersection, getIntersection, addIntersection, updateIntersection,getIntersectionname} from "@/api/road/intersection";
import { useRouter } from "vue-router";

const { proxy } = getCurrentInstance();
const router = useRouter();

const intersectionList = 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 detailVisible = ref(false);
const detailData = ref({});

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    intersectionName: undefined,
    intersectionId: undefined
  },
  rules: {
    intersectionName: [{ required: true, message: "路口名称不能为空", trigger: "blur" }],
    intersectionId: [{ required: true, message: "路口ID不能为空", trigger: "blur" }],
    longitude: [{ required: true, message: "经度不能为空", trigger: "blur" }],
    latitude: [{ required: true, message: "纬度不能为空", trigger: "blur" }]
  }
});

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

/** 查询路口列表 */
function getList() {
  loading.value = true;
  // 检查 queryParams 中的 intersectionName 参数
  if (queryParams.value.intersectionName && queryParams.value.intersectionName.trim() !== '') {
    // 如果 intersectionName 参数存在且不为空，调用 getIntersectionname 方法进行模糊查询
    getIntersectionname({ name: queryParams.value.intersectionName }).then(response => {
      // 打印 response 以检查其结构
      console.log('获取路口列表数据（模糊查询）:', response);
      if (response && Array.isArray(response)) {
        // 确保 response 是数组
        intersectionList.value = response;
        // 映射数据字段
        console.log('获取路口数据（模糊查询）:', intersectionList.value);
        intersectionList.value = intersectionList.value.map(item => ({
          intersectionId: item.intersectionId,
          intersectionName: item.intersectionName,
          latitude: item.latitude,
          longitude: item.longitude,
          areaCode: item.areaCode || '', // 如果没有areaCode字段，则设置为空字符串
          description: item.description || '', // 如果没有description字段，则设置为空字符串
          isActive: item.isActive, // 直接使用isActive布尔值
          createTime: item.createdTime
        }));
      } else {
        // 如果 response 不是数组或为空，设置为空数组
        intersectionList.value = [];
      }
      // 确保 response.total 是数字
      // total.value = typeof response.total === 'number' ? response.total : 0;
      total.value = response.length;
      console.log('路口列表total:', total.value);
      loading.value = false;
    }).catch(error => {
      console.error('获取路口列表失败（模糊查询）:', error);
      // 如果请求失败，将 total 设置为 0
      total.value = 0;
      loading.value = false;
    });
  } else {
    // 如果 intersectionName 参数为空，调用原有的 listIntersection 方法获取所有路口列表
    listIntersection().then(response => {
      // 打印完整的 response 对象
      console.log('完整响应数据（全部）:', response);
      if (response && Array.isArray(response)) {
        // 确保 response 是数组
        intersectionList.value = response;
        // 映射数据字段
        console.log('获取路口数据（全部）:', intersectionList.value);
        intersectionList.value = intersectionList.value.map(item => ({
          intersectionId: item.intersectionId,
          intersectionName: item.intersectionName,
          latitude: item.latitude,
          longitude: item.longitude,
          areaCode: item.areaCode || '', // 如果没有areaCode字段，则设置为空字符串
          description: item.description || '', // 如果没有description字段，则设置为空字符串
          isActive: item.isActive, // 直接使用isActive布尔值，与模糊查询保持一致
          createTime: item.createdTime
        }));
      } else {
        // 如果 response 不是数组或为空，设置为空数组
        intersectionList.value = [];
      }
      // 确保 response.total 是数字
      // total.value = typeof response.total === 'number' ? response.total : 0;
      total.value = intersectionList.value.length;
      console.log('路口列表total:', total.value);
      loading.value = false;
    }).catch(error => {
      console.error('获取路口列表失败（全部）:', error);
      // 如果请求失败，将 total 设置为 0
      total.value = 0;
      loading.value = false;
    });
  }
}

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

/** 表单重置 */
function reset() {
  form.value = {
    isEdit: false, // 添加标识，用于区分新增和修改
    intersectionId: undefined,
    intersectionName: undefined,
    longitude: undefined,
    latitude: undefined,
    areaCode: undefined,
    description: undefined,
    isActive: true
  };
  proxy.resetForm("intersectionRef");
}

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

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

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

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加路口";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.intersectionId || ids.value[0];
  getIntersection(id).then(response => {
    const data = response.data || response;
    // 将获取到的数据映射到表单字段
    form.value = {
      intersectionId: data.intersectionId,
      intersectionName: data.intersectionName,
      longitude: data.longitude,
      latitude: data.latitude,
      areaCode: data.areaCode,
      description: data.description,
      isActive: data.isActive // 直接使用isActive布尔值
    };
    // 添加标识，用于区分新增和修改
    form.value.isEdit = true;
    open.value = true;
    title.value = "修改路口";
  });
}

/** 详情按钮操作 */
function handleDetail(row) {
  const id = row.intersectionId;
  // 获取路口详情数据并显示弹窗
  getIntersection(id).then(response => {
    detailData.value = response.data || response;
    detailVisible.value = true;
  }).catch(error => {
    console.error('获取路口详情失败:', error);
    proxy.$modal.msgError('获取路口详情失败');
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["intersectionRef"].validate(valid => {
    if (valid) {
      // 准备提交数据
      const submitData = {
        // 不在请求体中包含intersectionId，它已经在URL路径中传递了
        intersectionName: form.value.intersectionName,
        longitude: form.value.longitude,
        latitude: form.value.latitude,
        areaCode: form.value.areaCode,
        description: form.value.description,
        isActive: form.value.isActive // 直接使用isActive布尔值
      };
      
      // 通过isEdit标识判断是新增还是修改
      if (form.value.isEdit) {
        // 修改路口
        updateIntersection(form.value.intersectionId, submitData).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).catch(error => {
          console.error("修改路口失败:", error);
          proxy.$modal.msgError("修改失败，" + (error.message || '路口编号可能已存在'));
        });
      } else {
        // 新增路口时需要包含intersectionId
        const addData = {
          intersectionId: form.value.intersectionId,
          intersectionName: form.value.intersectionName,
          longitude: form.value.longitude,
          latitude: form.value.latitude,
          areaCode: form.value.areaCode,
          description: form.value.description,
          isActive: form.value.isActive // 直接使用isActive布尔值
        };
        
        // 新增路口
        addIntersection(addData).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).catch(error => {
          console.error("新增路口失败:", error);
          proxy.$modal.msgError("新增失败，" + (error.message || '路口编号可能已存在'));
        });
      }
    }
  });
}


/** 导出按钮操作 */
function handleExport() {
  proxy.download('road/intersection/export', {
    ...queryParams.value
  }, `intersection_${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;
  display: flex;
  flex-direction: column;
}

.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;
    }
  }
}

.table-container {
  flex: 1;
  overflow-y: auto;
  // margin-bottom: 40px;
}

.custom-table {
  background-color: #292c38 !important;
  color: #ffffff;
  border-radius: 4px;
  overflow: visible;
  :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;
  }

  // 弹窗样式（修改弹窗和详情弹窗统一样式）
  :deep(.el-dialog) {
    background-color: #292c38;
    border: 1px solid #4c4f5f;
    border-radius: 8px;
    
    .el-dialog__header {
      background-color: #343744;
      border-bottom: 1px solid #4c4f5f;
      border-radius: 8px 8px 0 0;
      padding: 15px 20px;
      
      .el-dialog__title {
        color: #ffffff;
        font-size: 16px;
        font-weight: 500;
      }
      
      .el-dialog__headerbtn {
        .el-dialog__close {
          color: #96a0b5;
          &:hover {
            color: #ffffff;
          }
        }
      }
    }
    
    .el-dialog__body {
      background-color: #292c38;
      color: #ffffff;
      padding: 20px;
      
      // 表单样式
      .el-form {
        .el-form-item {
          .el-form-item__label {
            color: #96a0b5;
            font-weight: 500;
          }
          
          .el-input {
            .el-input__wrapper {
              background-color: #343744;
              border: 1px solid #4c4f5f;
              border-radius: 6px;
              
              .el-input__inner {
                background-color: transparent;
                color: #ffffff;
                
                &::placeholder {
                  color: #6b7280;
                }
              }
              
              &:hover {
                border-color: #5a5f70;
              }
              
              &.is-focus {
                border-color: #347ae2;
              }
            }
          }
          
          .el-textarea {
            .el-textarea__inner {
              background-color: #343744;
              border: 1px solid #4c4f5f;
              border-radius: 6px;
              color: #ffffff;
              
              &::placeholder {
                color: #6b7280;
              }
              
              &:hover {
                border-color: #5a5f70;
              }
              
              &:focus {
                border-color: #347ae2;
              }
            }
          }
          
          .el-radio-group {
            .el-radio {
              .el-radio__label {
                color: #ffffff;
              }
              
              .el-radio__input {
                .el-radio__inner {
                  background-color: #343744;
                  border-color: #4c4f5f;
                  
                  &:hover {
                    border-color: #347ae2;
                  }
                }
                
                &.is-checked {
                  .el-radio__inner {
                    background-color: #347ae2;
                    border-color: #347ae2;
                  }
                }
              }
            }
          }
        }
      }
      
      // 详情内容样式
      .detail-content {
        background-color: transparent;
        
        .detail-item {
          display: flex;
          align-items: center;
          padding: 12px 0;
          border-bottom: 1px solid #4c4f5f;
          
          &:last-child {
            border-bottom: none;
          }
          
          .detail-label {
            color: #96a0b5;
            font-weight: 500;
            min-width: 100px;
            flex-shrink: 0;
          }
          
          .detail-value {
            color: #ffffff;
            flex: 1;
            
            .el-tag {
              background-color: transparent;
              border: 1px solid;
              
              &.el-tag--success {
                color: #67c23a;
                border-color: #67c23a;
                background-color: rgba(103, 194, 58, 0.1);
              }
              
              &.el-tag--info {
                color: #909399;
                border-color: #909399;
                background-color: rgba(144, 147, 153, 0.1);
              }
            }
          }
        }
      }
    }
    
    .el-dialog__footer {
      background-color: #292c38;
      border-top: 1px solid #4c4f5f;
      padding: 15px 20px;
      border-radius: 0 0 8px 8px;
      
      .el-button {
        border-radius: 6px;
        height: 36px;
        min-width: 80px;
        
        &.el-button--primary {
          background-color: #347ae2;
          border-color: #347ae2;
          color: #ffffff;
          
          &:hover {
            background-color: #2563eb;
            border-color: #2563eb;
          }
        }
        
        &.el-button--default {
          background-color: #4c4f5f;
          border-color: #4c4f5f;
          color: #ffffff;
          
          &:hover {
            background-color: #5a5f70;
            border-color: #5a5f70;
          }
        }
      }
    }
  }
}
</style>