<?php

namespace App\Listeners;

use App\Carrier;
use App\City;
use App\Events\WaybillPriceModelEvent;
use App\Waybill;
use App\WaybillFinancialSnapshot;
use App\WaybillPayoff;
use App\WaybillFinancialExcepted;
use App\WaybillPriceModel;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class WaybillPriceModelListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    public function waybillPriceModel_check_waybill(WaybillPriceModel $waybillPriceModel){
        $cityIds=[$waybillPriceModel->city_id];
        //取省下所有市
        if(!$waybillPriceModel->city_id){
            $cities=City::select('id')->where('province_id',$waybillPriceModel['province_id'])->get();
            $cityIds=$cities->map(function ($city){
                return $city['id'];
            });
            //市不存在，价格区间不存在
            if (!$waybillPriceModel->range_max){
                $waybills=Waybill::where('carrier_id',$waybillPriceModel->carrier_id)->whereIn('destination_city_id',$cityIds)
                    ->where('type','专线')->where('status','!=','已完结')->where('carrier_weight_unit_id',$waybillPriceModel->unit_id)
                    ->orWhere('carrier_weight_unit_id_other',$waybillPriceModel->unit_id)->get();
            }
            //市不存在，价格区间存在
            if ($waybillPriceModel->range_max){
                $waybills=Waybill::where('carrier_id',$waybillPriceModel->carrier_id)->whereIn('destination_city_id',$cityIds)
                    ->whereRaw('carrier_weight <= ? AND carrier_weight > ? AND carrier_weight_unit_id = ?',[$waybillPriceModel->range_max,$waybillPriceModel->range_min,$waybillPriceModel->unit_id])
                    ->orWhereRaw('carrier_weight_other <= ? AND carrier_weight_other > ? AND carrier_weight_unit_id_other = ?',[$waybillPriceModel->range_max,$waybillPriceModel->range_min,$waybillPriceModel->unit_id])
                    ->where('type','专线')->where('status','!=','已完结')->get();
            }
        }

        //市存在，价格区间存在
        if ($waybillPriceModel->city_id&&$waybillPriceModel->range_max){
            $waybills=Waybill::where('carrier_id',$waybillPriceModel->carrier_id)->where('destination_city_id',$waybillPriceModel->city_id)
                ->whereRaw('carrier_weight <= ? AND carrier_weight > ? AND carrier_weight_unit_id = ?',[$waybillPriceModel->range_max,$waybillPriceModel->range_min,$waybillPriceModel->unit_id])
                ->orWhereRaw('carrier_weight_other <= ? AND carrier_weight_other > ? AND carrier_weight_unit_id_other = ?',[$waybillPriceModel->range_max,$waybillPriceModel->range_min,$waybillPriceModel->unit_id])
                ->where('type','专线')->where('status','!=','完结')->get();
        }

        //市存在，价格区间不存在
        if ($waybillPriceModel->city_id&&!$waybillPriceModel->range_max){
            $waybills=Waybill::where('carrier_id',$waybillPriceModel->carrier_id)->where('destination_city_id',$waybillPriceModel->city_id)
                ->where('type','专线')->where('status','!=','完结')->where('carrier_weight_unit_id',$waybillPriceModel->unit_id)
                ->orWhere('carrier_weight_unit_id_other',$waybillPriceModel->unit_id)->get();
        }
        return $waybills;
    }

    /**
     * Handle the event.
     *
     * @param  WaybillPriceModelEvent  $event
     * @return void
     */
    public function handle(WaybillPriceModelEvent $event)
    {
        $waybillPriceModel=$event->waybillPriceModel;
        $waybills=$this->waybillPriceModel_check_waybill($waybillPriceModel);
        if ($waybills){
            foreach ($waybills as $waybill){
                //修改运单表运费
                $carrier=Carrier::find($waybill->carrier_id);
                if ($waybill->carrier_weight<$waybillPriceModel->initial_weight){
                    $fee=(($waybillPriceModel->unit_price)*($waybillPriceModel->initial_weight))+$carrier->delivery_fee;
                }else{
                    $fee=(($waybillPriceModel->unit_price)*$waybill->carrier_weight)+$carrier->delivery_fee;
                }
                $waybill->fee=$fee;
                $waybill->save();
                $total_receivable=($waybill->charge);
                $total_expense=($waybill->pick_up_fee)+($waybill->other_fee)+($waybill->fee);

                //修改财务表信息
                if ($total_receivable){
                    $waybillPayoff=WaybillPayoff::where('waybill_id','=',$waybill->id)->first();
                    if ($waybillPayoff){
                        $waybillPayoff->total_expense=$total_expense;
                        $waybillPayoff->total_receivable=$total_receivable;
                        $waybillPayoff->gross_margin=$total_receivable-$total_expense;
                        $waybillPayoff->gross_profit_rate=(($total_receivable-$total_expense)/$total_receivable);
                        $waybillPayoff->save();
                    }else{
                        WaybillPayoff::create([
                            'waybill_id'=>$waybill->id,
                            'total_expense'=>$total_expense,
                            'total_receivable'=>$total_receivable,
                            'gross_margin'=>$total_receivable-$total_expense,
                            'gross_profit_rate'=>(($total_receivable-$total_expense)/$total_receivable),
                        ]);
                    };
                    $waybillFinancialExcepted=WaybillFinancialExcepted::where('waybill_id',$waybill->id)->first();
                    if ($waybillFinancialExcepted){
                        $waybillFinancialExcepted->delete();
                        $waybill->status='完结';
                        $waybillPayoff=WaybillPayoff::where('waybill_id','=',$waybillFinancialExcepted->waybill_id)->first();
                        $waybillPayoff->load(["waybill"]);
                        $waybillPayoff->waybill->load(["owner","carrier","origination_city","destination_city","warehouse_weight_unit","carrier_weight_unit","carType","waybillAuditLogs"]);
                        $waybillPayoff->waybill->waybillAuditLogs->load(["user"]);
                        $waybillPayoffJson=json_encode($waybillPayoff,JSON_UNESCAPED_UNICODE);
                        WaybillFinancialSnapshot::create([
                            'waybill_id'=>$waybillFinancialExcepted->waybill_id,
                            'json_content'=>$waybillPayoffJson,
                        ]);
                    }
                }
                if ($waybill->waybill_price_model_id!=$waybillPriceModel->id){
                    $waybill->waybill_price_model_id=$waybillPriceModel->id;
                }
                $waybill->save();
            }
        }
    }
}
