<?php

namespace Modules\User\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;
use Jason\Api\Api;
use Modules\Mall\Models\Order;
use Modules\Mall\Models\Refund as RefundModel;
use Modules\User\Http\Resources\Account\UserAccountResource;
use Modules\User\Models\Identity;
use Vinkla\Hashids\Facades\Hashids;

class UserInfoResource extends JsonResource
{

    public function toArray($request): array
    {
        $identity = $this->identityFirst();
        if ($identity->id > 2) {
            $order = true;
        } else {
            $order = false;
        }

        return [
            'user_id'      => $this->id,
            'username'     => $this->username,
            'nickname'     => $this->info->nickname ?? '',
            'avatar'       => $this->info->avatar ?? '',
            'account'      => new UserAccountResource($this->account),
            'identity'     => new UserIdentityBaseResource($identity),
            'service'      => new  UserServiceResource($identity->identities()->first()),
            'water_mobile' => app('Conf_mall')['water_mobile'] ?? '',
            'invite'       => Hashids::connection('code')->encode($this->id),
            'case'         => $this->getStockData(),
            'user_wechat'  => new UserWechatResource($this->wechat),
            'created_at'   => (string) $this->created_at,
            'sign'         => $this->getSignData(),
            'status'       => $this->getStateData(),
            'canPick'      => $this->canPick(),
            'count'        => [
                'relation'      => $this->getRelationCount(),//下级
                'notifications' => $this->unreadNotifications()->count(),//消息数量
                'orders'        => Order::byUser(Api::user())->common()->count(),//订单数量
                'refunds'       => RefundModel::byUser(Api::user())->count(),//退款单数量
            ],
            'identityShow' => $this->when(true, function () use ($identity) {
                return [
                    'right'  => new UserIdentityRightsResource($identity),
                    'times'  => new IdentityMiddleResource($this->identityMiddle()->first()),
                    'is_top' => $identity->id == 4,
                ];
            }),
        ];
    }

}
