<?php

namespace App\Models;

/**
 * App\Models\BuyInviteModel
 *
 * @property int $id
 * @property int $invite_id 邀请id
 * @property int $invite_uid 被邀请用户
 * @property \Illuminate\Support\Carbon $created_at 时间
 * @property int $state 邀请状态【0有效助力|1因被邀请者限制成无效助力|2因助力id完成成无效助力】
 * @property int $dis_score 折扣金额
 * @property string|null $comment 留言
 * @property \Illuminate\Support\Carbon|null $updated_at 更新时间
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\BuyInviteModel newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\BuyInviteModel newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\BuyInviteModel query()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\BuyInviteModel whereComment($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\BuyInviteModel whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\BuyInviteModel whereDisScore($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\BuyInviteModel whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\BuyInviteModel whereInviteId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\BuyInviteModel whereInviteUid($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\BuyInviteModel whereState($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\BuyInviteModel whereUpdatedAt($value)
 * @mixin \Eloquent
 */
class BuyInviteModel extends Model
{
    protected $table = "kdgx_partner_charge_buy_invite";

    protected $dateFormat = 'U';

    public $fillable = ['id', 'invite_id', 'invite_uid', 'state', 'comment', 'dis_score'];

    /**
     * 获取折扣百分比
     * @param  int $uid 发起用户uid
     * @param  int $partner_id 折扣卡片id
     * @return int
     */
    public function effectiveInvite(int $uid, int $partner_id)
    {
        $recod = new RecodeModel();
        if (
            $recod->where([
            ['partner_id', $partner_id],
            ['uid', $uid]
            ])->exists()
        ) {
            return 100;
        }
        $listModel = new BuyInviteListModel();
        $list = $listModel->where([
            ['uid', $uid],
            ['partner_id', $partner_id]
        ])->first();
        if (collect($list)->isEmpty()) {
            return 0;
        } else {
            $cnt = $this->where([
                ['invite_id', $list->id],
                ['state', 0]
            ])->sum('dis_score');
            return $cnt;
        }
    }
}
