<?php

namespace App\Models\Partner;

use App\Exceptions\AlertException;
use App\Models\Model;

/**
 * App\Models\Partner\ThumbActionModel
 *
 * @property int $id
 * @property \Illuminate\Support\Carbon $created_at 创建时间
 * @property \Illuminate\Support\Carbon $updated_at 更新时间
 * @property int $uid 用户
 * @property int $partner_id 卡片id
 * @property int $thumb 点赞
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Partner\ThumbActionModel newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Partner\ThumbActionModel newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Partner\ThumbActionModel query()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Partner\ThumbActionModel whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Partner\ThumbActionModel whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Partner\ThumbActionModel wherePartnerId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Partner\ThumbActionModel whereThumb($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Partner\ThumbActionModel whereUid($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Partner\ThumbActionModel whereUpdatedAt($value)
 * @mixin \Eloquent
 */
class ThumbActionModel extends Model
{
    protected $table = "kdgx_fpdx_thumb_action";

    protected $dateFormat = "U";

    protected $fillable = ['uid', 'partner_id', 'thumb'];

    /**
     * 点赞或取消
     * @param  int  $uid
     * @param  int  $partner_id
     * @param  int  $thumb
     * @return bool
     * @throws AlertException
     */
    public static function createdOrDeleted(int $uid, int $partner_id, int $thumb)
    {
        if ($thumb == 0) {
            ThumbActionModel::where([['uid', $uid], ['partner_id', $partner_id]])->delete();
            return true;
        }
        if (100 < ThumbActionModel::where('uid', $uid)->count()) {
            throw new AlertException("存储上限", 201);
        }
        ThumbActionModel::firstOrCreate([
            'uid' => $uid,
            'partner_id' => $partner_id
        ], [
            'uid' => $uid,
            'partner_id' => $partner_id
        ]);
        return true;
    }
}
