<?php

namespace App\Services\Client;

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

class CommonService
{
    /**
     * 获取代理商配置
     *
     * @param int $agentId 代理商编号
     * @return array
     * @throws Exception
     */
    public function getAgentConfig($agentId)
    {
        // 检查代理商是否存在
        $agent = AgentInfo::find($agentId);
        if (!$agent) {
            throw new Exception('代理商不存在');
        }

        // 获取代理商配置
        $config = AgentConfig::where('agent_id', $agentId)->first();
        if (!$config) {
            throw new Exception('代理商配置不存在');
        }

        return [
            'agent_id' => $config->agent_id,
            'min_distance' => $config->min_distance, // 最小路程
            'min_fee' => $config->min_fee, // 最小路费金额  
            'per_km_fee' => $config->per_km_fee, // 每公里路程单价
            'commission_rate' => $config->commission_rate, // 佣金比例
            'created_at' => $config->created_at,
            'updated_at' => $config->updated_at
        ];
    }

    /**
     * 获取技师配置
     * 
     * @param int $coachId 技师编号
     * @return array
     * @throws Exception
     */
    public function getCoachConfig($coachId) 
    {
        $config = CoachConfig::where('coach_id', $coachId)->first();
        if (!$config) {
            throw new Exception('技师配置不存在');
        }

        return [
            'coach_id' => $config->coach_id,
            'delivery_fee_enabled' => $config->delivery_fee_enabled, // 是否收取路费
            'delivery_fee_type' => $config->delivery_fee_type, // 路费类型:单程/往返
            'created_at' => $config->created_at,
            'updated_at' => $config->updated_at
        ];
    }

    /**
     * 根据代理商ID计算路费
     */
    public function calculateDeliveryFee($coachId, $agentId, $distance)
    {
        // 获取技师配置
        $coachConfig = $this->getCoachConfig($coachId);
        
        // 如果技师不收取路费
        if (!$coachConfig['delivery_fee_enabled']) {
            return 0;
        }

        // 获取代理商配置
        $agentConfig = $this->getAgentConfig($agentId);
        
        // 计算单程路费
        $onewayFee = $this->calculateOnewayFee($distance, $agentConfig);

        // 根据技师配置返回单程或往返路费
        return $coachConfig['delivery_fee_type'] == 'round_trip' ? $onewayFee * 2 : $onewayFee;
    }

    /**
     * 根据位置计算路费
     */
    public function calculateDeliveryFeeByLocation($coachId, $latitude, $longitude, $distance)
    {
        // 根据经纬度查询代理商
        $agent = AgentInfo::whereRaw("ST_Contains(business_area_polygon, ST_GeomFromText('POINT($longitude $latitude)'))")
            ->first();
            
        if (!$agent) {
            throw new Exception('该区域暂无代理商');
        }

        return $this->calculateDeliveryFee($coachId, $agent->id, $distance);
    }

    /**
     * 计算单程路费
     */
    private function calculateOnewayFee($distance, $agentConfig)
    {
        // 如果路程小于等于最小路程
        if ($distance <= $agentConfig['min_distance']) {
            return $agentConfig['min_fee'];
        }

        // 超出的路程
        $extraDistance = $distance - $agentConfig['min_distance'];
        
        // 计算超出部分的费用
        $extraFee = $extraDistance * $agentConfig['per_km_fee'];
        
        // 返回总费用
        return $agentConfig['min_fee'] + $extraFee;
    }
} 