<?php

namespace App\Modules\Admin\Services;

use App\Base\BaseService;
use App\Base\Utils;
use App\Models\Goods\GoodsCustom;
use App\Models\Order\Order;
use App\Models\Order\OrderGoods;
use App\Models\User\User;
use Illuminate\Database\Eloquent\Builder;

class OrderService extends BaseService
{
    public function paginate($params)
    {
        $p = Order::when($params['id'], function (Builder $query) use ($params) {
            $query->where("id", $params['id']);
        })->when($params['userinfo'], function (Builder $query) use ($params) {
            //根据userinfo获取用户信息
            if ($user = User::where("email", $params['userinfo'])->orWhere("phone", $params['userinfo'])->orWhere("id", $params['userinfo'])->first()) {
                $query->where("user_id", $user->id);
            } else {
                $query->where("id", 0);
            }
        })->orderByDesc("id")->paginate($params['page_size']);

        return [
            "total" => $p->total(),
            "page_total" => $p->lastPage(),
            "list" => array_map(function (Order $model) {
                /** @var OrderGoods $firstGoods */
                $firstGoods = $model->goods->first();
                return [
                    "id" => $model->id,
                    "no" => $model->goods->pluck("sn")->implode("\sn"),
                    "goods_name" => $firstGoods->goods->name,
                    "goods_sn" => $firstGoods->sn,
                    "user_id" => Utils::idNo4($model->user_id),
                    "thumb" => $firstGoods->goods->thumb,
                    "email" => $model->user->email,
                    "created_at" => $model->created_at->format("Y-m-d H:i:s"),
                    "goods" => $model->goods->map(function (OrderGoods $goods) {
                        return [
                            "goods_id" => $goods->id,
                            "goods_name" => $goods->goods->name,
                            "goods_thumb" => $goods->goods->thumb,
                            "goods_sn" => $goods->sn,
                            "goods_count" => $goods->count,
                            "custom" => array_map(function ($custom) {
                                $custom = GoodsCustom::where("id", $custom['custom_id'])->first();
                                return [
                                    "custom_id" => $custom['custom_id'],
                                    "title" => $custom->title,
                                    "en_title" => $custom->en_title,
                                    "value" => $custom['value'] ?? "",
                                ];
                            }, $goods->custom ?? []),
                        ];
                    }),
                    "phone" => $model->user->phone,
                    "name" => $model->user->name,
                    "source" => $model->source,
                ];
            }, $p->items()),
        ];
    }
}