<?php

namespace App\Http\Controllers\Business;

use App\Events\BusinessOrderCancelEvent;
use App\Events\CancelLogisticEvent;
use App\Exports\BusinessOrderExport;
use App\Exports\OrderBlankExport;
use App\Http\Controllers\Controller;
use App\Models\BusinessOrder;
use App\Models\BusinessOrderItem;
use App\Models\GoodsSku;
use App\Models\Shop;
use App\Models\Waybill;
use App\Services\Business\BusinessFactory;
use App\Services\WayBill\JingDong\JingDongService;
use App\Services\WayBill\JingDong\WayBillService;
use App\Utils\DateTimeUtils;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Resources\BusinessOrderResource;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;

class WaybillController extends Controller
{
    public function queryTrace(Request $request)
    {
        $params = $request->validate([
            'order_id' => 'required',
        ], [
            'order_id.required' => '订单id',
        ]);
        $waybill = Waybill::query()->where("order_id", $params['order_id'])->firstOrFail();
        $jingDongService = new JingDongService();
        return $jingDongService->queryTrace($waybill);
    }

    public function cancel(Request $request)
    {
        $params = $request->validate([
            'order_id' => 'required',
        ], [
            'order_id.required' => '订单id',
        ]);
        $waybill = Waybill::query()->where("order_id", $params['order_id'])->firstOrFail();
        if (empty($waybill->waybill_code)) {
            throw new \Exception("无快递单号可取消");
        }
        try{
            //取消快团团物流
            $shop = Shop::query()->findOrFail($waybill->shop_id);
            $client = BusinessFactory::init()->make($shop['plat_id'])->setShop($shop);
            $client->cancelLogistic($waybill->order_sn, $waybill->waybill_code);
            //取消京东物流
            $jingDongService = new JingDongService();
            $jingDongService->cancelOrder($waybill);
        }catch(\Exception $exception) {
            Log::error("取消快团团或者京东物流异常", ["error" => $exception->getMessage()]);
        }


        $waybill->waybill_code = '';
        $waybill->encryptedData = '';
        $waybill->status = Waybill::$STATUS_INIT;
        $waybill->cancel = 1;
        $waybill->save();
        BusinessOrder::query()->where("id", $params['order_id'])->update(['print_status' => 0]);

        return response(['message' => 'success']);
    }

}
