<?php

namespace App\Services\Client;

use App\Models\AgentInfo;
use App\Models\AgentConfig;
use App\Models\Project;
use Exception;

class AgentService
{
    /**
     * 获取代理商配置
     */
    public function getAgentConfig($agentId)
    {
        // 检查代理商是否存在
        $agent = AgentInfo::where('id', $agentId)
            ->where('state', 'enable')
            ->firstOrFail();

        // 获取代理商配置
        $config = AgentConfig::where('agent_id', $agentId)->firstOrFail();

        return [
            'min_distance' => $config->min_distance,
            'min_fee' => $config->min_fee,
            'per_km_fee' => $config->per_km_fee
        ];
    }

    /**
     * 获取代理商
     */
    public function getAgent($areaCode)
    {
        // 根据区域编码查询代理商
        $agent = AgentInfo::where('business_area', 'like', "%{$areaCode}%")
            ->where('state', 'enable')
            ->first();

        if (!$agent) {
            // 如果找不到,按照市、省、全国逐级查找
            $areaCodeParts = str_split($areaCode, 2);
            foreach ($areaCodeParts as $index => $part) {
                $searchCode = implode('', array_slice($areaCodeParts, 0, $index + 1));
                $agent = AgentInfo::where('business_area', 'like', "%{$searchCode}%")
                    ->where('state', 'enable')
                    ->first();
                if ($agent) {
                    break;
                }
            }
        }

        return $agent;
    }

    /**
     * 获取代理商项目列表
     */
    public function getProjectList($categoryId, $agentId)
    {
        // 查询代理商
        $agent = AgentInfo::where('id', $agentId)
            ->where('state', 'enable')
            ->firstOrFail();

        // 查询项目列表
        $query = Project::where('state', 'enable');

        if ($categoryId) {
            $query->where('category_id', $categoryId);
        }

        $projects = $query->whereHas('agents', function($q) use ($agentId) {
                $q->where('agent_id', $agentId);
            })
            ->with(['category:id,name'])
            ->orderBy('sort', 'desc')
            ->paginate(10);

        return $projects;
    }

    /**
     * 获取代理商项目详情
     */
    public function getProjectDetail($projectId, $agentId)
    {
        // 查询代理商
        $agent = AgentInfo::where('id', $agentId)
            ->where('state', 'enable')
            ->firstOrFail();

        // 查询项目
        $project = Project::where('id', $projectId)
            ->where('state', 'enable')
            ->whereHas('agents', function($q) use ($agentId) {
                $q->where('agent_id', $agentId);
            })
            ->with([
                'category:id,name',
                'agents' => function($q) use ($agentId) {
                    $q->where('agent_id', $agentId);
                }
            ])
            ->firstOrFail();

        return $project;
    }
} 