<?php
/**
 *
 * @file:WechatCommonSevice.php
 * @Date: 2023/7/7
 * @Time: 11:44
 */


namespace Modules\WechatPlatform\Services;

use Illuminate\Support\Facades\DB;
use Modules\Common\Services\BaseService;
use Modules\WechatPlatform\Models\WechatOfficialUserInfo;

class WechatCommonService extends BaseService
{


    /**
     *  播放页面地址
     * name: getPlayPageUrl
     * @param $videoId
     * @param $sequence
     * date 2023/07/07 11:52
     */
    public static function getPlayPageUrl($videoId, $sequence)
    {
        return ['url' => "/pages/video/index?video_id={$videoId}&sequence={$sequence}"];
    }

    /**
     *   微信消息推送处理
     * name: handleMessage
     * @param $app
     * @param $wechatInfoId 公众号授权信息id
     * @param $appid 公众号APPID
     * @param $message
     * @return string|void
     * date 2023/07/10 16:04
     */
    public static function handleMessage($app, $wechatInfoId, $appid, $message)
    {
        switch ($message['MsgType']) {
            case 'event':
                return self::handleEvent($app, $wechatInfoId, $appid, $message);
            case 'text':
                // 更新用户活跃时间
                self::updateUserActivityTime($app,$appid, $message['FromUserName'],$wechatInfoId );
                return self::handleTextMessage($wechatInfoId, $message);
            // case 'image':
            //     return '收到图片消息';
            // case 'voice':
            //     return '收到语音消息';
            // case 'video':
            //     return '收到视频消息';
            // case 'location':
            //     return '收到坐标消息';
            // case 'link':
            //     return '收到链接消息';
            // case 'file':
            //     return '收到文件消息';
            default:
                self::updateUserActivityTime($app, $appid, $message['FromUserName'],$wechatInfoId);
                return '收到其它消息';
        }
        return "";
    }

    /**
     *  文本纤细处理
     * name: handleTextMessage
     * @param $appid
     * @param $content
     * date 2023/07/10 15:03
     */
    private static function handleTextMessage($wechatAppId, $msg)
    {
        $content = $msg['Content'];
        if ($content == "pk") {
            return $msg['FromUserName'];
        }
        $back = WechatKeywordsService::getKeywordsByWords($content, $wechatAppId);
        return $back ?: "";
    }

    /**
     *  更新用户活跃时间
     * name: updateUserActivityTime
     * @param $app
     * @param $appid
     * @param $openId
     * date 2023/07/10 18:30
     */
    private static function updateUserActivityTime($app, $appid, $openId, $wechatInfoId)
    {

        $info = WechatOfficialUserInfo::query()->where('mp_openid', $openId)->where('gzh_appid', $appid)->first();
        $data = [
            'mp_openid' => $openId,
            'gzh_appid' => $appid,
            'gzh_id' =>  $wechatInfoId,
            'active_at' => time(),
        ];
        if (is_empty($info)) {
            $data = self::getUserInfo($app,$appid,$openId,$wechatInfoId);
            $data['active_at'] = time();
        }else{
            if ($info->uid == 0 && !empty($info->unionid)){
                $data['uid'] = intval(DB::table('wechat_miniprogram_users')->where('unionid', $info->unionid)->value('id'));
            }
        }

        WechatOfficialUserInfo::updateOrCreate(['mp_openid' => $data['mp_openid'], 'gzh_appid' => $data['gzh_appid']], $data);
    }

    /**
     *  关注取消关注更新用户信息
     * name: updateUserInfo
     * @param $app
     * @param $appid
     * @param $openId
     * @param $is_gz
     * date 2023/07/10 18:31
     */
    private static function updateUserInfo($app, $appid, $openId, $wechatInfoId, $is_gz)
    {

        if (!$is_gz) {
            $data = [
                'mp_openid' => $openId,
                'gzh_appid' => $appid,
                'gzh_id' => $wechatInfoId,
                'active_at' => time(),
                'is_subscribe' => 0,
                'unsubscribe_at' => get_date(),
            ];
        } else {
            $data = [
                'mp_openid' => $openId,
                'gzh_appid' => $appid,
                'gzh_id' => $wechatInfoId,
                'is_subscribe' => 1,
                'subscribe_time' => time(),
                'subscribe_time_str' => get_date(),
            ];
        }
        $info = WechatOfficialUserInfo::query()->where('mp_openid', $openId)->where('gzh_appid', $appid)->first();
        if ($is_gz == true && is_empty($info)) {
            $data = self::getUserInfo($app,$appid,$openId,$wechatInfoId);
            WechatOfficialUserInfo::updateOrCreate(['mp_openid' => $data['mp_openid'], 'gzh_appid' => $data['gzh_appid']], $data);
        }else{
            if (!is_empty($info)){
                if ($info->uid == 0 && !empty($info->unionid)){
                    $data['uid'] = intval(DB::table('wechat_miniprogram_users')->where('unionid', $info->unionid)->value('id'));
                }
                WechatOfficialUserInfo::updateOrCreate(['mp_openid' => $data['mp_openid'], 'gzh_appid' => $data['gzh_appid']], $data);
            }
        }
    }

    /**3
     *  构建用户数据
     * name: getUserInfo
     * @param $app
     * @param $appid
     * @param $openId
     * date 2023/07/10 18:31
     */
    protected  static  function getUserInfo($app,$appid,$openId, $wechatInfoId){
        $user = $app->user->get($openId);
        return [
            'mp_openid' => $openId,
            'gzh_appid' => $appid,
            'gzh_id' => $wechatInfoId,
            'unionid' => $user['unionid'],
            'is_subscribe' => $user['subscribe'],
            'subscribe_time' => $user['subscribe_time'],
            'subscribe_time_str' => get_date($user['subscribe_time']),
            'uid' => !is_empty($user['unionid']) ? intval(DB::table('wechat_miniprogram_users')->where('unionid', $user['unionid'])->value('id')) : 0,
        ];
    }

    /**
     *  处理事件消息
     * name: handleEvent
     * @param $app
     * @param $wechatInfoId
     * @param $appid
     * @param $message
     * @return mixed|string
     * date 2023/07/11 09:15
     */
    private static function handleEvent($app,  $wechatInfoId, $appid, $message)
    {
        switch ($message['Event']) {
            case 'unsubscribe':
                self::updateUserInfo($app, $appid, $message['FromUserName'], $wechatInfoId,false);
                return '取消关注';
            case 'subscribe':
                self::updateUserInfo($app, $appid, $message['FromUserName'],$wechatInfoId, true);
                return WechatSubscribeService::getContent($wechatInfoId);
            case 'CLICK':
                return  WechatMenuService::getClickInfoContent($wechatInfoId,$message['EventKey']);
            default:
                return '收到其它消息';
        }
        return  '';
    }


}