<?php

namespace App\Model;

use App\Exceptions\DatabaseException;
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
use MongoDB\BSON\UTCDateTime;

class DownloadRecord extends Eloquent
{
    protected $collection = "download_record";

    protected $connection = 'mongodb';  //使用mongodb

    protected $primaryKey = '_id';

    /**
     * @param $keyId
     * @param $data
     * @return mixed
     * @throws DatabaseException
     */
    public static function addRecord($keyId,$data){

        try{
            $record = self::getRecord($keyId);


            if (empty($record)){
                $create_time = new UTCDateTime(time() * 1000);;
                $data = [
                    'key_id'          => $keyId,
                    'content'      => json_encode($data),
                    'create_time'   => $create_time,
                ];

                $id = DownloadRecord::insertGetId($data);

            }else{
                $id = $record['id'];
            }

        }catch (\Exception $exception){
            throw new DatabaseException($exception->getMessage());
        }
        return $id;

    }

    /**
     * @param $keyId
     * @return mixed
     * @throws DatabaseException
     */
    public static function getRecord($keyId){

        try{
            $record = DownloadRecord::where("key_id",$keyId)->first();
        }catch (\Exception $exception){
            throw new DatabaseException($exception->getMessage());
        }
        return $record;
    }

    /**
     * 删除记录
     * @param $keyId
     * @return mixed
     * @throws DatabaseException
     */
    public static function delRecord($keyId){
        try{
            $flag = DownloadRecord::where("key_id",$keyId)->delete();
        }catch (\Exception $exception){
            throw new DatabaseException($exception->getMessage());
        }
        return $flag;
    }

}
