<?php

namespace app\admin\service;

use app\model\AdminModel;
use app\model\AuthGroupAccessModel;
use app\model\AwsIvsModel;
use app\model\CustomerRelationalModel;
use app\model\UserModel;

class AgentService extends AdminBaseService
{

    // 代理列表
    public function index()
    {
        try {
//            $agentUserId = env('AGENT.AGENT_GROUP_ID');
//            $agentAdminUserIds = AuthGroupAccessModel::where('group_id', $agentUserId)->column('uid');
            $roleId = 10;
            $agentAdminUser = AdminModel::where('role_id', 'in', $roleId)->field('id,user_name,nick_name,email,mobile,status,invite_code')->select();
            $rows = [];
            if (!$agentAdminUser->isEmpty()) {
                foreach ($agentAdminUser as $item) {
                    $rows[] = [
                        'id' => $item['id'],
                        'username' => $item['user_name'],
                        'nickname' => $item['nick_name'],
                        'email' => $item['email'] ?? '-',
                        'mobile' => $item['mobile'] ?? '-',
                        'status' => $item['status'],
                        'invite_code' => $item['invite_code'],
                    ];
                }
            }
            return $this->toData('0', 'SUCCESS', ['list' => $rows, 'total' => count($rows)]);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }
    }

    // 代理用户
    public function user($param)
    {
        try {
            if (empty($param['agent_id'])) {
                return $this->toData('0', 'SUCCESS', ['list' => []]);
            }

            $userList = UserModel::where('agent_id', 'in', [0, $param['agent_id']])->where('parent_id', 0)
                ->order('user_id', 'desc')
                ->select();
            $rows = [];
            if (!$userList->isEmpty()) {
                foreach ($userList as $item) {
                    $rows[] = [
                        'id' => $item['user_id'],
                        'email' => $item['email'],
                        'user_no' => $item['user_no'],
                        'status' => $item['agent_id'] == $param['agent_id'],
                        'agent_id' => $param['agent_id'],
                    ];
                }
            }
            return $this->toData('0', 'SUCCESS', ['list' => $rows, 'total' => count($rows)]);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }
    }

    public function manager($param)
    {
        try {
            if (empty($param['id']) || !is_numeric($param['id'])) {
                return $this->toData('1', '参错错误', ['list' => []]);
            }

            if (empty($param['agent_id']) || !is_numeric($param['agent_id'])) {
                return $this->toData('1', '参错错误', ['list' => []]);
            }

            $user = UserModel::where('user_id', $param['id'])->find();
            if (empty($user)) {
                return $this->toData('1', '用户不存在', ['list' => []]);
            }

            if ($user['parent_id'] != 0) {
                return $this->toData('1', '只能绑定顶层用户', ['list' => []]);
            }

            // 判断代理是否有效
            $admin = AdminModel::where('id', $param['agent_id'])->find();
            $roleId = 10;
            if (empty($admin) || $admin['role_id'] != $roleId) {
                return $this->toData('1', '代理不存在', ['list' => []]);
            }

//            $agentUserId = env('AGENT.AGENT_GROUP_ID');
//            $agentAdminUserIds = AuthGroupAccessModel::where('group_id', $agentUserId)->column('uid');
//            if(!in_array($param['agent_id'], $agentAdminUserIds)){
//                return $this->toData('1', '代理不存在', ['list' => []]);
//            }

            // 未绑定 直接绑定
            if ($user->agent_id == 0) {
                UserModel::update(['agent_id' => $param['agent_id']], ['user_id' => $param['id']]);
                return $this->toData('0', 'SUCCESS', []);
            }

            // 取消绑定
            if ($user->agent_id == $param['agent_id']) {
                UserModel::update(['agent_id' => 0], ['user_id' => $param['id']]);
                return $this->toData('0', 'SUCCESS', []);
            }

            return $this->toData('1', '该用户已被其他代理绑定, 请先取消绑定', []);

        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }
    }

    public function addUser($param)
    {
        try {
            if (empty($param['agent_id']) || !is_numeric($param['agent_id'])) {
                return $this->toData('1', '参错错误');
            }

            if (empty($param['user_id']) || !is_numeric($param['user_id'])) {
                return $this->toData('1', '参错错误');
            }

            $user = UserModel::where('user_id', $param['user_id'])->find();
            if (empty($user)) {
                return $this->toData('1', '用户不存在');
            }

            if ($user['parent_id'] != 0) {
                return $this->toData('1', '只能绑定顶层用户');
            }

            // 判断代理是否有效
            $admin = AdminModel::where('id', $param['agent_id'])->find();
            $roleId = 10;
            if (empty($admin) || $admin['role_id'] != $roleId) {
                return $this->toData('1', '代理不存在');
            }
            
            UserModel::update(['agent_id' => $param['agent_id']], ['user_id' => $param['user_id']]);
            return $this->toData('0', 'SUCCESS', []);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }
    }

    public function customerList($param)
    {
        try {
            if (empty($param['page']) || !is_numeric($param['page'])) {
                return $this->toData('1', '参错错误');
            }

            // 角色ID
            $roleId = 11;
            // 代理ID
            $agentId = 0;
            if (isset($param['agent_id']) && is_numeric($param['agent_id'])) {
                $agentId = $param['agent_id'];
            }
            $list = AdminModel::when($agentId, function ($query) use ($agentId) {
                $query->where('parent_id', $agentId)->order('id', 'desc');    //查询代理下的客服列表
            }, function ($query) use($roleId) {
                $query->where('role_id', $roleId)->order('id', 'desc');       //查询所有客服列表
            })->paginate([
                'list_rows' => 15,        // 每页显示 10 条
                'page' => $param['page'], // 使用前端传递的页码
            ]);

            return $this->toData('0', 'SUCCESS', [
                'list' => $list->items(), // 当前页的数据
                'page' => $list->currentPage(), // 当前页码
                'total' => $list->total(), // 总记录数
                'last_page' => $list->lastPage(), // 最后一页页码
                'agent_id' => $agentId,
            ]);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }
    }

    public function customerUser($param)
    {
        try {
            if (empty($param['customer_id']) || !is_numeric($param['customer_id'])) {
                return $this->toData('1', '参错错误');
            }
            if (empty($param['page']) || !is_numeric($param['page'])) {
                return $this->toData('1', '参错错误');
            }
            // 查询当前客服下的用户
            $list = CustomerRelationalModel::where('customer_id', $param['customer_id'])->order('id', 'desc')->paginate([
                'list_rows' => $param['limit'] ?? 15,
                'page' => $param['page'], // 使用前端传递的页码
            ]);
            $userIds = array_column($list->items(), 'user_id');  // 获取当前页的用户id
            // 根据user_id查询用户列表
            $userDetails = [];
            if ($userIds) {
                $userDetails = UserModel::whereIn('user_id', $userIds)->select()->toArray();
            }

            return $this->toData('0', 'SUCCESS', [
                'list' => $list->items(), // 当前页的数据
                'user_details' => $userDetails,
                'page' => $list->currentPage(), // 当前页码
                'total' => $list->total(), // 总记录数
                'last_page' => $list->lastPage(), // 最后一页页码
            ]);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }
    }

    public function awsIvsList($param)
    {
        try {
            if (empty($param['page']) || !is_numeric($param['page'])) {
                return $this->toData('1', '参错错误');
            }

            if (isset($param['title'])) {
                $list = AwsIvsModel::where('title', $param['title'])->order('id', 'desc')->paginate([
                    'list_rows' => 15,
                    'page' => $param['page'],
                ]);
            } else {
                $list = AwsIvsModel::order('id', 'desc')->paginate([
                    'list_rows' => 15,
                    'page' => $param['page'],
                ]);
            }

            return $this->toData('0', 'SUCCESS', [
                'list' => $list->items(), // 当前页的数据
                'page' => $list->currentPage(), // 当前页码
                'total' => $list->total(), // 总记录数
                'last_page' => $list->lastPage(), // 最后一页页码
            ]);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }
    }

    public function awsIvsAdd($param)
    {
        try {
            if (empty($param['title'])) {
                return $this->toData('1', 'Missing param title');
            }
            if (empty($param['anchor_name'])) {
                return $this->toData('1', 'Missing param anchor_name');
            }
            if (empty($param['desc'])) {
                return $this->toData('1', 'Missing param desc');
            }
            if (empty($param['push_url'])) {
                return $this->toData('1', 'Missing param push_url');
            }
            if (empty($param['secret_key'])) {
                return $this->toData('1', 'Missing param secret_key');
            }
            if (empty($param['play_url'])) {
                return $this->toData('1', 'Missing param play_url');
            }
            if (empty($param['agent_id'])) {
                return $this->toData('1', 'Missing param agent_id');
            }
            //判断一个代理下只能有一个推流配置
            $ckInfo = AwsIvsModel::where('agent_id', $param['agent_id'])->find();
            if ($ckInfo) {
                return $this->toData('1', '一个代理下只能配置一个推流信息');
            }
            //保存推流配置
            $res = AwsIvsModel::create([
                'title' => $param['title'],
                'anchor_name' => $param['anchor_name'],
                'avatar' => $param['avatar'],
                'desc' => $param['desc'],
                'push_url' => $param['push_url'],
                'secret_key' => $param['secret_key'],
                'play_url' => $param['play_url'],
                'agent_id' => $param['agent_id']
            ]);
            return $this->toData('0', 'SUCCESS', ['id' => $res->id]);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }
    }

    public function awsIvsEdit($param)
    {
        try {
            if (empty($param['id'])) {
                return $this->toData('1', 'Missing param id');
            }
            if (empty($param['title']) || empty($param['anchor_name']) || empty($param['desc']) || empty($param['push_url']) || empty($param['secret_key']) || empty($param['play_url']) || empty($param['agent_id'])) {
                return $this->toData('1', 'Parameter error');
            }
            // 检查是否存在数据
            $ckInfo = AwsIvsModel::where('id', $param['id'])->find();
            if (empty($ckInfo)) {
                return $this->toData('1', '编辑的数据不存在');
            }
            $ckInfo->title = $param['title'];
            $ckInfo->anchor_name = $param['anchor_name'];
            $ckInfo->avatar = $param['avatar'];
            $ckInfo->desc = $param['desc'];
            $ckInfo->push_url = $param['push_url'];
            $ckInfo->secret_key = $param['secret_key'];
            $ckInfo->play_url = $param['play_url'];
            $ckInfo->save();
            return $this->toData('1', 'Successful');
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }
    }
}