<?php
declare (strict_types = 1);

namespace app\admin\controller\api;

use app\manager\model\Member as MemberModel;
use think\admin\Controller;
use think\facade\Db;


/**
 * 会员接口管理
 */
class Member extends Controller
{
    /**
     * 验证会员状态
     */
    public function check()
    {
        // 接收参数
        $keyword = trim(input('keyword', ''));
        if (empty($keyword)) {
            return json([
                'code' => 1,
                'msg' => '请输入查询关键字'
            ]);
        }

        // 查询会员信息 (email = xxx OR order_id = xxx)
        $member = MemberModel::whereOr('email', '=', $keyword)
            ->whereOr('order_id', '=', $keyword)
            ->find();

        if (empty($member)) {
            return json([
                'code' => 1,
                'msg' => '会员不存在'
            ]);
        }

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

        // 检查有效期
        if (strtotime($member['expire_time']) < time()) {
            return json([
                'code' => 1,
                'msg' => '会员已过期'
            ]);
        }

        // 检查使用次数
        if ($member['usage_limit'] > 0 && $member['used_count'] >= $member['usage_limit']) {
            return json([
                'code' => 1,
                'msg' => '使用次数已达上限'
            ]);
        }

        // 更新使用次数和最后登录信息
        $member->used_count = $member->used_count + 1;
        $member->last_login_time = date('Y-m-d H:i:s');
        $member->last_login_ip = $this->request->ip();
        $member->save();

        // 返回成功
        return json([
            'code' => 0,
            'msg' => '验证通过',
            'data' => [
                'email' => $member['email'],
                'order_id' => $member['order_id'],
                'expire_time' => $member['expire_time'],
                'usage_limit' => $member['usage_limit'],
                'used_count' => $member['used_count'],
                'last_login_time' => $member['last_login_time']
            ]
        ]);
    }

    /**
     * 激活码验证并激活
     * @return void
     */
    public function activate()
    {
        try {
            // 验证激活码
            $code = input('code');
            if (empty($code)) {
                return json(['code' => 400, 'msg' => '激活码不能为空']);
            }

            // 获取设备信息
            $machineId = input('machine_id', '');
            if (empty($machineId)) {
                return json(['code' => 400, 'msg' => '设备ID不能为空']);
            }

            // 收集设备详细信息
            $deviceInfo = [
                'machine_id' => $machineId,
                'os' => input('os', ''),                    // 操作系统信息
                'device_name' => input('device_name', ''),  // 设备名称
                'ip' => $this->request->ip(),               // IP地址
                'user_agent' => $this->request->header('user-agent', ''), // UA信息
                'location' => input('location', '')         // 地理位置（如果有）
            ];

            // 获取激活码信息
            $activation = Db::name('cursor_activation_codes')
                ->where('code', $code)
                ->where('is_used', 0)
                ->find();

            if (empty($activation)) {
                return json(['code' => 400, 'msg' => '激活码无效或已被使用']);
            }

            // 开启事务
            Db::startTrans();
            try {
                // 标记新激活码为已使用
                Db::name('cursor_activation_codes')
                    ->where('id', $activation['id'])
                    ->update([
                        'is_used' => 1,
                        'used_at' => date('Y-m-d H:i:s'),
                        'used_by' => $machineId,
                        'device_info' => json_encode($deviceInfo)
                    ]);

                Db::commit();

                // 获取该设备所有的激活记录
                $activations = Db::name('cursor_activation_codes')
                    ->where('used_by', '=', $machineId)
                    ->where('is_used', '=', 1)
                    ->order('used_at desc')
                    ->select()
                    ->toArray();

                // 计算总天数
                $totalDays = array_sum(array_column($activations, 'days'));

                // 计算最终到期时间
                $now = time();
                $firstActivationTime = strtotime($activations[count($activations)-1]['used_at']); // 第一次激活时间
                $expireTime = $firstActivationTime + ($totalDays * 24 * 3600); // 总天数转换为秒数
                $daysLeft = ceil(($expireTime - $now) / 86400);

                // 返回成功信息
                $result = [
                    'code' => 200,
                    'msg' => '激活成功',
                    'data' => [
                        'expire_time' => date('Y-m-d H:i:s', $expireTime),
                        'total_days' => $totalDays,
                        'added_days' => $activation['days'],
                        'days_left' => $daysLeft,
                        'machine_id' => $machineId,
                        'device_info' => $deviceInfo,
                        'activation_time' => date('Y-m-d H:i:s'),
                        'activation_records' => array_map(function($record) {
                            return [
                                'code' => $record['code'],
                                'days' => $record['days'],
                                'activation_time' => $record['used_at'],
                                'device_info' => json_decode($record['device_info'], true)
                            ];
                        }, $activations)
                    ]
                ];

                return json($result);

            } catch (\Exception $e) {
                Db::rollback();
                throw $e;
            }

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

    /**
     * 获取会员状态
     */
    public function status()
    {
        try {
            // 获取设备ID
            $machineId = input('machine_id', '');
            if (empty($machineId)) {
                return json(['code' => 400, 'msg' => '设备ID不能为空']);
            }

            try {
                // 获取Redis实例
                $redis = cache('redis');
                $cacheKey = "device_status:{$machineId}";
                
                // 尝试获取缓存
                if ($redis && $statusInfo = $redis->get($cacheKey)) {
                    return json(json_decode($statusInfo, true));
                }
            } catch (\Exception $e) {
                // Redis异常时记录日志但继续执行
                trace("Redis异常: " . $e->getMessage(), 'error');
            }

            // 获取该设备所有的激活记录
            $activations = Db::name('cursor_activation_codes')
                ->where('used_by', '=', $machineId)
                ->where('is_used', '=', 1)
                ->field(['days', 'used_at', 'code', 'device_info'])
                ->order('used_at desc')
                ->select()
                ->toArray();

            if (empty($activations)) {
                $result = [
                    'code' => 401,
                    'msg' => '未激活',
                    'data' => [
                        'status' => 'inactive',
                        'expire_time' => '',
                        'total_days' => 0,
                        'days_left' => 0,
                        'activation_records' => []
                    ]
                ];
                // 未激活状态缓存1分钟
                try {
                    if ($redis) {
                        $redis->set($cacheKey, json_encode($result), 60);
                    }
                } catch (\Exception $e) {
                    trace("Redis缓存写入异常: " . $e->getMessage(), 'error');
                }
                return json($result);
            }

            // 计算总天数
            $totalDays = array_sum(array_column($activations, 'days'));

            // 计算最终到期时间
            $now = time();
            $firstActivationTime = strtotime($activations[count($activations)-1]['used_at']); 
            $expireTime = $firstActivationTime + ($totalDays * 24 * 3600);
            $daysLeft = ceil(($expireTime - $now) / 86400);

            // 判断是否过期
            if ($daysLeft <= 0) {
                $result = [
                    'code' => 401,
                    'msg' => '已过期',
                    'data' => [
                        'status' => 'expired',
                        'expire_time' => date('Y-m-d H:i:s', $expireTime),
                        'total_days' => $totalDays,
                        'days_left' => 0,
                        'machine_id' => $machineId,
                        'activation_records' => array_map(function($record) {
                            return [
                                'code' => $record['code'],
                                'days' => $record['days'],
                                'activation_time' => $record['used_at'],
                                'device_info' => json_decode($record['device_info'], true)
                            ];
                        }, $activations)
                    ]
                ];
                // 过期状态缓存1分钟
                try {
                    if ($redis) {
                        $redis->set($cacheKey, json_encode($result), 60);
                    }
                } catch (\Exception $e) {
                    trace("Redis缓存写入异常: " . $e->getMessage(), 'error');
                }
                return json($result);
            }

            // 正常状态返回
            $result = [
                'code' => 200,
                'msg' => '正常',
                'data' => [
                    'status' => 'active',
                    'expire_time' => date('Y-m-d H:i:s', $expireTime),
                    'total_days' => $totalDays,
                    'days_left' => $daysLeft,
                    'machine_id' => $machineId,
                    'activation_records' => array_map(function($record) {
                        return [
                            'code' => $record['code'],
                            'days' => $record['days'],
                            'activation_time' => $record['used_at'],
                            'device_info' => json_decode($record['device_info'], true)
                        ];
                    }, $activations)
                ]
            ];
            
            // 正常状态缓存5分钟
            try {
                if ($redis) {
                    $redis->set($cacheKey, json_encode($result), 300);
                }
            } catch (\Exception $e) {
                trace("Redis缓存写入异常: " . $e->getMessage(), 'error');
            }
            return json($result);
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => '系统异常，请稍后重试'
            ]);
        }
    }
} 