<?php

namespace app\model;

use think\model\relation\HasMany;
use think\model\relation\HasOne;

/**
 * 扫码日志表
 * Class ScanLog
 * @package app\model
 */
class ScanLog extends Base
{
    public const TYPE_SIGN = 'sign';//签到

    public const ACTION_SCAN_BY_STAFF   = 'scan_by_staff';//员工扫码
    public const ACTION_SCAN_BY_MACHINE = 'scan_by_machine';//扫码器扫码

    /**
     * 检测是否扫码成功
     *
     * @param  int  $accountId
     * @param  string  $nonceStr
     * @return bool
     */
    public static function isScan(int $accountId, string $nonceStr): bool
    {
        $where   = [];
        $where[] = ['account_id', '=', $accountId];
        $where[] = ['nonce_str', '=', $nonceStr];
        $where[] = ['created_at', '>', date('Y-m-d H:i:s', time() - 15 * 60)];

        return self::where($where)->count() > 0;
    }

    /**
     * 记录扫码日志
     *
     * @param  int  $accountId
     * @param  int  $scanUserId
     * @param  string  $nonceStr
     * @param  string  $type
     * @param  string  $action
     * @param  string  $deviceNumber  扫码设备编号 默认无 仅当二维码扫描器操作室可能存在
     * @return ScanLog|\think\Model
     */
    public static function log(int $accountId, int $scanUserId, string $nonceStr, string $type = self::TYPE_SIGN, string $action = self::ACTION_SCAN_BY_STAFF, string $deviceNumber = '')
    {
        $insert = [
            'type'          => $type,
            'action'        => $action,
            'account_id'    => $accountId,
            'staff_id'      => $scanUserId,
            'nonce_str'     => $nonceStr,
            'device_number' => $deviceNumber,
            'created_at'    => date('Y-m-d H:i:s'),
        ];

        if ($action == self::ACTION_SCAN_BY_MACHINE) {
            //机器扫码每天一次
            $count = self::where('type', $type)
                ->where('action', $action)
                ->where('account_id', $accountId)
                ->where('created_at', '>', date('Y-m-d 00:00:00'))
                ->where('created_at', '<', date('Y-m-d 23:59:59'))
                ->count();
            if ($count <= 0) {
                return self::create($insert);
            }
        } else {
            // 非机器扫码 不限制
            return self::create($insert);

        }
    }
}