<?php
/**
 *  ╔═══════════════════════════════════════════════════╗
 *  ║                                                   ║
 *  ║     ██╗  ██╗   █████╗    ██████╗                  ║
 *  ║     ██║  ██║  ██╔══██╗  ██╔═══██╗                 ║
 *  ║     ███████║  ███████║  ██║   ██║                 ║
 *  ║     ██╔══██║  ██╔══██║  ██║   ██║                 ║
 *  ║     ██║  ██║  ██║  ██║  ╚██████╔╝   SNS           ║
 *  ║                                                   ║    
 *  ║                                                   ║    
 *  ║     © 2023 HaoSNS™ All Rights Reserved            ║
 *  ║     官方网站: https://www.haosns.com                *
 *  ║     本代码由赣州乐易网络科技有限公司®提供             *
 *  ║                                                    *
 *  ║   未经授权禁止复制、传播或用于其他商业目的            *
 *  ║                                                   ║
 *  ╚═══════════════════════════════════════════════════╝
 */

namespace app\common\logic;


use app\common\cache\ChatCache;
use app\common\enum\{ ChatMsgEnum, ChatEnum};
use app\common\model\{ChatRelation, Goods,  User};
use app\common\service\ConfigService;

/**
 * 通用聊天逻辑
 * Class ChatLogic
 * @package app\common\logic
 */
class ChatLogic extends BaseLogic
{

    /**
     * @notes 在线用户
     * @return array|bool
     */
    public static function getOnlineUser()
    {
        $key = config('project.websocket_prefix') . 'user';
        return (new ChatCache())->getSmembersArray($key);
    }


    /**
     * @notes 格式化聊天记录
     * @param $records
     * @return array
     * @date 2022/3/14 15:05
     */
    public static function formatChatRecords($records) : array
    {
        if (empty($records)) {
            return [];
        }

        $receive = [];
        $user = [];

        // 获取到客服和用户不同的两组id
        foreach ($records as $item) {
            if ($item['from_type'] == ChatEnum::TYPE_RECEIVE) {
                $receive[] = $item['from_id'];
            } else {
                $user[] = $item['from_id'];
            }
        }

        $receive = array_unique($receive);
        $user = array_unique($user);

        $receive = User::where('id', 'in', $receive)->column('nickname, avatar', 'id');
        $user = User::where('id', 'in', $user)->column('nickname, avatar', 'id');

        foreach ($records as &$item) {
            $item['from_nickname'] = '';
            $item['from_avatar'] = '';

            if ($item['from_type'] == ChatEnum::TYPE_RECEIVE) {
                $receiveId = $item['from_id'];
                if (isset($receive[$receiveId])) {
                    $item['from_nickname'] = $receive[$receiveId]['nickname'] ?? '';
                    $item['from_avatar'] = $receive[$receiveId]['avatar'] ?? '';
                }
            }

            if ($item['from_type'] == ChatEnum::TYPE_USER) {
                $userId = $item['from_id'];
                if (isset($user[$userId])) {
                    $item['from_nickname'] = $user[$userId]['nickname'] ?? '';
                    $item['from_avatar'] = $user[$userId]['avatar'] ?? '';
                }
            }
     

            $item['create_time_stamp'] = strtotime($item['create_time']);
        }
        return array_reverse($records);
    }

        /**
     * @notes 格式化聊天记录
     * @param $records
     * @return array
     * @date 2022/3/14 15:05
     */
    public static function formatChatMessages($messages) : array
    {
        if (empty($messages)) {
            return [];
        }

        $receive = [];
        $user = [];

        // 获取到客服和用户不同的两组id
        foreach ($messages as $item) {
            if ($item['from_type'] == ChatEnum::TYPE_RECEIVE) {
                $receive[] = $item['from_id'];
            } else {
                $user[] = $item['from_id'];
            }
        }

        $receive = array_unique($receive);
        $user = array_unique($user);

        $receive = User::where('id', 'in', $receive)->column('nickname, avatar', 'id');
        $user = User::where('id', 'in', $user)->column('nickname, avatar', 'id');

        foreach ($messages as &$item) {
            $item['from_nickname'] = '';
            $item['from_avatar'] = '';

            if ($item['from_type'] == ChatEnum::TYPE_RECEIVE) {
                $receiveId = $item['from_id'];
                if (isset($receive[$receiveId])) {
                    $item['from_nickname'] = $receive[$receiveId]['nickname'] ?? '';
                    $item['from_avatar'] = $receive[$receiveId]['avatar'] ?? '';
                }
            }

            if ($item['from_type'] == ChatEnum::TYPE_USER) {
                $userId = $item['from_id'];
                if (isset($user[$userId])) {
                    $item['from_nickname'] = $user[$userId]['nickname'] ?? '';
                    $item['from_avatar'] = $user[$userId]['avatar'] ?? '';
                }
            }
     

            $item['create_time_stamp'] = strtotime($item['create_time']);
        }
        return array_reverse($messages);
    }



    /**
     * @notes 绑定关系
     * @param $userId
     * @param $receiveId
     * @param $data
     * @param int $isRead
     * @return mixed
     * @date 2022/3/14 15:06
     */
    public static function bindRelation($userId, $receiveId, $data, $isRead = 0)
    {
        $relation = ChatRelation::where(['user_id' => $userId])->findOrEmpty();

        $user = User::where(['id' => $userId])->findOrEmpty();
        
        if ($relation->isEmpty()) {
            $relation = ChatRelation::create([
                'user_id' => $userId,
                'receive_id' => $receiveId,
                'nickname' => $user['nickname'],
                'avatar' => $user['avatar'],
                'terminal' => $data['terminal'] ?? 0,
                'msg' => $data['msg'] ?? '',
                'msg_type' => $data['msg_type'] ?? ChatMsgEnum::TYPE_TEXT,
                'is_read' => 1, // 新创建关系都算已读
                'create_time' => time(),
                'update_time' => time(),
            ]);
        } else {
            ChatRelation::update(
                [
                    'receive_id' => $receiveId,
                    'nickname' => $user['nickname'],
                    'avatar' => $user['avatar'],
                    'terminal' => $data['terminal'] ?? 0,
                    'msg' => $data['msg'] ?? '',
                    'msg_type' => $data['msg_type'] ?? ChatMsgEnum::TYPE_TEXT,
                    'update_time' => time(),
                    'is_read' => $isRead
                ],
                ['id' => $relation['id']]
            );
        }

        return $relation['id'];
    }


    /**
     * @notes 配置
     * @return array
     * @remark 
     */
    public static function getConfig(): array
    {

        // 缓存配置
        if ('redis' != self::getCacheDrive()) {
            return ['code' => 0, 'msg' => '请联系管理员设置缓存驱动为redis'];
        }

        return ['code' => 1, 'msg' => ''];
    }


    /**
     * @notes 检查配置
     * @return bool
     */
    public static function checkConfig():  bool
    {
        try {

            if ('redis' != self::getCacheDrive()) {
                throw new \Exception('请联系管理员设置缓存驱动为redis');
            }
            return true;
        } catch (\Exception $e) {
            self::$error = $e->getMessage();
            return false;
        }
    }



    /**
     * @notes 当前缓存驱动
     * @return mixed
     */
    public static function getCacheDrive()
    {
        return config('cache.default');
    }



}