<?php

namespace App\Models\User;

use App\Exceptions\AlertException;
use Illuminate\Database\Eloquent\Builder;
use App\Http\Controllers\Wechat\Fans;
use Illuminate\Database\Eloquent\Model;

/**
 * Class Openid
 *
 * @package App\Models\User
 * @method static Builder ofPublic(int $to_uid, string $public_id = "gh_b598cb7474d8")
 * @property int $id 主键
 * @property int $uid 用户ID
 * @property string $public_id 公众号原始ID
 * @property string $openid 用户的标识，对当前公众号唯一
 * @property int $subscribe 是否订阅该公众号
 * @property string $nickname 用户的昵称
 * @property int $sex 用户的性别
 * @property string $city 用户所在城市
 * @property string $country 用户所在国家
 * @property string $province 用户所在省份
 * @property string $language 用户的语言
 * @property string $headimgurl 用户头像
 * @property string $remark 公众号运营者对粉丝的备注
 * @property int $groupid 用户所在的分组ID
 * @property string $tagid_list 用户被打上的标签ID列表
 * @property string|null $unionid 微信开放平台帐号
 * @property int $subscribe_time 用户关注时间
 * @property int $interaction_time 用户最后交互时间
 * @property int $logintime 最近登录时间
 * @property string $subscribe_scene 用户关注的渠道来源
 * @property string $qr_scene 二维码扫码场景
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\Openid newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\Openid newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\Openid query()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\Openid whereCity($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\Openid whereCountry($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\Openid whereGroupid($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\Openid whereHeadimgurl($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\Openid whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\Openid whereInteractionTime($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\Openid whereLanguage($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\Openid whereLogintime($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\Openid whereNickname($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\Openid whereOpenid($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\Openid whereProvince($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\Openid wherePublicId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\Openid whereQrScene($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\Openid whereRemark($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\Openid whereSex($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\Openid whereSubscribe($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\Openid whereSubscribeScene($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\Openid whereSubscribeTime($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\Openid whereTagidList($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\Openid whereUid($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\Openid whereUnionid($value)
 * @mixin \Eloquent
 */
class Openid extends Model
{


    protected $table = 'kddx_user_openid';

    public $timestamps = false;

    protected $fillable = ['uid', 'openid', 'public_id', 'subscribe'];

    /**
     * 获取用户uid
     * @param  string  $openid
     * @return array
     * @throws AlertException
     */
    public function getUidByopenid(string $openid)
    {
        $openinfo = $this->where('openid', $openid)->firstOrFail();
        $auth = AuthKey::where('auth_key', $openinfo->unionid)->firstOrFail();
        return array(
            'uid' => $auth->uid,
            'openid' => $openid,
            'public_id' => $openinfo->public_id,
            'interaction_time' => time()
        );
    }

    /**
     * 获取用户openid
     * @param  int  $uid  用户id
     * @return array
     * @throws AlertException
     */
    public function getOpenidByuid($uid)
    {
        $public_id = config('wechat.fpdx.public_id');
        /** @var self|null $openidEloqument */
        $openidEloqument = $this->where([['uid', $uid], ['public_id', $public_id]])->first();
        if (collect($openidEloqument)->isEmpty() || empty($openidEloqument->openid)) {
            $auth = AuthKey::where([['uid', $uid], ['auth_type', "kdgx_unionid"]])->first();
            if (collect($auth)->isEmpty()) {
                throw new AlertException("该用户已被注销", 401);
            }
            $openidEloqument = $this->where([['unionid', $auth->auth_key], ['public_id', $public_id]])->first();
            if (collect($openidEloqument)->isEmpty()) {
                throw new AlertException("用户未绑定微信号", 404);
            } else {
                $openidEloqument->uid = $uid;
                $openidEloqument->save();
            }
        } else {
            return [
                'uid' => $openidEloqument->uid,
                'openid' => $openidEloqument->openid,
                'public_id' => $openidEloqument->public_id,
                'interaction_time' => $openidEloqument->interaction_time
            ];
        }
    }

    /**
     * 绑定用户
     * @param  string  $public_id
     * @param  int  $uid
     * @param  string  $openid
     */
    public function bindUser(string $public_id, $uid, string $openid)
    {
        $where['openid'] = $openid;
        $save = [
            'openid' => $openid,
            'uid' => $uid,
            'public_id' => $public_id,
            'subscribe' => 1
        ];
        $openidEloqument = $this->where($where)->get();
        if ($openidEloqument->isEmpty() || empty($openidEloqument->uid)) {
            $this->updateOrCreate($where, $save);
        }
    }

    /**
     * 筛选某公众号的用户信息
     * @param $query
     * @param $uid
     * @param  string  $public_id
     * @return mixed
     */
    public function scopeOfPublic(/** @var Builder $query */ $query, $uid, $public_id = 'gh_b598cb7474d8')
    {
        return $query->where(['uid' => $uid, 'public_id' => $public_id]);
    }

    /**
     * 判断是否关注公众号
     * @param  int  $uid
     * @param  string  $public_id
     * @return bool
     */
    public static function isSubscribe(int $uid, string $public_id): bool
    {
        try {
            $auth = AuthKey::where(array(['uid', $uid], ['auth_type', 'kdgx_unionid']))->firstOrFail();
            if (self::where([['unionid', $auth->auth_key], ['public_id', $public_id], ['subscribe', 1]])->exists()) {
                return true;
            }
            return false;
        } catch (\Exception $exception) {
            return false;
        }
    }
}
