where(['store_id' => $storeId])->delete(); if (empty($fenceData) || !is_array($fenceData)) { return true; // 空数据表示清空围栏 } $insertData = []; $currentTime = time(); foreach ($fenceData as $index => $fence) { // 处理fence_data字段 - 可能是JSON字符串或points数组 $fenceDataJson = ''; if (isset($fence['fence_data']) && !empty($fence['fence_data'])) { // 如果fence_data是字符串,直接使用 if (is_string($fence['fence_data'])) { $fenceDataJson = $fence['fence_data']; } else { // 如果是数组,转换为JSON $fenceDataJson = json_encode($fence['fence_data'], JSON_UNESCAPED_UNICODE); } } elseif (isset($fence['points']) && !empty($fence['points'])) { // 兼容旧的points字段 $fenceDataJson = json_encode($fence['points'], JSON_UNESCAPED_UNICODE); } $insertData[] = [ 'store_id' => $storeId, 'merchant_id' => $merchantId, 'fence_name' => isset($fence['fence_name']) ? $fence['fence_name'] : (isset($fence['name']) ? $fence['name'] : "配送区域" . ($index + 1)), 'fence_data' => $fenceDataJson, 'fence_type' => isset($fence['fence_type']) ? $fence['fence_type'] : 1, // 多边形 'is_active' => isset($fence['is_active']) ? $fence['is_active'] : 1, 'create_time' => $currentTime, 'update_time' => $currentTime ]; } return $this->addAll($insertData); } /** * 获取门店围栏数据 * @param int $storeId 门店ID * @return array */ public function getFenceData($storeId) { $fences = $this->where(['store_id' => $storeId])->select(); if (empty($fences)) { return []; } $result = []; foreach ($fences as $fence) { $result[] = [ 'id' => $fence['id'], // 添加真实ID字段 'fence_name' => $fence['fence_name'], 'fence_type' => $fence['fence_type'], 'is_active' => (int)$fence['is_active'], 'fence_data' => json_decode($fence['fence_data'], true), // 保持JSON字符串格式,不进行解码 'tempId' => 'fence_' . $fence['id'] // 添加临时ID用于前端识别 ]; } return $result; } /** * 删除门店围栏数据 * @param int $storeId 门店ID * @return bool */ public function deleteFenceData($storeId) { return $this->where(['store_id' => $storeId])->delete(); } }