<?php
namespace web\ambap;

// 确保引入必要的工具类（根据实际项目路径调整）
require_once dirname(__FILE__) . '/../../ciy/db.php';
require_once dirname(__FILE__) . '/../../ciy/post.php';
require_once dirname(__FILE__) . '/../../ciy/sql.php';

class member {
    // 接口入口：通过 act 参数路由到不同方法
    public static function index() {
        // 1. 解决跨域问题
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
        header("Access-Control-Allow-Headers: Content-Type, X-Requested-With");
        header("Content-Type: application/json; charset=utf-8");
        
        // 处理 OPTIONS 预检请求
        if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
            http_response_code(200);
            exit;
        }

        // 2. 安全获取 act 参数
        $act = isset($_REQUEST['act']) ? trim($_REQUEST['act']) : '';
        switch($act) {
            case 'member.list':
                self::json_list();
                break;
            case 'member.add':
                self::json_add();
                break;
            case 'member.edit':
                self::json_edit();
                break;
            case 'member.detail':
                self::json_detail();
                break;
            case 'member.del':
                self::json_del();
                break;
            case 'member.audit':
                self::json_audit();
                break;
            default:
                self::err('无效的接口动作：' . $act);
                break;
        }
    }

    // 1. 获取成员列表（适配当前 db.php 的 ciy\sql 语法）
    public static function json_list() {
        global $db;
        $post = new \ciy\post();
        $page = $post->getint('page', 1);
        $pageSize = $post->getint('pageSize', 15);
        $offset = ($page - 1) * $pageSize;

        // 构建查询条件（通过 ciy\sql 的构造参数指定字段）
        $csql = new \ciy\sql('lab_user', 'id, name, mobile, usertitle, stpstatus, sex, education, email, avatar, addtimes');
        $csql->limit($offset, $pageSize); // 分页：偏移量、每页条数
        $csql->order('addtimes DESC');
        
        // 核心修改：使用 db.php 的 get 方法（$rowcount=-1 自动查总数）
        $rowcount = -1;
        $list = $db->get($csql, $rowcount);

        // 处理查询失败
        if ($list === false) {
            return self::err('获取列表失败：' . $db->error);
        }

        // 格式化返回数据
        $retList = [];
        foreach ($list as $item) {
            $retList[] = [
                'id' => intval($item['id']),
                'name' => $item['name'] ?? '',
                'mobile' => $item['mobile'] ?? '',
                'usertitle' => intval($item['usertitle']),
                'stpstatus' => intval($item['stpstatus']),
                'sex' => intval($item['sex']),
                'education' => intval($item['education'] ?? 50),
                'email' => $item['email'] ?? '',
                'avatar' => $item['avatar'] ?? '/static/avatar-default.png',
                'addtimes' => intval($item['addtimes'])
            ];
        }

        echo json_encode([
            'code' => 1,
            'list' => $retList,
            'total' => $rowcount,
            'page' => $page,
            'pageSize' => $pageSize
        ], JSON_UNESCAPED_UNICODE);
    }

    // 2. 新增成员（适配当前 db.php）
    public static function json_add() {
        global $db;
        $post = new \ciy\post();
        
        // 获取表单数据
        $name = trim($post->get('name', ''));
        $mobile = trim($post->get('mobile', ''));
        $usertitle = $post->getint('usertitle', 10);
        $stpstatus = $post->getint('stpstatus', 30);
        $sex = $post->getint('sex', 90);
        $education = $post->getint('education', 50);
        $email = trim($post->get('email', ''));
        $password = trim($post->get('password', ''));

        // 基础验证
        if (empty($name)) return self::err('请输入姓名');
        if (empty($mobile)) return self::err('请输入手机号');
        if (!preg_match('/^1[3-9]\d{9}$/', $mobile)) return self::err('手机号格式错误');
        if (empty($password)) return self::err('请设置密码');
        if (strlen($password) < 6) return self::err('密码长度不少于6位');

        // 检查手机号是否已注册
        $csql = new \ciy\sql('lab_user', 'id');
        $csql->where('mobile', $mobile);
        $exist = $db->getone($csql);
        if (is_array($exist)) return self::err('该手机号已注册：' . $mobile);

        // 组装数据
        $data = [
            'name' => $name,
            'mobile' => $mobile,
            'usertitle' => $usertitle,
            'stpstatus' => $stpstatus,
            'sex' => $sex,
            'education' => $education,
            'email' => $email,
            'password' => $password,
            'userlevel' => 10,
            'trytime' => 0,
            'logintimes' => self::tostamp(),
            'addtimes' => self::tostamp(),
            'ip' => self::getip(),
            'laborgid' => 1,
            'sn' => 'LAB-' . date('Ymd') . '-' . rand(1000, 9999),
            'totalpnt' => 0,
            'dvotecnt' => 0,
            'updatetime' => self::tostamp()
        ];

        // 插入数据
        $csql = new \ciy\sql('lab_user');
        $insertId = $db->insert($csql, $data);
        if ($insertId === false) {
            return self::err('新增失败：' . $db->error);
        }

        echo json_encode([
            'code' => 1, 
            'msg' => '新增成功',
            'id' => $insertId
        ], JSON_UNESCAPED_UNICODE);
    }

    // 3. 编辑成员（适配当前 db.php）
    public static function json_edit() {
        global $db;
        $post = new \ciy\post();
        
        $id = $post->getint('id');
        $name = trim($post->get('name', ''));
        $usertitle = $post->getint('usertitle', 10);
        $stpstatus = $post->getint('stpstatus', 30);
        $sex = $post->getint('sex', 90);
        $education = $post->getint('education', 50);
        $email = trim($post->get('email', ''));

        // 参数验证
        if (empty($id)) return self::err('参数错误：缺少成员ID');
        if (empty($name)) return self::err('请输入姓名');

        // 组装更新数据
        $data = [
            'name' => $name,
            'usertitle' => $usertitle,
            'stpstatus' => $stpstatus,
            'sex' => $sex,
            'education' => $education,
            'email' => $email,
            'updatetime' => self::tostamp()
        ];

        // 更新数据
        $csql = new \ciy\sql('lab_user');
        $csql->where('id', $id);
        $result = $db->update($csql, $data);
        if ($result === false) {
            return self::err('修改失败：' . $db->error);
        }

        echo json_encode([
            'code' => 1, 
            'msg' => '修改成功'
        ], JSON_UNESCAPED_UNICODE);
    }

    // 4. 获取成员详情（适配当前 db.php）
    public static function json_detail() {
        global $db;
        $post = new \ciy\post();
        $id = $post->getint('id');

        if (empty($id)) return self::err('参数错误：缺少成员ID');

        // 查询详情（通过 ciy\sql 构造参数指定字段）
        $csql = new \ciy\sql('lab_user', 'id, name, mobile, usertitle, stpstatus, sex, education, email');
        $csql->where('id', $id);
        $item = $db->getone($csql);

        if (!is_array($item)) return self::err('成员不存在或已删除');

        // 格式化返回数据
        $data = [
            'id' => intval($item['id']),
            'name' => $item['name'] ?? '',
            'mobile' => $item['mobile'] ?? '',
            'usertitle' => intval($item['usertitle']),
            'stpstatus' => intval($item['stpstatus']),
            'sex' => intval($item['sex']),
            'education' => intval($item['education'] ?? 50),
            'email' => $item['email'] ?? ''
        ];

        echo json_encode([
            'code' => 1, 
            'data' => $data
        ], JSON_UNESCAPED_UNICODE);
    }

    // 5. 删除成员（适配当前 db.php）
    public static function json_del() {
        global $db;
        $post = new \ciy\post();
        $id = $post->getint('id');

        if (empty($id)) return self::err('参数错误：缺少成员ID');

        // 物理删除
        $csql = new \ciy\sql('lab_user');
        $csql->where('id', $id);
        $result = $db->delete($csql);

        if ($result === false) {
            return self::err('删除失败：' . $db->error);
        }

        echo json_encode([
            'code' => 1, 
            'msg' => '删除成功'
        ], JSON_UNESCAPED_UNICODE);
    }

    // 6. 审核成员（适配当前 db.php）
    public static function json_audit() {
        global $db;
        $post = new \ciy\post();
        $id = $post->getint('id');
        $status = $post->getint('status');

        if (empty($id)) return self::err('参数错误：缺少成员ID');
        if (!in_array($status, [10,20,30,40,50])) return self::err('无效的状态值');

        $data = ['stpstatus' => $status];
        $csql = new \ciy\sql('lab_user');
        $csql->where('id', $id);
        $result = $db->update($csql, $data);
        if ($result === false) {
            return self::err('审核失败：' . $db->error);
        }

        echo json_encode([
            'code' => 1, 
            'msg' => '审核成功'
        ], JSON_UNESCAPED_UNICODE);
    }

    // 通用错误返回
    private static function err($msg) {
        echo json_encode([
            'code' => 0, 
            'errmsg' => $msg
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }

    // 兼容tostamp函数
    private static function tostamp() {
        return isset($GLOBALS['tostamp']) ? $GLOBALS['tostamp']() : time() * 1000;
    }

    // 兼容getip函数
    private static function getip() {
        if (isset($_SERVER['HTTP_X_REAL_IP'])) {
            return $_SERVER['HTTP_X_REAL_IP'];
        } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            return $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
            return $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';
        }
    }
}

// 执行入口
member::index();
?>