<?php

namespace App\Models\User;

use App\Events\UpdatedUserInfo;
use App\Models\BlackListModel;
use App\Models\NoticeModel;
use App\Models\Model;
use App\Models\PartnerModel;
use App\Models\RiskListModel;
use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\Storage;
use Ixudra\Curl\Facades\Curl;

/**
 * App\Models\User\UserModel
 *
 * @property int $uid 用户ID
 * @property int $sex 性别
 * @property int $sxo 性取向
 * @property int $feed_sex 首页性别
 * @property string|null $headimgurl 头像
 * @property string|null $nickname 用户昵称
 * @property float $gold_flower 金fa数量
 * @property float $red_flower 红fa数量
 * @property int $ck_count 抽卡次数
 * @property string|null $task 任务[表白|上传语音|上架自己|卖室友|设置个人信息]0:未完成;1完成
 * @property int $height 身高
 * @property string|null $age 年-月-日
 * @property string $home 故乡：省-市
 * @property string $address 长居城市
 * @property int $partner_id partner卡片id
 * @property string|null $expect 期望
 * @property string|null $introduce 自我描述
 * @property string|null $phone 手机号
 * @property string $school 学校
 * @property string $subject 专业
 * @property string $limit 限制失效时间-次数
 * @property int $last_sign 上次签到时间（客户端调用）
 * @property \Illuminate\Support\Carbon $updated_at 更新时间
 * @property \Illuminate\Support\Carbon $created_at 创建时间
 * @property int $sign_con 连续签到次数
 * @property int $hiding 屏蔽
 * @property string $star 星座
 * @property string $tag_1 标签一
 * @property string $tag_2 标签二
 * @property string $tag_3 标签三
 * @property string $tag_4 标签四
 * @property int $subscribe_at 关注获取fa
 * @property string $fpdx_like 个人偏好
 * @property string $kf_account 分配对象客服
 * @property int $rollback 后悔滑动的机会
 * @property string $qq QQ
 * @property string $weixin 微信
 * @property string $education 学历
 * @property int $login_at 登录时间(接口级)
 * @property string|null $voice 语音地址
 * @property int $pair_min_age 匹配比我小的年龄
 * @property int $pair_max_age 匹配比我大的年龄
 * @property int $pair_province 允许同省调剂
 * @property int $pair_all 允许全国调剂
 * @property string|null $photo_src 主页图片
 * @property string|null $photo_1 相册1
 * @property string|null $photo_2 相册2
 * @property string|null $photo_3 相册3
 * @property string|null $photo_4 相册4
 * @property string|null $last_life 最近生活状态
 * @property string|null $why 为什么参加活动
 * @property string|null $pair_voice 匹配语音
 * @property int $jigsaw_amount 拼图数量
 * @property string|null $wxkf 微信客服
 * @property string|null $sign 签名
 * @property int $is_auto_expand 是否自动扩大
 * @property int $only_last 是否只看活跃的
 * @property float $lng 经度
 * @property float $lat 纬度
 * @property string $location 地理位置
 * @property int $feed_dis 首页筛选距离
 * @property string|null $identity_auth 通过身份认证的照片
 * @property int $wx_auth 是否通过微信认证
 * @property string $work_state 工作状态
 * @property string|null $claim_tag 需求标签
 * @property int $last_likeme_lock_at 上次喜欢我的解锁时间
 * @property int $be_vip_at 成为vip的时间
 * @property int $supvip_endat 超级会员到期时间
 * @property int $task_photo 爆照任务[-1不设置为任务|0不设置为任务(默认)|设置为任务]
 * @property int $task_question 心动考验任务[-1不设置为任务|0不设置为任务(默认)|设置为任务]
 * @property int|null $task_sing 心动接唱任务[-1不设置为任务|0不设置为任务(默认)|设置为任务]
 * @property array|null $task_question_data 心动考验问题[{问题:{问题形式,问题},模版id}]
 * @property int $logoff_at 注销时间
 * @property int $app_like_unlock_count app心动解锁次数
 * @property string|null $login_app_platform app登录平台
 * @property int|null $feed_cnt 滑动总次数
 * @property int|null $feed_like 滑动点赞数
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel query()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereAddress($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereAge($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereAppLikeUnlockCount($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereBeVipAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereCkCount($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereClaimTag($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereEducation($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereExpect($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereFeedCnt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereFeedDis($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereFeedLike($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereFeedSex($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereFpdxLike($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereGoldFlower($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereHeadimgurl($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereHeight($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereHiding($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereHome($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereIdentityAuth($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereIntroduce($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereIsAutoExpand($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereJigsawAmount($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereKfAccount($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereLastLife($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereLastLikemeLockAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereLastSign($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereLat($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereLimit($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereLng($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereLocation($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereLoginAppPlatform($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereLoginAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereLogoffAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereNickname($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereOnlyLast($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel wherePairAll($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel wherePairMaxAge($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel wherePairMinAge($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel wherePairProvince($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel wherePairVoice($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel wherePartnerId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel wherePhone($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel wherePhoto1($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel wherePhoto2($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel wherePhoto3($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel wherePhoto4($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel wherePhotoSrc($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereQq($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereRedFlower($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereRollback($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereSchool($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereSex($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereSign($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereSignCon($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereStar($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereSubject($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereSubscribeAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereSupvipEndat($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereSxo($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereTag1($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereTag2($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereTag3($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereTag4($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereTask($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereTaskPhoto($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereTaskQuestion($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereTaskQuestionData($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereTaskSing($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereUid($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereUpdatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereVoice($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereWeixin($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereWhy($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereWorkState($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereWxAuth($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User\UserModel whereWxkf($value)
 */
class UserModel extends Model
{
    protected $table = 'kdgx_partner_charge_user';

    protected $dateFormat = 'U';

    protected $primaryKey = 'uid';

    protected $fillable = [
        'uid',
        'gold_flower',
        'red_flower',
        'headimgurl',
        'nickname',
        'sex',
        'sxo',
        'height',
        'age',
        'star',
        'home',
        'education',
        'address',
        'qq',
        'weixin',
        'partner_id',
        'task_photo',
        'task_question',
        'task_sing',
        'expect',
        'introduce',
        'phone',
        'school',
        'subject',
        'created_at',
        'login_at',
        'supvip_endat',
        'sign_con',
        'tag_1',
        'tag_2',
        'tag_3',
        'tag_4',
        'fpdx_like',
        'last_life',
        'why',
        'kf_account',
        'voice',
        'pair_min_age',
        'pair_max_age',
        'pair_province',
        'pair_all',
        'pair_voice',
        'photo_src',
        'photo_1',
        'photo_2',
        'photo_3',
        'photo_4',
        'jigsaw_amount',
        'wxkf',
        'sign',
        'feed_sex',
        'is_auto_expand',
        'feed_dis',
        'only_last',
        'lat',
        'lng',
        'location',
        'identity_auth',
        'wx_auth',
        'work_state',
        'claim_tag',
        'last_likeme_lock_at',
        'be_vip_at',
        'login_app_platform',
        'feed_cnt',
        'feed_like',
        'bgcolor',
        'im_account',
        'im_sig',
        'pair_energy',
    ];

    protected $appends = [
        'full_url_photo_src',
        'full_url_photo',
        'full_url_photo1',
        'full_url_photo2',
        'full_url_photo3',
        'full_url_photo4',
        'avatar',
        'birthday',
        'is_super_vip',
    ];


    protected $casts = [
        'task_question_data' => 'array',
        'task_sing_data' => 'array',
        'updated_at' => 'int',
        'be_vip_at' => 'int',
        'supvip_endat' => 'int'
    ];


    public static function boot()
    {
        parent::boot();
        self::saving(function (/** @var UserModel $model */ $model) {
            // 头像上传oss
            if (
                'local' != config('app.env') && !empty($model->headimgurl) && 0 == substr_count(
                    $model->headimgurl,
                    "oss.pocketuniversity.cn"
                )
            ) {
                $response = Curl::to($model->headimgurl)->withResponseHeaders()->returnResponseObject()->get();
                $new_avatar = sprintf("avatar/%s/%s.png", date('Y-m-d'), \Ramsey\Uuid\Uuid::uuid4()->toString());
                Storage::disk('oss')->put($new_avatar, $response->content);
                $avatar = Storage::disk('oss')->url($new_avatar);
                $model->headimgurl = $avatar;
            }

            // 黑名单处理
            if (
                (
                    $model->isDirty('weixin') &&
                    BlackListModel::where('account_type', 'weixin')
                        ->where('account', $model->weixin)
                        ->first()
                ) ||
                (
                    $model->isDirty('qq') &&
                    BlackListModel::where('account_type', 'qq')
                        ->where('account', $model->qq)
                        ->first()
                )
            ) {
                RiskListModel::create([
                    'uid' => $model->uid,
                    'phone' => $model->phone,
                    'weixin' => $model->weixin,
                    'qq' => $model->qq,
                ]);
                BlackListModel::updateOrcreate(
                    ['account_type' => 'uid', 'account' => $model->uid],
                    ['type' => 'all', 'end_at' => 1893427200, 'state' => 3]
                );
                BlackListModel::updateOrcreate(
                    ['account_type' => 'phone', 'account' => $model->phone],
                    ['type' => 'all', 'end_at' => 1893427200, 'state' => 3]
                );
            }

            // 更新登录时间
            if ($model->isDirty('login_at') && $model->partner_id > 0) {
                try {
                    PartnerModel::findOrFail($model->partner_id)->update(['login_at' => $model->login_at]);
                } catch (ModelNotFoundException $exception) {
                }
            }
        });

        self::updated(function (/** @var UserModel $model */ $model) {
            event(new UpdatedUserInfo($model));
        });
    }


    /**
     * 初始化fpdx用户
     * @param  int  $uid
     * @return UserModel|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model
     */
    public function initUser(int $uid)
    {
        $isnew = false;

        try {
            $user = $this->findOrFail($uid);
            if (0 == $user->login_at) {
                $isnew = true;
            }
        } catch (Exception $e) {
            $user = $this->fill(['uid' => $uid, 'phone' => null]);
            $user->save();
            $isnew = true;
        }

        if ($isnew) {
            NoticeModel::create([
                'uid' => $uid,
                'title' => '欢迎来到分配对象',
                'content' => "hi，你好呀，终于等到你了~今后就让小象带你认识有趣的人，遇见属于你的心动！快先来完善你的交友信息吧，小象等不及要给你“分配对象”啦~",
                'type' => 5,
                'type_id' => 0,
                'tab_content' => '编辑个人资料',
                'tab_url' => '/pages/my-friend-card-editor/my-friend-card-editor',
            ]);
        }

        return $user;
    }


    public function getAuth()
    {
        $apps = [
            '1109365561' => '1109365561',       //分配对象QQ小程序
            '1109284509' => '1109284509',       //时遇记QQ小程序
            'gh_b598cb7474d8' => 'wx7955aab955345d39',//分配对象公众号
            'gh_c94c95866ca5' => 'wxa80cac3f6c2de130',//时遇记公众号
            'gh_01c089b58dda' => 'wx4c1722a4055bd229',//分配对象小程序,
            'qq_unionid' => 'qq_unionid',
            'kdgx_unionid' => 'unionid',
            'phone' => 'phone',
        ];


        $unionid = AuthKey::where('uid', $this->uid)->where('auth_type', 'kdgx_unionid')->value('auth_key');
        $qq_unionid = AuthKey::where('uid', $this->uid)->where('auth_type', 'qq_unionid')->value('auth_key');

        $data = [
            'uid' => $this->uid,
            'sex' => $this->sex,
            'device' => $this->login_app_platform,
            'phone' => AuthKey::where('uid', $this->uid)
                ->where('auth_type', 'phone')
                ->value('auth_key'),
            'unionid' => $unionid,
            'qq_unionid' => $qq_unionid,
            'wxa80cac3f6c2de130' => $unionid ? Openid::where('unionid', $unionid)
                ->where('public_id', 'gh_c94c95866ca5')
                ->value('openid') : '',
            'wx7955aab955345d39' => $unionid ? Openid::where('unionid', $unionid)
                ->where('public_id', 'gh_b598cb7474d8')
                ->value('openid') : '',
            'wx4c1722a4055bd229' => AuthKey::where('uid', $this->uid)
                ->where('auth_type', 'gh_01c089b58dda')
                ->value('auth_key') ?: '',
            '1109365561' => AuthKey::where('uid', $this->uid)
                ->where('auth_type', '1109365561')
                ->value('auth_key') ?: '',
            '1109284509' => AuthKey::where('uid', $this->uid)
                ->where('auth_type', '1109284509')
                ->value('auth_key') ?: '',
        ];
        return $data;
    }


    public function black()
    {
        $black = [
            'msy' => BlackListModel::select(['created_at', 'end_at', 'state'])
                ->where('account_type', 'uid')
                ->where('account', $this->uid)
                ->where('end_at', '>', time())
                ->whereIn('type', ['all', 'msy'])
                ->orderBy('end_at', 'desc')
                ->first(),

            'fpdx' => BlackListModel::select(['created_at', 'end_at', 'state'])
                ->where('account_type', 'uid')
                ->where('account', $this->uid)
                ->where('end_at', '>', time())
                ->whereIn('type', ['all', 'fpdx'])
                ->orderBy('end_at', 'desc')
                ->first(),

            'black' => BlackListModel::select(['created_at', 'end_at', 'state'])
                ->where('account_type', 'uid')
                ->where('account', $this->uid)
                ->where('end_at', '>', time())
                ->whereIn('type', ['all', 'black'])
                ->orderBy('end_at', 'desc')
                ->first(),

            'chat' => BlackListModel::select(['created_at', 'end_at', 'state'])
                ->where('account_type', 'uid')
                ->where('account', $this->uid)
                ->where('end_at', '>', time())
                ->whereIn('type', ['all', 'chat'])
                ->orderBy('end_at', 'desc')
                ->first(),

            'night' => BlackListModel::select(['created_at', 'end_at', 'state'])
                ->where('account_type', 'uid')
                ->where('account', $this->uid)
                ->where('end_at', '>', time())
                ->whereIn('type', ['all', 'night'])
                ->orderBy('end_at', 'desc')
                ->first(),

            'home' => BlackListModel::select(['created_at', 'end_at', 'state'])
                ->where('account_type', 'uid')
                ->where('account', $this->uid)
                ->where('end_at', '>', time())
                ->whereIn('type', ['all', 'home'])
                ->orderBy('end_at', 'desc')
                ->first(),

            'account' => BlackListModel::select(['created_at', 'end_at', 'state'])
                ->where('account_type', 'uid')
                ->where('account', $this->uid)
                ->where('end_at', '>', time())
                ->whereIn('type', ['all', 'account'])
                ->orderBy('end_at', 'desc')
                ->first(),
        ];
        return $black;
    }


    public function getNicknameAttribute($value)
    {
        return $value
            ? mb_substr($value, 0, 10)
            : '';
    }


    public function getHeadimgurlAttribute($value)
    {
        return $value ?: '';
    }

    public function getAvatarAttribute()
    {
        return $this->headimgurl ?: '';
    }

    public function getBirthdayAttribute()
    {
        return $this->age ?: null;
    }

    public function getFullUrlPhotoAttribute()
    {
        $url = $this->photo_src;
        if (!$url || str_contains($url, 'http')) {
            return $url;
        }

        return "https://oss.pocketuniversity.cn{$url}";
    }

    public function getFullUrlPhotoSrcAttribute()
    {
        $url = $this->photo_src;
        if (!$url || str_contains($url, 'http')) {
            return $url;
        }

        return "https://oss.pocketuniversity.cn{$url}";
    }

    public function getFullUrlPhoto1Attribute()
    {
        $url = $this->photo_1;
        if (!$url || str_contains($url, 'http')) {
            return $url;
        }

        return "https://oss.pocketuniversity.cn{$url}";
    }

    public function getFullUrlPhoto2Attribute()
    {
        $url = $this->photo_2;
        if (!$url || str_contains($url, 'http')) {
            return $url;
        }

        return "https://oss.pocketuniversity.cn{$url}";
    }

    public function getFullUrlPhoto3Attribute()
    {
        $url = $this->photo_3;
        if (!$url || str_contains($url, 'http')) {
            return $url;
        }

        return "https://oss.pocketuniversity.cn{$url}";
    }

    public function getFullUrlPhoto4Attribute()
    {
        $url = $this->photo_4;
        if (!$url || str_contains($url, 'http')) {
            return $url;
        }

        return "https://oss.pocketuniversity.cn{$url}";
    }

    public function getIsSuperVipAttribute()
    {
        return $this->supvip_endat > time();
    }

}
