<?php

namespace App\Jobs;

use App\Feature;
use App\Order;
use App\OwnerFeeDetail;
use App\OwnerFeeDetailLogistic;
use App\Process;
use App\Province;
use App\Services\CacheService;
use App\Services\OwnerPriceDirectLogisticService;
use App\Services\OwnerPriceExpressService;
use App\Services\OwnerPriceLogisticService;
use App\Services\OwnerPriceOperationService;
use App\Store;
use App\Waybill;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Cache;

class ResetInstantBill implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /** @var \stdClass $detail  */
    private $detail;
    /**
     * Create a new job instance.
     *
     * @param OwnerFeeDetail $detail
     *
     * @return void
     */
    public function __construct(OwnerFeeDetail $detail)
    {
        $this->detail = $detail;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        switch ($this->detail->outer_table_name){
            case "orders":
                /** @var \stdClass $order */
                //检查订单对象
                $order = Order::query()->find($this->detail->outer_id);
                if (!$order || $order->wms_status != "订单完成")break;
                $order->loadMissing(["logistic","shop","packages.commodities.commodity","batch"]);
                /** @var OwnerPriceExpressService $service */
                $service = app("OwnerPriceExpressService");
                $logistic_fee = 0;
                $amount = 0;
                $volume = 0;
                $weight = 0;
                $logistic_bill = "";

                if (!$order->logistic || $order->logistic->type == "物流")$logistic_fee = null;

                $items = [];
                $isBunched = $order->logistic && $order->logistic->is_bunched=='Y';
                $weightExceptionMark = false;
                $provinceId = null;
                $logisticTaxFee = 0;
                foreach ($order->packages as &$package){
                    $tax = 0;

                    $logistic_bill .= $package->logistic_number.",";
                    $volume += $package->bulk;
                    $weight += $package->weight;
                    if (!$weightExceptionMark && (!$package->weight || $package->weight<0))$weightExceptionMark = true;
                    $partAmount = 0;
                    foreach($package->commodities as $commodity){
                        $partAmount += $commodity->amount;
                    }
                    $amount += $partAmount;

                    $provinceName = mb_substr($order->province,0,2);
                    $province = app(CacheService::class)->getOrExecute("province_".$provinceName,function ()use($provinceName){
                        return Province::query()->where("name","like",$provinceName."%")->first();
                    },86400);
                    $fee = null;
                    if ($province){
                        if (!$provinceId)$provinceId = $province->id;
                        else if ($provinceId!=$province->id)$weightExceptionMark = true;
                        if (!$isBunched)list($fee,$tax) = $service->matching($package->weight, $order->owner_id, $order->logistic_id, $province->id);
                    }else $logistic_fee = null;

                    $items[] = [
                        "amount" => $partAmount,
                        "logistic_bill" => $package->logistic_number,
                        "volume"=>$package->bulk,
                        "weight"=>$package->weight,
                        "logistic_fee" => $fee,
                        "tax_fee" => $tax,
                    ];
                    if ($logistic_fee!==null){
                        if (!$fee || $fee<0)$logistic_fee = null;
                        else $logistic_fee += $fee;
                    }
                    $logisticTaxFee += $tax;
                }
                /* 为字母单 且 重量与省份完整 且 重量大于0 且 省份存在 进入子母单计算 */
                if ($isBunched && !$weightExceptionMark && $weight>0 && $provinceId)list($logistic_fee,$logisticTaxFee) = $service->matching($weight, $order->owner_id, $order->logistic_id, $provinceId);
                if ($logistic_fee!==null && $logistic_fee<0)$logistic_fee = null;
                /** @var OwnerPriceOperationService $service */
                $service = app("OwnerPriceOperationService");
                list($id,$money,$workTaxFee) = $service->matching($order,Feature::MAPPING["order"],$order->owner_id,"出库");

                $this->detail->update([
                    "owner_id"          => $order->owner_id,
                    "worked_at"         => $order->wms_edittime ?? $order->updated_at,
                    "shop_id"           => $order->shop_id,
                    "operation_bill"    => $order->code,
                    "consignee_name"    => $order->consignee_name,
                    "consignee_phone"   => $order->consignee_phone,
                    "commodity_amount"  => $amount,
                    "logistic_bill"     => rtrim($logistic_bill,","),
                    "volume"            => $volume,
                    "weight"            => $weight,
                    "logistic_id"       => $order->logistic_id,
                    "work_fee"          => $money,
                    "owner_price_operation_id"  => $id,
                    "logistic_fee"      => $logistic_fee,
                    "work_tax_fee"      => $workTaxFee,
                    "logistic_tax_fee"  => $logistic_fee ? $logisticTaxFee : null,
                ]);
                OwnerFeeDetailLogistic::query()->where("owner_fee_detail_id",$this->detail->id)->delete();
                foreach ($items as &$item)$item["owner_fee_detail_id"] = $this->detail->id;
                if (count($items)>1)OwnerFeeDetailLogistic::query()->insert($items);
                app("OrderService")->setOrderQuantity($order->owner_id,$order->logistic_id);
                break;
            case "processes":
                /** @var \stdClass $process */
                $process = Process::query()->with("processStatistic")->find($this->detail->outer_id);
                $this->detail->update([
                    "work_fee"  => $process->processStatistic ? $process->processStatistic->revenue : null,
                ]);
                break;
            case "waybills":
                /** @var \stdClass $waybill */
                $waybill = Waybill::query()->find($this->detail->outer_id);
                $waybill->loadMissing(["destinationCity","order.owner"]);
                if (!$waybill->destinationCity && !$waybill->order)break;

                $owner_id = $waybill->order->owner_id ?? $waybill->owner_id;
                $detail = OwnerFeeDetail::query()->where("type","发货")
                    ->where("owner_id",$owner_id)->whereIn("operation_bill",[$waybill->wms_bill_number,$waybill->waybill_number])->first();

                if ($detail && $detail->logistic_fee !== null)break;

                if ($waybill->type == "专线"){
                    /** @var OwnerPriceLogisticService $service */
                    $service = app("OwnerPriceLogisticService");
                    list($fee,$taxFee) = $service->matching($waybill->carrier_weight_other,$owner_id,$waybill->logistic_id,
                        $waybill->carrier_weight_unit_id_other,$waybill->order ? app("RegionService")->getProvince($waybill->order->province) : $waybill->destinationCity->province_id,
                        $waybill->destination_city_id);
                }else{
                    /** @var OwnerPriceDirectLogisticService $service */
                    $service = app("OwnerPriceDirectLogisticService");
                    list($fee,$taxFee) = $service->matching($waybill->mileage,$owner_id,$waybill->carType_id);
                }
                $this->detail->update([
                    "logistic_fee" => $fee,
                    "logistic_tax_fee" => $taxFee,
                ]);
                break;
            case "stores":
                /** @var \stdClass $store */
                $store = Store::query()->find($this->detail->outer_id);
                if (!$store || $store->status != "已入库") break;
                $store->loadMissing(["storeItems.commodity","warehouse"]);

                /** @var OwnerPriceOperationService $service */
                $service = app("OwnerPriceOperationService");
                list($id,$money,$taxFee) = $service->matching($store, Feature::MAPPING["store"], $store->owner_id, "入库");
                $this->detail->update([
                    "owner_id" => $store->owner_id,
                    "worked_at" => $store->updated_at,
                    "operation_bill" => $store->asn_code,
                    "commodity_amount" => array_sum(array_column($store->storeItems->toArray(), "amount")),
                    "work_fee" => $money,
                    "owner_price_operation_id" => $id,
                    "work_tax_fee" => $taxFee
                ]);
                break;
        }
    }
}
