<?php

namespace Modules\User\Traits;

use Carbon\Carbon;
use Modules\User\Models\UserWechatSubscribe;
use Modules\User\Models\UserWechat;
use Modules\User\Models\UserWechatOfficial;

trait WechatTrait
{

    /**
     * Notes: 通过code获取用户信息
     *
     * @Author: 玄尘
     * @Date  : 2021/9/28 10:36
     * @return mixed|string
     * @throws \Exception
     */
    public function getUserFromCode()
    {
        try {
            $code = request()->code;
            if (! $code) {
                throw new \Exception('缺少code');
            }
            $weChat = app('wechat.official_account');

            $weUser = $weChat->oauth->userFromCode(request()->code);

            return $weUser;
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }

    }

    /**
     * Notes: 获取用户信息
     *
     * @Author: 玄尘
     * @Date: 2022/8/11 11:56
     * @param $openid
     * @return mixed
     */
    public function getWechatUser($openid)
    {
        $weChat = app('wechat.official_account');

        return $weChat->user->get($openid);
    }

    /**
     * Notes: 设置已关注列表
     *
     * @Author: 玄尘
     * @Date: 2022/9/28 14:18
     * @param $unionid
     * @param $openid
     * @param  int  $subscribe
     */
    public function setUserSubscribe($unionid, $openid, int $subscribe = 1)
    {
        UserWechatSubscribe::query()->updateOrCreate([
            'unionid' => $unionid,
            'openid'  => $openid,
        ], [
            'subscribe' => $subscribe,
        ]);
    }

    /**
     * Notes: 入库所有关注列表
     *
     * @Author: 玄尘
     * @Date: 2022/9/28 14:41
     */
    public function getAllSubscribeUsers()
    {
        $app   = app('wechat.official_account');
        $users = $app->user->list();
        collect($users->data['openid'])
            ->split(3)->map(function ($datas) use ($app) {
                $infos = $app->user->select($datas->toArray());
                foreach ($infos['user_info_list'] as $info) {
                    $this->setUserSubscribe($info['unionid'], $info['openid'], 1);
                }
            });
    }

    /**
     * Notes: 用户关注公众号
     *
     * @Author: 玄尘
     * @Date: 2022/11/1 14:19
     */
    public function userSubOfficial()
    {
        $app  = app('wechat.official_account');
        $user = $app->user->get($this->payload->FromUserName);

        if ($user->unionid) {
            $wechatUsers = UserWechat::query()
                ->where('unionid', $user->unionid)
                ->get();
            if ($wechatUsers->isNotEmpty()) {
                foreach ($wechatUsers as $wechatUser) {
                    if ($wechatUser->official) {
                        if ($wechatUser->official->subscribe != 1) {
                            $wechatUser->official->update([
                                'subscribe'     => 1,
                                'subscribed_at' => Carbon::parse($user->subscribe_time)->toDateTimeString(),
                            ]);
                        }
                    } else {
                        $wechatUser->official()->create([
                            'openid'        => $this->payload->FromUserName,
                            'subscribe'     => 1,
                            'subscribed_at' => Carbon::parse($user->subscribe_time)->toDateTimeString(),
                        ]);
                    }

                }
            }

            //插入关注数据
            $this->setUserSubscribe($user->unionid, $this->payload->FromUserName, 1);

        } else {
            // 先查找用户是否存在，不存在再注册
            $officialUsers = UserWechatOfficial::query()
                ->where('openid', $this->payload->FromUserName)
                ->get();

            //设置总表uniond
            if ($officialUsers->isNotEmpty()) {
                foreach ($officialUsers as $officialUser) {
                    if (! $officialUser->userWechat->unionid && $user->unionid) {
                        $officialUser->userWechat->update([
                            'unionid' => $user->unionid
                        ]);
                    }

                    if ($officialUser->subscribe != 1) {
                        $officialUser->update([
                            'subscribe'     => 1,
                            'subscribed_at' => Carbon::parse($user->subscribe_time)->toDateTimeString(),
                        ]);
                    }
                }
            }
        }
    }

    /**
     * Notes: 用户取消关注公众号
     *
     * @Author: 玄尘
     * @Date: 2022/11/1 14:25
     */
    public function userUnSubOfficial()
    {
        $officialUsers = UserWechatOfficial::where('openid', $this->payload->FromUserName)->get();
        if ($officialUsers->isNotEmpty()) {
            foreach ($officialUsers as $officialUser) {
                $officialUser->update([
                    'subscribe'     => 0,
                    'subscribed_at' => null,
                ]);

                //设置取消关注
                if ($officialUser->userWechat && $officialUser->userWechat->unionid) {
                    $this->setUserSubscribe($officialUser->userWechat->unionid, $officialUser->openid, 0);
                }
            }
        }
    }

}