<?php

namespace app\model;

/**
 * 打卡日志
 *
 * Class ClockLog
 * @package app\model
 */
class ClockLog extends Base
{
    public const TYPE_NORMAL = 'normal';//普通打卡 适用于普通用户打卡 不区分上下班 场地 位置等等

    public const TYPE_MORNING_ON  = 'morning_on';//上午上班
    public const TYPE_MORNING_OFF = 'morning_off';//上午下班

    public const TYPE_AFTERNOON_ON  = 'afternoon_on';//下午上班
    public const TYPE_AFTERNOON_OFF = 'afternoon_off';//下午下班

    public const STATUS_TODO = 0;//待审核
    public const STATUS_YES  = 1;//通过
    public const STATUS_NO   = -1;//不通过

    public function account()
    {
        return $this->hasOne(Account::class, 'id', 'account_id');
    }

    public static function typeText(): array
    {
        return [
            self::TYPE_MORNING_ON    => '上午上班',
            self::TYPE_MORNING_OFF   => '上午下班',
            self::TYPE_AFTERNOON_ON  => '下午上班',
            self::TYPE_AFTERNOON_OFF => '下午下班',
        ];
    }

    public static function statusText(): array
    {
        return [
            self::STATUS_TODO => '待审核',
            self::STATUS_YES  => '审核通过',
            self::STATUS_NO   => '审核拒绝',
        ];
    }

    /**
     * 检查打卡频率
     * 目前针对普通用户
     *
     * @param  int  $accountId 用户ID
     * @param  string  $type 打卡类型
     * @param  int  $worksiteId 工地ID 默认0
     * @param  int  $seconds 时间限制,秒  即多少秒内只能打一次  默认60
     * @return bool true=单位时间有打卡 false=单位时间未打卡
     * @throws \think\db\exception\DbException
     */
    public static function checkRate(int $accountId, string $type = self::TYPE_MORNING_ON, int $worksiteId = 0, int $seconds = 60): bool
    {
        return self::where('account_id', $accountId)
                ->where('type', $type)
                ->where('worksite_id', $worksiteId)
                ->where('create_time', '>', time() - $seconds)
                ->count() > 0;
    }

    /**
     * 检查当天是否已打卡
     * 目前针对工人和负责人
     *
     * @param  int  $accountId 用户ID
     * @param  string  $type 打卡类型
     * @param  int  $worksiteId 工地ID 默认0
     * @return bool
     * @throws \think\db\exception\DbException
     */
    public static function hasSign(int $accountId, string $type, int $worksiteId): bool
    {
        return self::where('account_id', $accountId)
                ->where('type', $type)
                ->where('worksite_id', $worksiteId)
                ->where('status', '<>', -1)
                ->where('create_time', '>=', strtotime(date('Y-m-d')))
                ->where('create_time', '<=', strtotime(date('Y-m-d 23:59:59')))
                ->count() > 0;
    }
}