<?php

namespace App\Http\Controllers\H5;

use App\Http\Controllers\Controller;
use App\Http\Response\ResponseJson;
use App\Jobs\AddErrorLog;
use App\Models\AnnualMeeting;
use App\Models\ConnectDragon;
use App\Models\ServiceUser;
use App\Models\Talk;
use App\Models\TalkComment;
use App\Models\TalkStar;
use App\Models\User;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use function Symfony\Component\Translation\t;

class OtherController extends Controller
{
    use ResponseJson;


    public function addConnectDragon(Request $request)
    {
        $name = $request->input('name');
        if (empty($name))
            return $this->failure('邀请人姓名不为空');
        $invite_name = $request->input('invite_name');
        if (empty($invite_name))
            return $this->failure('被邀请人姓名不为空');

        if (config('app.env') == 'production') {
            $work_wechat_user = session('work_wechat_user');
            if (empty($work_wechat_user))
                return $this->failure('未授权企业微信');
            //用户企业微信信息
            $work_user_id = $work_wechat_user['raw']['userid'];
        } else {
            $work_user_id = "hankin";
        }

        foreach ($invite_name as $value) {
            ConnectDragon::create(['name' => $name, 'invite_name' => $value, 'work_id' => $work_user_id, 'type' => ConnectDragon::TYPE_INVITE]);
        }

        //查询统计数据
        $count = ConnectDragon::select(DB::raw('count(id) as count'), DB::raw('name'))
            ->where('type', ConnectDragon::TYPE_INVITE)->orderBy('count', 'desc')->take(3)->groupBy('name')->get();
        //查询数据,再推送数据通知
        $list = ConnectDragon::where('type', ConnectDragon::TYPE_INVITE)->orderBy('id', 'desc')->get()?->toArray();

        $content = "友福邀约：\r\n";
        foreach ($count as $index => $val) {
            $rand = $index + 1;
            $emoji = "";
            if ($rand == 1) {
                $emoji = "👑";
            } elseif ($rand == 2) {
                $emoji = "💎";
            } elseif ($rand == 3) {
                $emoji = "🏆";
            }
            $content .= $emoji . ' ' . "第" . $rand . "名：" . $val->name . '  个数：' . $val->count . "\r\n";
        }
        $content = $content . "-----------------------\r\n";
        //        // 显示前10条数据
//        foreach (array_slice($list, 0, 10) as $index => $val) {
//            $content .= $index+1 . ":" . $val['name'] . "  " . $val['invite_name'] . "\r\n";
//        }
        $content = $content . "...\r\n...\r\n...\r\n";

        $count_invite = count($invite_name);
        $total_count = count($list);
        if ($count_invite > 3) {
            foreach ($invite_name as $k => $v) {
                $content .= $total_count - $count_invite + $k + 1 . "：" . $name . "  " . $v . "\r\n";
            }
        } else {
            // 显示后3条数据
            if ($total_count > 3) {
                foreach (array_slice($list, -3) as $k => $v) {
                    $content .= $total_count - 3 + $k + 1 . "：" . $v['name'] . "  " . $v['invite_name'] . "\r\n";
                }
            } else {
                foreach ($list as $k => $v) {
                    $content .= $k + 1 . "：" . $v['name'] . "  " . $v['invite_name'] . "\r\n";
                }
            }
        }
        $content = $content . "-----------------------\r\n" . "[我要邀约](" . config('app.url') . "/api/h5/invite/auth)\r\n";
        $content = $content . "-----------------------\r\n" . "[查看全部邀约](" . config('app.url') . "/api/h5/view/invite/auth)";

        $send_data = [
            'msgtype' => 'markdown',
            'markdown' => [
                'content' => $content,
            ]
        ];

        //正式群
        $url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=905fe4d1-a681-4133-b847-0be2d290477c";
        //测试群
        if (!(config('app.env') == 'production')) {
            $url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=fe963d6e-2a67-487a-b0ac-3dbdc62f6f8c";
        }
        //        $url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=fe963d6e-2a67-487a-b0ac-3dbdc62f6f8c";
        //本地群
//        $url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=ec3c5836-42cf-4a7d-98c4-4e5c544d0612";

        $response = Http::post($url, $send_data);

        $status = $response->status(); // 获取响应状态码
        if ($status != 200) {
            return $this->failure('发送失败');
        }
        return $this->success('ok');
    }

    public function getConnectDragon(Request $request)
    {
        if (config('app.env') == 'production') {
            $work_wechat_user = session('work_wechat_user');
            if (empty($work_wechat_user))
                return $this->failure('未授权企业微信');
            //用户企业微信信息
            $work_user_id = $work_wechat_user['raw']['userid'];
        } else {
            $work_user_id = "hankin";
        }
        $list = ConnectDragon::where('type', ConnectDragon::TYPE_INVITE)->where('work_id', $work_user_id)->orderByDesc('id')->get();

        return $this->success('ok', $list);
    }

    public function getConnectList(Request $request)
    {
        //查询统计数据
        $count = ConnectDragon::select(DB::raw('count(id) as count'), DB::raw('name'))->where('type', ConnectDragon::TYPE_INVITE)->orderBy('count', 'desc')->take(3)->groupBy('name')->get();
        $list = ConnectDragon::where('type', ConnectDragon::TYPE_INVITE)->orderByDesc('id')->paginate();
        return $this->success('ok', compact('list', 'count'));
    }
    public function deleteConnectDragon($id)
    {
        ConnectDragon::where('id', $id)->delete();
        return $this->success('ok');
    }

    public function clearConnectTable()
    {
        ConnectDragon::truncate();
        return $this->success('ok');
    }

    public function addAnnualMeetingUser(Request $request)
    {
        $name = $request->input('name');
        if (empty($name))
            return $this->failure('邀请人姓名不为空');
        $invite_name = $request->input('invite_name');
        if (empty($invite_name))
            return $this->failure('被邀请人姓名不为空');

        if (config('app.env') == 'production') {
            $work_wechat_user = session('work_wechat_user');
            if (empty($work_wechat_user))
                return $this->failure('未授权企业微信');
            //用户企业微信信息
            $work_user_id = $work_wechat_user['raw']['userid'];
        } else {
            $work_user_id = "hankin";
        }

        foreach ($invite_name as $value) {
            AnnualMeeting::create(['name' => $name, 'invite_name' => $value, 'work_id' => $work_user_id]);
        }

        //查询数据,再推送数据通知
        $list = AnnualMeeting::orderBy('id', 'desc')->get()?->toArray();

        $content = "友福年会报名：\r\n";

        $content = $content . "-----------------------\r\n";
        //        // 显示前3条数据
//        foreach (array_slice($list, 0, 3) as $index => $val) {
//            $content .= $index+1 . ":" . $val['name'] . "  " . $val['invite_name'] . "\r\n";
//        }
        $content = $content . "...\r\n...\r\n...\r\n";

        $count_invite = count($invite_name);
        $total_count = count($list);
        if ($total_count < 3) {
            $total_count = 3;
        }
        if ($count_invite > 3) {
            foreach ($invite_name as $k => $v) {
                $content .= $total_count - $count_invite + $k + 1 . "：" . $name . "  " . $v . "\r\n";
            }
        } else {
            // 显示后3条数据
            if ($total_count > 3) {
                foreach (array_slice($list, -3) as $k => $v) {
                    $content .= $total_count - 3 + $k + 1 . "：" . $v['name'] . "  " . $v['invite_name'] . "\r\n";
                }
            } else {
                foreach ($list as $k => $v) {
                    $content .= $k + 1 . "：" . $v['name'] . "  " . $v['invite_name'] . "\r\n";
                }
            }
        }
        $content = $content . "-----------------------\r\n" . "[我要参加](" . config('app.url') . "api/h5/add/annual/meeting/auth)\r\n";
        $content = $content . "-----------------------\r\n" . "[查看全部参加](" . config('app.url') . "/api/h5/all/annual/meeting/auth)";

        $send_data = [
            'msgtype' => 'markdown',
            'markdown' => [
                'content' => $content,
            ]
        ];

        //正式群
        $url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=905fe4d1-a681-4133-b847-0be2d290477c";
        //测试群
        if (!(config('app.env') == 'production')) {
            $url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=fe963d6e-2a67-487a-b0ac-3dbdc62f6f8c";
        }
        //        $url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=fe963d6e-2a67-487a-b0ac-3dbdc62f6f8c";
        //本地群
//        $url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=ec3c5836-42cf-4a7d-98c4-4e5c544d0612";

        $response = Http::post($url, $send_data);

        $status = $response->status(); // 获取响应状态码
        if ($status != 200) {
            return $this->failure('发送失败');
        }
        return $this->success('ok');
    }

    public function getAnnualMeetingUser(Request $request)
    {
        if (config('app.env') == 'production') {
            $work_wechat_user = session('work_wechat_user');
            if (empty($work_wechat_user))
                return $this->failure('未授权企业微信');
            //用户企业微信信息
            $work_user_id = $work_wechat_user['raw']['userid'];
        } else {
            $work_user_id = "hankin";
        }
        $query = AnnualMeeting::query()->orderBy('id', 'desc');
        $is_all = $request->get('is_all');
        if ($is_all) {
            $list = $query->paginate();
        } else {
            $list = $query->where('work_id', $work_user_id)->get();
        }

        return $this->success('ok', $list);
    }

    public function deleteAnnualMeetingUser($id)
    {
        AnnualMeeting::where('id', $id)->delete();
        return $this->success('ok');
    }

    public function getTalkList(Request $request)
    {
        try {
            $user = auth()->user();
            $keyword = $request->input('keyword');
            $status = $request->input('status');
            $query = Talk::query();
            $query->when($keyword, function ($query) use ($keyword) {
                $query->where('title', 'like', "%{$keyword}%");
            });
            $query->when(strlen($status) > 0, function ($query) use ($status) {
                $query->where('status', $status);
            });
            $list = $query->orderBy('status', 'asc')
                ->orderBy('id', 'desc')
                ->paginate();
            foreach ($list as $item) {
                $item->images = json_decode($item->images);
                $item->star = TalkStar::where('talk_id', $item->id)
                    ->count();
                $item->comment = TalkComment::where('talk_id', $item->id)
                    ->count();
                $item->is_star = TalkStar::where('talk_id', $item->id)->where('user_id', $user->id)->exists();
            }
            return $this->success('ok', $list);
        } catch (\Exception $e) {
            AddErrorLog::dispatch('getTalkList file:' . $e->getFile() . '|line:' . $e->getLine() . '|message:' . $e->getMessage())->onQueue('health');
            return $this->failure('获取失败');
        }
    }

    public function commentTalk(Request $request, $id)
    {
        try {
            $talk = Talk::findorFail($id);
            if ($talk->status == Talk::STATUS_CLOSE) {
                return $this->failure('话题已关闭');
            }
            $user = auth()->user();
            $comment = $request->input('content');
            $type = $request->input('type', 0);
            $comment_id = $request->input('comment_id');
            $model = TalkComment::create(['talk_id' => $id, 'user_id' => $user->id, 'content' => $comment, 'type' => $type, 'comment_id' => $comment_id]);

            $service_user = ServiceUser::where('user_id', $user->id)->first();


            if (mb_strlen($comment, 'UTF-8') > 20) {
                $comment = mb_substr($comment, 0, 20, 'UTF-8') . '...';
            }
            if (!$comment_id) {
                $content = "{$service_user->name}评论了话题【{$talk->title}】\r\n" . "————————————\r\n" . "{$service_user->name}回复: $comment\r\n" . "————————————\r\n" . "[点击查看/加入讨论详情](" . config('app.url') . "/work/#/h5/discussDetail?id={$talk->id})";

                $send_data = [
                    'msgtype' => 'markdown',
                    'markdown' => [
                        'content' => $content,
                    ]
                ];
                //正式群
                $url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=905fe4d1-a681-4133-b847-0be2d290477c";
                //测试群
                if (!(config('app.env') == 'production')) {
                    $url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=fe963d6e-2a67-487a-b0ac-3dbdc62f6f8c";
                }
                //                $url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=fe963d6e-2a67-487a-b0ac-3dbdc62f6f8c";
                //本地群
//            $url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=ec3c5836-42cf-4a7d-98c4-4e5c544d0612";
                $response = Http::post($url, $send_data);
                $status = $response->status(); // 获取响应状态码
                if ($status != 200) {
                    return $this->failure('发送失败');
                }
            }

            return $this->success('ok', $model);
        } catch (\Exception $e) {
            AddErrorLog::dispatch('commentTalk file:' . $e->getFile() . '|line:' . $e->getLine() . '|message:' . $e->getMessage())->onQueue('health');
            return $this->failure('评论失败');
        }
    }

    public function getTalkDetail($id)
    {
        try {
            $user = auth()->user();
            $detail = Talk::find($id);
            if (empty($detail)) {
                return $this->failure('该话题已删除');
            }
            $detail->images = json_decode($detail->images);
            $detail->star = TalkStar::where('talk_id', $detail->id)
                ->count();
            $detail->comment = TalkComment::where('talk_id', $detail->id)
                ->count();

            $detail->is_star = TalkStar::where('talk_id', $detail->id)->where('user_id', $user->id)->exists();
            $detail->browse_num = $detail->browse_num + 1;
            Talk::where('id', $id)->update(['browse_num' => $detail->browse_num]);
            return $this->success('ok', $detail);
        } catch (\Exception $e) {
            AddErrorLog::dispatch('getTalkDetail file:' . $e->getFile() . '|line:' . $e->getLine() . '|message:' . $e->getMessage())->onQueue('health');
            return $this->failure('获取失败');
        }
    }

    public function getTalkComment($id)
    {
        try {
            $user = auth()->user();
            $comment = TalkComment::with(['user', 'serviceUser'])->where('talk_id', $id)->where('type', TalkComment::TYPE_COMMENT)
                ->whereNull('comment_id')->orderByDesc('id')->paginate();
            foreach ($comment as $item) {
                $item->reply = TalkComment::with("user")->where('talk_id', $id)->where('type', TalkComment::TYPE_REPLY)
                    ->where('comment_id', $item->id)
                    ->orderByDesc('id')
                    ->get();
                if (!empty($item->reply)) {
                    foreach ($item->reply as $value) {
                        $value->is_self = false;
                        if ($user->id == $value->user_id) {
                            $value->is_self = true;
                        }
                        $reply_service = ServiceUser::where('user_id', $value->user_id)->first();
                        if (!empty($reply_service)) {
                            $value->user->name = $reply_service->name;
                            $value->user->mobile = $reply_service->mobile;
                        }
                    }
                }
                $item->is_self = false;
                if ($user->id == $item->user_id) {
                    $item->is_self = true;
                }
                $item->is_star = TalkStar::where('comment_id', $item->id)->where('user_id', $user->id)->exists();
                $item->star = TalkStar::where('comment_id', $item->id)->count();
                if (isset($item->serviceUser)) {
                    $item->user->name = $item->serviceUser->name;
                    $item->user->mobile = $item->serviceUser->mobile;
                }
            }
            return $this->success('ok', $comment);
        } catch (\Exception $e) {
            AddErrorLog::dispatch('getTalkComment file:' . $e->getFile() . '|line:' . $e->getLine() . '|message:' . $e->getMessage())->onQueue('health');
            return $this->failure('获取失败');
        }
    }

    public function browseTalk($id)
    {
        try {
            $detail = Talk::find($id);
            $detail->browse_num = $detail->browse_num + 1;
            $detail->save();
            return $this->success('ok');
        } catch (\Exception $e) {
            AddErrorLog::dispatch('visitTalk file:' . $e->getFile() . '|line:' . $e->getLine() . '|message:' . $e->getMessage())->onQueue('health');
            return $this->failure('浏览失败');
        }
    }
    public function clickStar(Request $request, $id)
    {
        try {
            $user = auth()->user();
            $comment_id = $request->input('comment_id');
            $exists = TalkStar::where('user_id', $user->id)->where('talk_id', $id)->where('comment_id', $comment_id)->exists();
            if ($exists) {
                TalkStar::where('user_id', $user->id)->where('talk_id', $id)->where('comment_id', $comment_id)->delete();
            } else {
                TalkStar::create(['user_id' => $user->id, 'talk_id' => $id, 'comment_id' => $comment_id]);
            }
            return $this->success('ok');
        } catch (\Exception $e) {
            AddErrorLog::dispatch('clickStar file:' . $e->getFile() . '|line:' . $e->getLine() . '|message:' . $e->getMessage())->onQueue('health');
            return $this->failure('点赞失败');
        }
    }

    public function deleteTalkComment($id)
    {
        try {
            DB::beginTransaction();
            $user = auth()->user();
            TalkComment::where('id', $id)->where('user_id', $user->id)->delete();
            //            TalkStar::where('')
            DB::commit();
            return $this->success('ok');
        } catch (\Exception $e) {
            DB::rollBack();
            AddErrorLog::dispatch('deleteTalkComment file:' . $e->getFile() . '|line:' . $e->getLine() . '|message:' . $e->getMessage())->onQueue('health');
            return $this->failure('点赞失败');
        }
    }
    public function updateUserInfo(Request $request)
    {
        try {
            DB::beginTransaction();
            $user = auth()->user();
            $user_info = User::find($user->id);
            if (empty($user_info)) {
                return $this->failure('用户不存在');
            }
            $service_user = ServiceUser::where('user_id', $user->id)->first();
            if ($request->has('name')) {
                $user_info->name = $request->input('name');
                if ($service_user) {
                    $service_user->name = $request->input('name');
                }
            }
            if ($request->has('avatar')) {
                $user_info->avatar = $request->input('avatar');
            }
            if ($request->has('mobile')) {
                if ($service_user) {
                    $service_user->mobile = $request->input('mobile');
                }
            }
            //先这样处理，时间太紧了
            if ($service_user) {
                $service_user->save();
            }
            $user_info->save();
            DB::commit();
            return $this->success('ok', $user_info);
        } catch (\Exception $e) {
            DB::rollBack();
            AddErrorLog::dispatch('updateUserInfo file:' . $e->getFile() . '|line:' . $e->getLine() . '|message:' . $e->getMessage())->onQueue('health');
            return $this->failure('更新失败');
        }
    }

    public function addInviteUserV3(Request $request)
    {
        $name = $request->input('name');
        if (empty($name))
            return $this->failure('邀请人姓名不为空');
        $invite_name = $request->input('invite_name');
        if (empty($invite_name))
            return $this->failure('被邀请人姓名不为空');

        if (config('app.env') == 'production') {
            $work_wechat_user = session('work_wechat_user');
            if (empty($work_wechat_user))
                return $this->failure('未授权企业微信');
            //用户企业微信信息
            $work_user_id = $work_wechat_user['raw']['userid'];
        } else {
            $work_user_id = "hankin";
        }

        foreach ($invite_name as $value) {
            ConnectDragon::create(['name' => $name, 'invite_name' => $value, 'work_id' => $work_user_id, 'type' => ConnectDragon::TYPE_MERCHANT]);
        }

        //查询统计数据
        $count = ConnectDragon::select(DB::raw('count(id) as count'), DB::raw('name'))->where('type', ConnectDragon::TYPE_MERCHANT)->orderBy('count', 'desc')->take(3)->groupBy('name')->get();
        //查询数据,再推送数据通知
        $list = ConnectDragon::where('type', ConnectDragon::TYPE_MERCHANT)->orderBy('id', 'desc')->get()?->toArray();

        $content = "友福批发商大会计划：\r\n";
        foreach ($count as $index => $val) {
            $rand = $index + 1;
            $emoji = "";
            if ($rand == 1) {
                $emoji = "👑";
            } elseif ($rand == 2) {
                $emoji = "💎";
            } elseif ($rand == 3) {
                $emoji = "🏆";
            }
            $content .= $emoji . ' ' . "第" . $rand . "名：" . $val->name . '  个数：' . $val->count . "\r\n";
        }
        $content = $content . "-----------------------\r\n";
        //        // 显示前10条数据
//        foreach (array_slice($list, 0, 10) as $index => $val) {
//            $content .= $index+1 . ":" . $val['name'] . "  " . $val['invite_name'] . "\r\n";
//        }
        $content = $content . "...\r\n...\r\n...\r\n";

        $count_invite = count($invite_name);
        $total_count = count($list);
        if ($count_invite > 3) {
            foreach ($invite_name as $k => $v) {
                $content .= $total_count - $count_invite + $k + 1 . "：" . $name . "  " . $v . "\r\n";
            }
        } else {
            // 显示后3条数据
            if ($total_count > 3) {
                foreach (array_slice($list, -3) as $k => $v) {
                    $content .= $total_count - 3 + $k + 1 . "：" . $v['name'] . "  " . $v['invite_name'] . "\r\n";
                }
            } else {
                foreach ($list as $k => $v) {
                    $content .= $k + 1 . ":" . $v['name'] . "  " . $v['invite_name'] . "\r\n";
                }
            }
        }
        $content = $content . "-----------------------\r\n" . "[我要邀请](" . config('app.url') . "/api/h5/invite/auth/v3)\r\n";
        $content = $content . "-----------------------\r\n" . "[查看全部邀请](" . config('app.url') . "/api/h5/view/invite/auth/v3)";

        $send_data = [
            'msgtype' => 'markdown',
            'markdown' => [
                'content' => $content,
            ]
        ];

        //正式群
        $url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=905fe4d1-a681-4133-b847-0be2d290477c";
        //测试群
        if (!(config('app.env') == 'production')) {
            $url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=fe963d6e-2a67-487a-b0ac-3dbdc62f6f8c";
        }
        //        $url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=fe963d6e-2a67-487a-b0ac-3dbdc62f6f8c";
        //本地群
//        $url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=ec3c5836-42cf-4a7d-98c4-4e5c544d0612";

        $response = Http::post($url, $send_data);

        $status = $response->status(); // 获取响应状态码
        if ($status != 200) {
            return $this->failure('发送失败');
        }
        return $this->success('ok');
    }

    public function getInviteV3()
    {
        if (config('app.env') == 'production') {
            $work_wechat_user = session('work_wechat_user');
            if (empty($work_wechat_user))
                return $this->failure('未授权企业微信');
            //用户企业微信信息
            $work_user_id = $work_wechat_user['raw']['userid'];
        } else {
            $work_user_id = "hankin";
        }
        $list = ConnectDragon::where('type', ConnectDragon::TYPE_MERCHANT)->where('work_id', $work_user_id)->orderByDesc('id')->get();

        return $this->success('ok', $list);
    }

    public function getInviteListV3(Request $request)
    {
        //查询统计数据
        $count = ConnectDragon::select(DB::raw('count(id) as count'), DB::raw('name'))
            ->where('type', ConnectDragon::TYPE_MERCHANT)->orderBy('count', 'desc')
            ->take(3)->groupBy('name')
            ->get();

        $list = ConnectDragon::where('type', ConnectDragon::TYPE_MERCHANT)->orderBy('id', 'desc')->paginate();
        return $this->success('ok', compact('list', 'count'));
    }

    public function deleteInviteV3($id)
    {
        ConnectDragon::where('id', $id)->delete();
        return $this->success('ok');
    }

    public function addInviteUserV2(Request $request)
    {
        $name = $request->input('name');
        if (empty($name))
            return $this->failure('邀请人姓名不为空');
        $invite_name = $request->input('invite_name');
        if (empty($invite_name))
            return $this->failure('被邀请人姓名不为空');


        if (config('app.env') == 'production') {
            $work_wechat_user = session('work_wechat_user');
            if (empty($work_wechat_user))
                return $this->failure('未授权企业微信');
            //用户企业微信信息
            $work_user_id = $work_wechat_user['raw']['userid'];
        } else {
            $work_user_id = "hankin";
        }

        foreach ($invite_name as $value) {
            ConnectDragon::create(['name' => $name, 'invite_name' => $value, 'work_id' => $work_user_id, 'type' => ConnectDragon::TYPE_HOT_POT]);
        }
        //查询数据,再推送数据通知
        $list = ConnectDragon::where('type', ConnectDragon::TYPE_HOT_POT)->orderBy('id', 'desc')->get()?->toArray();

        $content = "年三十围炉火锅团聚夜\r\n———————————\r\n每人带一食材,料理一起迎新年\r\n时间：2/9  17:00开始\r\n地点：3301\r\n———————————\r\n";

        $content = $content . "...\r\n...\r\n...\r\n";

        $count_invite = count($invite_name);
        $total_count = count($list);
        if ($count_invite > 3) {
            foreach ($invite_name as $k => $v) {
                $content .= $total_count - $count_invite + $k + 1 . ":" . $name . "  " . $v . "\r\n";
            }
        } else {
            // 显示后3条数据
            if ($total_count > 3) {
                foreach (array_slice($list, -3) as $k => $v) {
                    $content .= $total_count - 3 + $k + 1 . "：" . $v['name'] . "  " . $v['invite_name'] . "\r\n";
                }
            } else {
                foreach ($list as $k => $v) {
                    $content .= $k + 1 . "：" . $v['name'] . "  " . $v['invite_name'] . "\r\n";
                }
            }
        }
        $content = $content . "-----------------------\r\n" . "[我要参加](" . config('app.url') . "/api/h5/invite/auth/v2)\r\n";
        $content = $content . "-----------------------\r\n" . "[查看全部参加](" . config('app.url') . "/api/h5/view/invite/auth/v2)";

        $send_data = [
            'msgtype' => 'markdown',
            'markdown' => [
                'content' => $content,
            ]
        ];

        //正式群
        $url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=905fe4d1-a681-4133-b847-0be2d290477c";
        //测试群
        if (!(config('app.env') == 'production')) {
            $url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=fe963d6e-2a67-487a-b0ac-3dbdc62f6f8c";
        }
        //        $url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=fe963d6e-2a67-487a-b0ac-3dbdc62f6f8c";
        //本地群
//        $url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=ec3c5836-42cf-4a7d-98c4-4e5c544d0612";

        $response = Http::post($url, $send_data);

        $status = $response->status(); // 获取响应状态码
        if ($status != 200) {
            return $this->failure('发送失败');
        }
        return $this->success('ok');
    }

    public function getInviteV2(Request $request)
    {
        if (config('app.env') == 'production') {
            $work_wechat_user = session('work_wechat_user');
            if (empty($work_wechat_user))
                return $this->failure('未授权企业微信');
            //用户企业微信信息
            $work_user_id = $work_wechat_user['raw']['userid'];
        } else {
            $work_user_id = "hankin";
        }
        $list = ConnectDragon::where('type', ConnectDragon::TYPE_HOT_POT)->where('work_id', $work_user_id)->orderByDesc('id')->get();

        return $this->success('ok', $list);
    }

    public function getInviteListV2(Request $request)
    {
        //查询统计数据
        $count = ConnectDragon::select(DB::raw('count(id) as count'), DB::raw('name'))
            ->where('type', ConnectDragon::TYPE_HOT_POT)->orderBy('count', 'desc')
            ->take(3)->groupBy('name')
            ->get();

        $list = ConnectDragon::where('type', ConnectDragon::TYPE_HOT_POT)->orderBy('id', 'desc')->paginate();
        return $this->success('ok', compact('list', 'count'));
    }

    public function deleteInviteV2($id)
    {
        ConnectDragon::where('id', $id)->delete();
        return $this->success('ok');
    }

    public function addInviteUserV4(Request $request)
    {
        $name = $request->input('name');
        if (empty($name))
            return $this->failure('邀请人姓名不为空');
        $invite_name = $request->input('invite_name');
        if (empty($invite_name))
            return $this->failure('被邀请人姓名不为空');


        if (config('app.env') == 'production') {
            $work_wechat_user = session('work_wechat_user');
            if (empty($work_wechat_user))
                return $this->failure('未授权企业微信');
            //用户企业微信信息
            $work_user_id = $work_wechat_user['raw']['userid'];
        } else {
            $work_user_id = "hankin";
        }

        foreach ($invite_name as $value) {
            ConnectDragon::create(['name' => $name, 'invite_name' => $value, 'work_id' => $work_user_id, 'type' => ConnectDragon::TYPE_FRIEND]);
        }
        //查询数据,再推送数据通知
        $list = ConnectDragon::where('type', ConnectDragon::TYPE_FRIEND)->orderBy('id', 'desc')->get()?->toArray();

        $content = "3.9 16:00 友福批发商联谊会\r\n";

        $content = $content . "...\r\n...\r\n...\r\n";

        $count_invite = count($invite_name);
        $total_count = count($list);
        if ($count_invite > 3) {
            foreach ($invite_name as $k => $v) {
                $content .= $total_count - $count_invite + $k + 1 . ":" . $name . "  " . $v . "\r\n";
            }
        } else {
            // 显示后3条数据
            if ($total_count > 3) {
                foreach (array_slice($list, -3) as $k => $v) {
                    $content .= $total_count - 3 + $k + 1 . "：" . $v['name'] . "  " . $v['invite_name'] . "\r\n";
                }
            } else {
                foreach ($list as $k => $v) {
                    $content .= $k + 1 . "：" . $v['name'] . "  " . $v['invite_name'] . "\r\n";
                }
            }
        }
        $content = $content . "-----------------------\r\n" . "[参加接龙](" . config('app.url') . "/api/h5/invite/auth/v4)\r\n";
        $content = $content . "-----------------------\r\n" . "[查看接龙](" . config('app.url') . "/api/h5/view/invite/auth/v4)";

        $send_data = [
            'msgtype' => 'markdown',
            'markdown' => [
                'content' => $content,
            ]
        ];

        //正式群
        $url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=905fe4d1-a681-4133-b847-0be2d290477c";
        //测试群
        if (!(config('app.env') == 'production')) {
            $url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=fe963d6e-2a67-487a-b0ac-3dbdc62f6f8c";
        }
        //        $url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=fe963d6e-2a67-487a-b0ac-3dbdc62f6f8c";
        //本地群
//        $url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=ec3c5836-42cf-4a7d-98c4-4e5c544d0612";

        $response = Http::post($url, $send_data);

        $status = $response->status(); // 获取响应状态码
        if ($status != 200) {
            return $this->failure('发送失败');
        }
        return $this->success('ok');
    }

    public function getInviteV4(Request $request)
    {
        if (config('app.env') == 'production') {
            $work_wechat_user = session('work_wechat_user');
            if (empty($work_wechat_user))
                return $this->failure('未授权企业微信');
            //用户企业微信信息
            $work_user_id = $work_wechat_user['raw']['userid'];
        } else {
            $work_user_id = "hankin";
        }
        $list = ConnectDragon::where('type', ConnectDragon::TYPE_FRIEND)->where('work_id', $work_user_id)->orderByDesc('id')->get();

        return $this->success('ok', $list);
    }

    public function getInviteListV4(Request $request)
    {
        //查询统计数据
        $count = ConnectDragon::select(DB::raw('count(id) as count'), DB::raw('name'))
            ->where('type', ConnectDragon::TYPE_FRIEND)->orderBy('count', 'desc')
            ->take(3)->groupBy('name')
            ->get();

        $list = ConnectDragon::where('type', ConnectDragon::TYPE_FRIEND)->orderBy('id', 'desc')->paginate();
        return $this->success('ok', compact('list', 'count'));
    }

    public function deleteInviteV4($id)
    {
        ConnectDragon::where('id', $id)->delete();
        return $this->success('ok');
    }
}
