<?php

namespace App\Models;

use cccdl\yunxin_sdk\Im\Msg;
use cccdl\yunxin_sdk\Im\Team;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class Group extends BaseModel
{
    use HasFactory;

    const TYPE_WECHAT = 0;
    const TYPE_WANGYIYUN = 1;

    const SERVICE_TYPE_GENERAL = 0; // 普通
    const SERVICE_TYPE_DMA = 1; // DMA
    const SERVICE_TYPE_CERT = 2; // 双证
    const SERVICE_TYPE_MINI_DMA = 3; // MENI DMA

    public function users()
    {
        return $this->hasManyThrough(User::class, GroupUser::class, 'group_id', 'id', 'id', 'user_id')->selectRaw('ufutx_users.id, name, avatar, mobile, role_id, role_name,nickname');
    }
    public function order()
    {
        return $this->hasOne(Order::class, 'id', 'order_id');
    }

    public function groupUsers()
    {
        return $this->hasMany(GroupUser::class, "group_id", "id");
    }

    public function groupRoleUsers()
    {
        return $this->hasMany(GroupUser::class, "group_id", "id")->where("role_id", ">", 0);
    }

    public function autoCreateChat($order_id)
    {
        $icon = "https://images.health.ufutx.com/202411/15/2d117497b649f659d103069e10a785b9.jpeg";
        DB::beginTransaction();
        $order = Order::where('id', $order_id)->first();
        //生成规则都是一样的,这里就不查数据库了
        $owner_id = 8;
        if (config('app.env') == "production") {
            $owner_id = 3675;
        }
        $owner_ac_cid = make_wangyiyun_accid($owner_id);

        $members = [7];
        if (config('app.env') == "production") {
            $members = [1080];
        }
        if ($order->user_id > 0) {
            $members = array_merge($members, [$order->user_id]);
        }

        Log::info("autoCreateChat:" . json_encode($members));
        $im_members = [];
        foreach ($members as $id) {
            $im_members[] = make_wangyiyun_accid($id);
        }
        $options = [];
        $options['icon'] = $icon;
        $options['intro'] = $order->name . "服务群,友福健康，诚心为您服务";
        $options['announcement'] = $data['announcement'] ?? "友福健康，诚心为您服务";
        //创建群,并插入群成员
        $imTeam = new Team(config('chat.im.app_id'), config('chat.im.app_secret'));
        $group_info = $imTeam->create($order->name . "服务群", $owner_ac_cid, $im_members, '友福健康，诚心为您服务', 0, 0, $options);

        //创建群
        $map = [];
        $map['name'] = $order->name . "服务群";
        $map['order_id'] = $order_id;
        $map['avatar'] = $icon;
        $map['intro'] = $order->name . "服务群,友福健康，诚心为您服务";
        //         $map['announcement'] = "欢迎加入DMA服务群！  
// · 本群用于教练指导您的健康管理服务，请勿讨论政治、宗教或发布外部广告。  
// · 服务团队将陆续进群为您提供支持，祝您健康之旅顺利！🌹🌹";
        $map["announcement"] = "😊 本群是您的专属健康服务群

👏 让我们一起携手创造快乐温馨的学习氛围，祝福您在此有一个美好的健康生活之旅

【请勿讨论政治、宗教或发广告】";
        $map['owner_id'] = $owner_id;
        $map['chat_name'] = $order->name . "服务群";
        $map['im_chat_id'] = $group_info['tid'];
        $map["service_type"] = 1;
        $map['type'] = Group::TYPE_WANGYIYUN;
        $group_model = Group::updateorcreate(['order_id' => $order_id], $map);

        //插入群主到群成员表
        GroupUser::create(['user_id' => $owner_id, 'group_id' => $group_model->id, 'type' => GroupUser::TYPE_OWNER]);
        foreach ($members as $member) {
            GroupUser::create(['user_id' => $member, 'group_id' => $group_model->id, 'type' => GroupUser::TYPE_NORMAL]);
        }

        //发送群消息
        $owner_ac_cid = make_wangyiyun_accid($owner_id);
        $imMsg = new Msg(config('chat.im.app_id'), config('chat.im.app_secret'));

        $imMsg->sendMsg($owner_ac_cid, 1, $group_info['tid'], 0, json_encode(['msg' => $map['announcement']]));
        DB::commit();
    }

    public function autoCreateChatV2($order_id, $group_name, $service_type, $announcement)
    {
        $icon = "https://images.health.ufutx.com/202411/15/2d117497b649f659d103069e10a785b9.jpeg";
        DB::beginTransaction();
        $order = Order::where('id', $order_id)->first();
        //生成规则都是一样的,这里就不查数据库了

        $owner_id = 8;
        if (config('app.env') == "production") {
            $owner_id = 3675;
        }

        $members = [4513];
        if (config('app.env') == "production") {
            $members = [1080];
        }
        if ($order->user_id > 0) {
            $members = array_merge($members, [$order->user_id]);
        }

        $owner_ac_cid = make_wangyiyun_accid($owner_id);


        Log::info("autoCreateChat:" . json_encode($members));
        $im_members = [];
        foreach ($members as $id) {
            $im_members[] = make_wangyiyun_accid($id);
        }
        //         $announcement = "【友福同享】欢迎加入DMA服务群[Mini版]!

        // ·本群用于教练指导您的健康管理服务，请勿讨论政治、宗教或发布外部广告。

        // ·服务团队将陆续进群为您提供支持，祝您健康之旅顺利! 🌹🌹";
        $options = [];
        $intro = $group_name . ",友福健康，诚心为您服务";
        $options['icon'] = $icon;
        $options['intro'] = $intro;
        $options['announcement'] = $announcement;
        //创建群,并插入群成员
        $imTeam = new Team(config('chat.im.app_id'), config('chat.im.app_secret'));
        $group_info = $imTeam->create($group_name, $owner_ac_cid, $im_members, '友福健康，诚心为您服务', 0, 0, $options);

        //创建群
        $map = [];
        $map['name'] = $group_name;
        $map['order_id'] = $order_id;
        $map['avatar'] = $icon;
        $map['intro'] = $intro;
        $map["announcement"] = $announcement;
        $map['owner_id'] = $owner_id;
        $map['chat_name'] = $group_name;
        $map['im_chat_id'] = $group_info['tid'];
        $map["service_type"] = $service_type;
        $map['type'] = Group::TYPE_WANGYIYUN;
        $group_model = Group::updateorcreate(['order_id' => $order_id], $map);

        //插入群主到群成员表
        GroupUser::create(['user_id' => $owner_id, 'group_id' => $group_model->id, 'type' => GroupUser::TYPE_OWNER]);
        foreach ($members as $member) {
            GroupUser::create(['user_id' => $member, 'group_id' => $group_model->id, 'type' => GroupUser::TYPE_NORMAL]);
        }

        //发送群消息
        $owner_ac_cid = make_wangyiyun_accid($owner_id);
        $imMsg = new Msg(config('chat.im.app_id'), config('chat.im.app_secret'));

        $imMsg->sendMsg($owner_ac_cid, 1, $group_info['tid'], 0, json_encode(['msg' => $map['announcement']]));
        DB::commit();
        return;
    }
    public function autoCreateCertChat(int $userId, string $chatName, $orderId = 0)
    {
        $icon = "https://images.health.ufutx.com/202411/15/2d117497b649f659d103069e10a785b9.jpeg";
        DB::beginTransaction();
        //生成规则都是一样的,这里就不查数据库了
        $owner_id = 8;
        if (config('app.env') == "production") {
            $owner_id = 15536;
        }
        $owner_ac_cid = make_wangyiyun_accid($owner_id);

        $service_user_id = 7;
        if (config('app.env') == "production") {
            $service_user_id = 1620;
        }

        // 群成员
        $members = [$service_user_id, $userId];

        Log::info("autoCreateCertChat:" . json_encode($members));
        $im_members = [];
        foreach ($members as $id) {
            $im_members[] = make_wangyiyun_accid($id);
        }
        $options = [];
        $options['icon'] = $icon;
        $options['intro'] = $chatName . ",友福健康，诚心为您服务";
        $options['announcement'] = "😊 本群是您的双证咨询服务群

👏 让我们一起携手创造快乐温馨的学习氛围，祝福您在此有一个美好的健康生活之旅

【请勿讨论政治、宗教或发广告】";
        //创建群,并插入群成员
        $imTeam = new Team(config('chat.im.app_id'), config('chat.im.app_secret'));
        $group_info = $imTeam->create($chatName, $owner_ac_cid, $im_members, "友福健康，诚心为您服务", 0, 0, $options);

        //创建群
        $map = [];
        $map['name'] = $chatName;
        $map['order_id'] = $orderId;
        $map['avatar'] = $icon;
        $map['intro'] = $options['intro'];
        $map["announcement"] = $options['announcement'];
        $map['owner_id'] = $owner_id;
        $map['chat_name'] = $chatName;
        $map['im_chat_id'] = $group_info['tid'];
        $map["service_type"] = 2;
        $map['type'] = Group::TYPE_WANGYIYUN;
        $group_model = Group::create($map);

        //插入群主到群成员表
        GroupUser::create(['user_id' => $owner_id, 'group_id' => $group_model->id, 'type' => GroupUser::TYPE_OWNER]);
        foreach ($members as $member) {
            GroupUser::create(['user_id' => $member, 'group_id' => $group_model->id, 'type' => GroupUser::TYPE_NORMAL]);
        }

        //发送群消息
        $owner_ac_cid = make_wangyiyun_accid($owner_id);
        $imMsg = new Msg(config('chat.im.app_id'), config('chat.im.app_secret'));

        $imMsg->sendMsg($owner_ac_cid, 1, $group_info['tid'], 0, json_encode(['msg' => $map['announcement']]));
        DB::commit();
    }

    // 群用户id
    public static function getGroupUserId($group_id)
    {
        $user_id = GroupUser::where("group_id", $group_id)->whereHas("user", function ($sql) {
            $sql->whereIn("source", [2, 3, 5]);
        })->value("user_id");
        return $user_id;
    }


}
