<?php

namespace App\Services;
use App\Models\DmaServiceUserRole;
use App\Models\Group;
use App\Models\GroupMessage;
use App\Models\GroupMessageConfig;
use App\Models\GroupUser;
use App\Models\Order;
use App\Models\ServiceRole;
use App\Models\ServiceRoleOrder;
use cccdl\yunxin_sdk\Im\Msg;
use GatewayClient\Gateway;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class ChatService
{
    const MSG_TYPE_GROUP = 100; //群聊自定义消息
    const MSG_TYPE_GROUP_FAT = 1; //自定义消息，体重详情
    const MSG_TYPE_GROUP_GUIDE = 2; //自定义消息，餐单详情


    const MSG_SINGLE_OPE = 0; // 单聊
    const MSG_GROUP_OPE = 1; // 群聊

    const MSG_TYPE_TEXT = 0; // 文本
    const MSG_TYPE_IMG = 1; // 图片
    const MSG_TYPE_AUDIO = 2; // 语言
    const MSG_TYPE_VIDEO = 3; // 视频
    const MSG_TYPE_LOCAL = 4; // 地理位置
    const MSG_TYPE_FILE = 6; // 文件
    const MSG_TYPE_NOTICE = 10; // 提示
    const MSG_TYPE_CUSTOM = 100; // 自定义



    public function bindUid($client_id, $uid)
    {
        Gateway::bindUid($client_id, $uid);
        return true;
    }

    public function joinGroup($client_id, $group_id)
    {
        Gateway::joinGroup($client_id, $group_id);
        return true;
    }

    public function leaveGroup($client_id, $group_id)
    {
        Gateway::leaveGroup($client_id, $group_id);
        return false;
    }

    public function getClientIdByUid($uid)
    {
        $res = Gateway::getClientIdByUid($uid);
        if (count($res) == 0)
            return null;
        return $res[0];
    }

    public function sendNoticeNum($user)
    {
        $group_id = GroupUser::where('user_id', $user->id)->value("group_id");
        $chat_num = 0;
        if ($group_id) {
            //发送未读数 todo
            $last_msg_id = GroupMessageConfig::where('group_id', $group_id)->where('user_id', $user->id)->value('last_msg_id');
            $chat_num = GroupMessage::where('group_id', $group_id)->where('is_read', 0)->where('id', '>', $last_msg_id)->count();
        }
        $message = ['scene' => 'team', 'type' => 'notification', 'text' => $chat_num];
        $this->sendToUid($user->id, $message);
    }

    public function sendToUid($uid, $message)
    {
        Gateway::sendToUid($uid, $message);
        return true;
    }

    public function sendToGroup($group_id, $message)
    {
        Gateway::sendToGroup($group_id, json_encode($message));
    }

    public function getUidListByGroup($group_id)
    {
        Gateway::getUidListByGroup($group_id);
    }

    /**
     * 发送自定义网易云群消息
     * @param null $user
     * @param array $data
     * @return false|\Illuminate\Http\JsonResponse|void
     */
    public function sendGroupMsg($user_id = null, $title = '提示信息', $content = '请点击查看详情', $icon = '', $page_url = '', $params = [], $order = null)
    {
        try {
            if (empty($user_id)) {
                return false;
            }

            if (empty($order)) {
                $order = Order::getPayOrder($user_id);
            }
            if (empty($order)) {
                return false;
            }
            //查看订单是否绑定群,并存在群主
            $group = Group::where('order_id', $order->id)->whereNotNull('im_chat_id')->whereNotNull('owner_id')->first();
            if (empty($group)) {
                return false;
            }
            //获取群主网易云accid
            $owner_ac_cid = make_wangyiyun_accid($group->owner_id);
            $this->sendImMsg($owner_ac_cid, $group->im_chat_id, 1, $title, $content, $icon, $page_url, $params);
            return true;
        } catch (\Exception $e) {
            Log::error('sendGroupMsg:' . $e->getMessage());
            return false;
        }
    }

    /**
     * 发送网易云消息,单对单
     * @param $order_id
     * @param string $title
     * @param string $content
     * @param string $icon
     * @param string $page_url
     * @param array $role
     * @param array $params
     */
    public function sendImMsgUserToUser($order_id, $title = '系统通知', $content = '点击查看详情', $icon = '', $page_url = '', $role = [], $params = [], $user_ids = [])
    {
        if (empty($order_id)) {
            return false;
        }
        //获取群主网易云accid
        $user_id = 12;
        if (config('app.env') == 'production') {
            $user_id = 4169;
        }

        $group = Group::where('order_id', $order_id)->first();
        if (empty($group))
            return false;
        $to_user_ids = ServiceRoleOrder::where('order_id', $order_id)->whereNotIn('user_id', $user_ids)->whereIn('role_id', $role)->pluck('user_id')->unique()->toArray();

        if (in_array(ServiceRole::ADMINISTRATIVE, $role)) { // 通知行政
            $admin_user_ids = DmaServiceUserRole::where("role", ServiceRole::ADMINISTRATIVE)->whereNotIn("user_id", $to_user_ids)->pluck("user_id")->unique()->toArray();
            $to_user_ids = array_merge($to_user_ids, $admin_user_ids);
        }

        //获取需要发送的人员
        $params['ext'] = json_encode(['is_system' => 1]);
        $params['chat_id'] = $group->im_chat_id;
        $params["group_name"] = $group->name;
        $user_ac_cid = make_wangyiyun_accid($user_id);
        foreach ($to_user_ids as $to_user_id) {
            $url = $page_url;
            $to_user_ac_cid = make_wangyiyun_accid($to_user_id);
            if (strpos($url, "https") !== false) {
                $role = ServiceRoleOrder::where('order_id', $order_id)->where('user_id', $to_user_id)->value('role_id');
                // 包含 "https"
                $url = $url . '?service_user_id=' . $to_user_id . '&chat_id=' . $group->im_chat_id . '&is_im=1&role=' . $role;
            }
            Log::info('sendImMsgUserToUser url:' . $url);
            $this->sendImMsg($user_ac_cid, $to_user_ac_cid, 0, $title, $content, $icon, $url, $params);
        }
    }

    public function sendImMsgUserToUserV2($order_id, $to_user_id, $title = '系统通知', $content = '点击查看详情', $icon = '', $page_url = '')
    {
        if (empty($order_id)) {
            return false;
        }
        //获取群主网易云accid
        $user_id = 12;
        if (config('app.env') == 'production') {
            $user_id = 4169;
        }

        $group = Group::where('order_id', $order_id)->first();
        //获取需要发送的人员
        $params['ext'] = json_encode(['is_system' => 1]);
        $params['chat_id'] = $group->im_chat_id;
        $params["group_name"] = $group->name;
        $user_ac_cid = make_wangyiyun_accid($user_id);
        $url = $page_url;
        $to_user_ac_cid = make_wangyiyun_accid($to_user_id);
        $role = ServiceRoleOrder::where('order_id', $order_id)->where('user_id', $to_user_id)->value('role_id');
        if (strpos($url, "https") !== false) {
            // 包含 "https"
            $url = $url . '?service_user_id=' . $to_user_id . '&chat_id=' . $group->im_chat_id . '&is_im=1&role=' . $role;
        }
        Log::info('sendImMsgUserToUser url:' . $url);
        $this->sendImMsg($user_ac_cid, $to_user_ac_cid, 0, $title, $content, $icon, $url, $params);

    }

    /**
     * 提取公因式发送消息到网易云信
     * @param $user_ac_cid
     * @param $to_user_ac_cid
     * @param $op
     * @param $title
     * @param $content
     * @param string $icon
     * @param string $page_url
     * @param array $params
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \cccdl\yunxin_sdk\Exception\cccdlException
     */
    public function sendImMsg($user_ac_cid, $to_user_ac_cid, $op, $title, $content, $icon = '', $page_url = '', $params = [])
    {
        $imMsg = new Msg(config('chat.im.app_id'), config('chat.im.app_secret'));
        $send_data = [];
        $send_data['title'] = $title;
        $send_data['content'] = $content;
        $send_data['page_url'] = $page_url;
        $send_data['icon'] = $icon;
        $send_data['type'] = self::MSG_TYPE_GROUP;
        $send_data['data'] = ['type' => 1002, 'title' => "", 'content' => "", 'page_url' => "", 'icon' => "", 'params' => ""];
        $params['extra'] = 1;
        $send_data['params'] = $params;
        $send_data['push'] = true;

        //增加日志
        Log::info("sendGroupMsg from:" . $user_ac_cid . "|to:" . $to_user_ac_cid . "|op:" . $op . "data:" . json_encode($send_data, JSON_UNESCAPED_UNICODE));

        $imMsg->sendMsg($user_ac_cid, $op, $to_user_ac_cid, self::MSG_TYPE_GROUP, json_encode($send_data, JSON_UNESCAPED_UNICODE));

    }

    public function getTextBody($message)
    {
        return json_encode(["msg" => $message], JSON_UNESCAPED_UNICODE);
    }
    public function getCustomBody($title, $content, $page_url, $icon, $params = [])
    {
        $send_data = [];
        $send_data['title'] = $title;
        $send_data['content'] = $content;
        $send_data['page_url'] = $page_url;
        $send_data['icon'] = $icon;
        $send_data['type'] = self::MSG_TYPE_GROUP;
        $send_data['data'] = ['type' => 1002, 'title' => "", 'content' => "", 'page_url' => "", 'icon' => "", 'params' => ""];
        $params['extra'] = 1;
        $send_data['params'] = $params;
        $send_data['push'] = true;
        return json_encode($send_data, JSON_UNESCAPED_UNICODE);
    }

    public function getIdCardMessageBody($order_id)
    {
        $title = "签署合约";
        $content = "友福同享《健康 DMA 人体驾照》依法成立的合约";
        $page_url = "yfheal://app/push/UploadIDCard";
        $icon = "https://ufutx-health.oss-cn-hangzhou.aliyuncs.com/202501/08/cobtract.png";
        $params = ["order_id" => $order_id];
        $res = $this->getCustomBody($title, $content, $page_url, $icon, $params);
        return $res;
    }

    /**
     * 发送文本消息
     * @param mixed $fromAccid  发送方
     * @param mixed $ope  聊天类型 ：单聊，群聊
     * @param mixed $to   接收方
     * @param mixed $body 消息内容
     * @return void
     */
    public function sendImMessage($fromAccid, $ope, $to, $type, $body)
    {
        $imMsg = new Msg(config('chat.im.app_id'), config('chat.im.app_secret'));
        $imMsg->sendMsg($fromAccid, $ope, $to, $type, $body);
        return;
    }
}
