<?php

namespace App\Http\Controllers\Business;

use App\Exports\BusinessAfterOrderExport;
use App\Exports\BusinessOrderExport;
use App\Exports\OrderBlankExport;
use App\Http\Controllers\Controller;
use App\Models\BusinessAfterSaleOrder;
use App\Models\BusinessOrder;
use App\Models\BusinessOrderItem;
use App\Models\GoodsSku;
use App\Models\Shop;
use App\Services\Ship\WayBillService;
use App\Utils\DateTimeUtils;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Resources\BusinessOrderResource;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class BusinessAfterSaleOrderController extends Controller
{
    public function index(Request $request)
    {
        $shopIds = Shop::query()
            ->where('plat_id', Shop::$PLAT_KTT)
            ->pluck('id');
        $builder = BusinessAfterSaleOrder::query()
            ->with(["shop:id,name"])
            ->whereIn('shop_id', $shopIds)
            ->filter();
        if (!empty($request->created_at_start) & !empty($request->created_at_end)) {
            $builder = $builder->whereBetween("after_sale_created_at"
                , [$request->created_at_start, $request->created_at_end]);
        }

        if ($request->get("is_export")) {
            $params = $request->validate([
                'created_at_start' => 'required',
                'created_at_end' => 'required',
            ], [
                'created_at_start.required' => '请输入开始确认时间',
                'created_at_end.required' => '请输入结束确认时间',
            ]);
            $startDate = Carbon::parse($params['created_at_start']);
            $endDate = Carbon::parse($params['created_at_end']);

            if ($endDate->gt($startDate->copy()->addMonth())) {
                throw new \Exception("导出时间超出一个月");
            }

            return Excel::download(new BusinessAfterOrderExport($builder->get()->toArray())
                , $startDate . '~' . $endDate . "售后订单数据" . '.xlsx');
        }
        $businessOrders = $builder->orderByDesc('after_sale_created_at')
            ->paginate($request->get('per_page'));
        $businessOrders->getCollection()->map(function ($v) {
            $v->refund_amount = bcdiv($v->refund_amount,100,2);
            $v->refund_shipping_amount = bcdiv($v->refund_shipping_amount,100,2);
        });

        return JsonResource::collection($businessOrders);
    }

}
