<?php

namespace Modules\User\Models\Traits;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Support\Arr;
use Modules\User\Models\Sign;
use Modules\User\Models\SignConfig;
use Modules\User\Models\SignLog;

trait HasSign
{
    /**
     * 用户签到
     *
     * @return HasOne
     */
    public function sign(): HasOne
    {
        return $this->hasOne(Sign::class);
    }

    /**
     * Notes   : 当前日期是否签到
     *
     * @Date   : 2022/1/6 13:25
     * @Author : Mr.wang
     * @param  string  $date
     * @return bool
     */
    public function isSign($date = null): bool
    {
        $date = $date ?? Carbon::now()->format('Y-m-d');
        return $this->signLogs()->whereDate('date', $date)->exists();
    }

    /**
     * Notes   : 用户签到日志
     *
     * @Date   : 2022/1/6 13:23
     * @Author : Mr.wang
     * @return HasMany
     */
    public function signLogs(): HasMany
    {
        return $this->hasMany(SignLog::class);
    }

    /**
     * Notes: 获取签到数据
     *
     * @Author: 玄尘
     * @Date: 2022/8/3 15:35
     */
    public function getSignData(): array
    {
        $all  = Arr::get(SignConfig::getParams(), 'cycle_day', 0);
        $data = [
            'continue' => 0,
            'total'    => 0,
            'all'      => $all
        ];
        if ($this->sign) {
            $data = [
                'continue' => $this->sign->continue_days,
                'total'    => $this->sign->counts,
                'all'      => $all,
            ];
        }
        $data = array_merge($data, [
            'text' => '第'.$data['continue'].'/'.$data['all'].'天'
        ]);
        return $data;
    }
}