<?php
declare (strict_types = 1);

namespace app\admin\controller\api;

use think\admin\Controller;
use think\facade\Db;
use think\facade\Cache;

/**
 * 代理商接口
 */
class Agent extends Controller
{
    /**
     * 代理商登录
     */
    public function login()
    {
        try {
            $data = $this->_vali([
                'username.require' => '用户名不能为空',
                'password.require' => '密码不能为空'
            ]);

            // 查询代理商
            $agent = Db::name('cursor_agents')
                ->where('username', $data['username'])
                ->find();

            if (empty($agent)) {
                return json(['code' => 400, 'msg' => '用户名或密码错误']);
            }

            // 验证密码
            if (!password_verify($data['password'], $agent['password'])) {
                return json(['code' => 400, 'msg' => '用户名或密码错误']);
            }

            // 检查状态
            if ($agent['status'] != 1) {
                return json(['code' => 400, 'msg' => '账号已被禁用']);
            }

            // 生成token
            $token = md5($agent['id'] . time() . rand(1000, 9999));
            
            // 存储token，有效期7天
            Cache::set('agent_token_' . $token, $agent['id'], 7 * 24 * 3600);

            // 更新登录信息
            Db::name('cursor_agents')
                ->where('id', $agent['id'])
                ->update([
                    'last_login_time' => date('Y-m-d H:i:s'),
                    'last_login_ip' => $this->request->ip(),
                    'updated_at' => date('Y-m-d H:i:s')
                ]);

            // 返回登录信息
            return json([
                'code' => 200,
                'msg' => '登录成功',
                'data' => [
                    'token' => $token,
                    'agent' => [
                        'id' => $agent['id'],
                        'username' => $agent['username'],
                        'nickname' => $agent['nickname'],
                        'level' => $agent['level'],
                        'balance' => $agent['balance'],
                        'commission_rate' => $agent['commission_rate']
                    ]
                ]
            ]);

        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 验证token
     */
    protected function checkToken()
    {
        $token = $this->request->header('token');
        if (empty($token)) {
            return json(['code' => 401, 'msg' => '请先登录']);
        }

        $agentId = Cache::get('agent_token_' . $token);
        if (empty($agentId)) {
            return json(['code' => 401, 'msg' => '登录已过期，请重新登录']);
        }

        return $agentId;
    }

    /**
     * 获取代理商信息
     */
    public function info()
    {
        try {
            $agentId = $this->checkToken();
            if (!is_numeric($agentId)) {
                return $agentId; // 返回错误信息
            }

            $agent = Db::name('cursor_agents')
                ->where('id', $agentId)
                ->find();

            if (empty($agent)) {
                return json(['code' => 400, 'msg' => '代理商不存在']);
            }

            // 获取激活码统计
            $codeStats = Db::name('cursor_agent_codes')
                ->where('agent_id', $agentId)
                ->field([
                    'COUNT(*) as total_codes',
                    'SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) as settled_codes',
                    'SUM(commission) as total_commission',
                    'SUM(CASE WHEN status = 1 THEN commission ELSE 0 END) as settled_commission'
                ])
                ->find();

            // 获取未使用的激活码
            $unusedCodes = Db::name('cursor_agent_codes')
                ->alias('ac')
                ->join('cursor_activation_codes c', 'ac.code_id = c.id')
                ->where('ac.agent_id', $agentId)
                ->where('c.is_used', 0)
                ->field('c.code, c.days, ac.price')
                ->select()
                ->toArray();

            return json([
                'code' => 200,
                'msg' => '获取成功',
                'data' => [
                    'agent' => [
                        'id' => $agent['id'],
                        'username' => $agent['username'],
                        'nickname' => $agent['nickname'],
                        'level' => $agent['level'],
                        'balance' => $agent['balance'],
                        'total_income' => $agent['total_income'],
                        'commission_rate' => $agent['commission_rate'],
                        'last_login_time' => $agent['last_login_time']
                    ],
                    'stats' => [
                        'total_codes' => $codeStats['total_codes'] ?? 0,
                        'settled_codes' => $codeStats['settled_codes'] ?? 0,
                        'total_commission' => $codeStats['total_commission'] ?? 0,
                        'settled_commission' => $codeStats['settled_commission'] ?? 0
                    ],
                    'unused_codes' => $unusedCodes
                ]
            ]);

        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 获取代理商的激活码列表
     */
    public function codes()
    {
        try {
            $agentId = $this->checkToken();
            if (!is_numeric($agentId)) {
                return $agentId;
            }

            $page = input('page/d', 1);
            $limit = input('limit/d', 20);
            $status = input('status');

            $query = Db::name('cursor_agent_codes')
                ->alias('ac')
                ->join('cursor_activation_codes c', 'ac.code_id = c.id')
                ->where('ac.agent_id', $agentId);

            if (isset($status)) {
                $query = $query->where('c.is_used', intval($status));
            }

            $total = $query->count();
            $list = $query->field([
                'c.code',
                'c.days',
                'c.is_used',
                'c.used_at',
                'c.used_by',
                'ac.price',
                'ac.commission',
                'ac.status as settle_status',
                'ac.created_at'
            ])
            ->page($page, $limit)
            ->order('ac.created_at desc')
            ->select()
            ->toArray();

            return json([
                'code' => 200,
                'msg' => '获取成功',
                'data' => [
                    'list' => $list,
                    'total' => $total,
                    'page' => $page,
                    'limit' => $limit
                ]
            ]);

        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage()]);
        }
    }
} 