<?php

namespace App\Api\WechatHandlers;


use Carbon\Carbon;
use EasyWeChat\Kernel\Contracts\EventHandlerInterface;
use EasyWeChat\Kernel\Messages\Text;
use Modules\User\Models\UserWechat;
use Modules\User\Models\UserWechatOfficial;
use Modules\User\Traits\WechatTrait;

class EventMessageHandler implements EventHandlerInterface
{
    use WechatTrait;

    private $payload;

    public function handle($payload = null)
    {
        if (method_exists($this, $payload->Event)) {
            $this->payload = $payload;
            return call_user_func_array([$this, $payload->Event], []);
        } else {
            //            return '暂不支持的消息类型';
        }
    }


    /**
     * Notes: 关注事件
     *
     * @Author: 玄尘
     * @Date: 2022/7/27 9:41
     */
    private function subscribe()
    {
        $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(),
                        ]);
                    }
                }
            }
        }

        return $this->firstSubscribeMessage();
    }

    /**
     * Notes: 取消关注事件
     *
     * @Author: 玄尘
     * @Date: 2022/7/27 9:41
     */
    private function unsubscribe()
    {
        $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) {
                    $this->setUserSubscribe($officialUser->userWechat->unionid, $officialUser->openid, 0);
                }
            }
        }
    }

    /**
     * Notes: 关注返回的消息
     *
     * @Author: 玄尘
     * @Date: 2022/8/2 11:37
     * @return Text
     */
    private function firstSubscribeMessage()
    {
        $officialUser = UserWechatOfficial::where('openid', $this->payload->FromUserName)->first();
        $text         = new Text('扎西德勒！感谢关注锶源昆仑。锶源昆仑天然饮用水，水源地位于海拔4300米的昆仑山，水中富含镁离子、锶元素、钙元素等微量元素且氘含量低，稀世罕见，仅供30000人饮用。
参与打卡“锶享体验官”活动，请点击公众号菜单上的按钮“锶享体验官”进入活动，来申请喝水体验官吧！');
        if ($officialUser && $officialUser->userWechat) {
            $nickname = $officialUser->userWechat->nickname;
            $text     = new Text('扎西德勒！'.$nickname.'，感谢关注锶源昆仑。锶源昆仑天然饮用水，水源地位于海拔4300米的昆仑山，水中富含镁离子、锶元素、钙元素等微量元素且氘含量低，稀世罕见，仅供30000人饮用。
参与打卡“锶享体验官”活动，请点击公众号菜单上的按钮“锶享体验官”进入活动，来申请喝水体验官吧！');
        }


        return $text;
    }

}
