<?php

namespace Modules\Base\Entities;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;
use SMG\Support\Traits\HasHttpRequest;

class Openid extends Model
{
    use  HasHttpRequest;

    protected $fillable = ['type', 'openid', 'user_id', 'unionid', 'extra'];

    protected $casts = [
        'extra' => 'json',
    ];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function getUserExt()
    {
        if ($this->type == 'wx_mini') {
            $result = $this->extra;
            $data = [];
            $data['sex'] = $result['gender'] ?? 0;
            $data['name'] = $result['nickName'] ?? null;
            $data['avatar'] = isset($result['avatarUrl']) ? $this->downloadAvatar($result['avatarUrl']) : null;

            return $data;
        } elseif ($this->type == 'weixin') {
            $result = $this->extra;
            $data = [];
            $data['sex'] = $result['sex'] ?? 0;
            $data['name'] = $result['nickname'] ?? null;
            $data['avatar'] = isset($result['headimgurl']) ? $this->downloadAvatar($result['headimgurl']) : null;

            return $data;
        }

        return [];
    }

    public function downloadAvatar($avatar_url, $extension = 'png')
    {
        if (!$avatar_url) {
            return null;
        }

        //微信换成大头像
        if (strpos($avatar_url, 'qlogo.cn')) {
            $info = explode('/', $avatar_url);
            $last = count($info) - 1;
            if (in_array($info[$last], ['46', '64', '96', '132'])) {
                $info[$last] = '0';
                $avatar_url = implode('/', $info);
            }
        }

        $content = $this->httpGet($avatar_url);

        if (!$content) {
            return null;
        }

        $folder = config('upload.avatar.folder', 'avatar');
        $folder_name = "{$folder}/".date('Ym', time()).'/'.date('d', time()).'/'.uniqid().'.'.$extension;
        Storage::disk(config('upload.avatar.filesystem'))->put($folder_name, $content);

        return $folder_name;
    }
}
