<?php

namespace App\Models;

use App\Models\Traits\HasAccount;
use App\Models\Traits\HasArea;
use DateTimeInterface;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use RuLong\Identity\Traits\UserHasIdentity;
use Illuminate\Support\Facades\Cache;

class User extends Authenticatable
{

    use Notifiable, HasAccount, UserHasIdentity, HasArea;

    /**
     * The attributes that are mass assignable.
     * @var array
     */
    protected $guarded = [];

    /**
     * The attributes that should be hidden for arrays.
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * @var array
     */
    protected $appends = [
        'nickname',
    ];

    /**
     * 默认加载的关联
     * @var array
     */
    protected $with = ['info', 'identity', 'code'];

    protected static function boot()
    {
        parent::boot();

        self::created(function ($model) {
            if ($model->parent_id) {
                $parent           = self::find($model->parent_id);
                $model->server_id = $parent->server_id;
                $model->outlet_id = date('ymdHi') . mt_rand(100, 999);
                $model->IdentityUpdate(2);
            } else {
                $model->server_id  = date('Ymd') . mt_rand(100000, 999999);
                $model->server_key = Str::random(32);
                $model->des3key    = Str::random(24);
                $model->IdentityUpdate(1);
            }

            $model->info()->create([
                'nickname' => $model->username,
            ]);
            $model->save();
        });
    }

    /**
     * 为数组 / JSON 序列化准备日期。
     * @param  \DateTimeInterface  $date
     * @return string
     */
    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format($this->dateFormat ?: 'Y-m-d H:i:s');
    }

    protected function getNicknameAttribute(): string
    {
        return $this->info ? $this->info->nickname : '';
    }

    public function info(): HasOne
    {
        return $this->hasOne(UserInfo::class);
    }

    //渠道商配置
    public function code(): HasMany
    {
        return $this->hasMany(UserCode::class);
    }

    public function parent()
    {
        return $this->hasOne(User::class, 'id', 'parent_id');
    }

    public function children(): hasMany
    {
        return $this->hasMany(User::class, 'parent_id');
    }

    /**
     * Notes: 密码加密
     * @Author: <C.Jason>
     * @Date  : 2019/9/6 11:37
     * @param $password
     */
    protected function setPasswordAttribute($password)
    {
        if (!empty($password)) {
            $this->attributes['password'] = bcrypt($password);
        }
    }

    public function getTypeTextAttribute()
    {
        switch ($this->type) {
            case 'pingan':
                return '平安券';
                break;
            case 'wo':
                return '沃支付';
                break;
            default:
                return '未知';
                break;
        }
    }

    /**
     * 关联平安卡券核销
     * @author 玄尘 2020-04-03
     * @return \Illuminate\Database\Eloquent\Relations\HasMany [type] [description]
     */
    public function coupons()
    {
        return $this->hasMany(Coupon::class);
    }

    /**
     * Notes: description
     * @Author: 玄尘
     * @Date  : 2021/7/5 17:00
     * @param          $type
     * @param  string  $date
     * @return int
     */
    public function getCouponCount($type, $date = false)
    {
        $data = $this->checkCouponCount($date);

        return $data[$type] ?? 0;

        //        return $this->coupons()
        //                    ->whereIn('status', [2])
        //                    ->where('thirdPartyGoodsId', $type)
        //                    ->when($date, function ($q) {
        //                        $q->whereDate('created_at', now()->format('Y-m-d'));
        //                    })
        //                    ->count();
    }

    /**
     * Notes: 一次性设置用户数据
     * @Author: 玄尘
     * @Date  : 2021/7/5 17:01
     * @param $date
     * @return array|mixed
     */
    public function checkCouponCount($date)
    {
        $date = $date ? 'today' : 'all';

        $name = "user_{$this->id}_coupon_count_date_{$date}";

        if (Cache::has($name)) {
            return Cache::get($name, []);
        } else {
            $res = $this->coupons()
                        ->whereIn('status', [2])
                        ->when($date == 'today', function ($q) {
                            $q->whereDate('created_at', '2020-11-11');
                        })
                        ->select('thirdPartyGoodsId', DB::raw('count(*) as total'))
                        ->groupBy('thirdPartyGoodsId')
                        ->get()
                        ->pluck('total', 'thirdPartyGoodsId')
                        ->toArray();

            Cache::put($name, $res, 10);

            return $res;
        }
    }

}
