// logger.fatal(request);
if request.Method<>'POST' then
begin
    print('{"code": 400, "msg": "只允许使用POST方法提交请求。"}');
    exit;
end; 
var login_ip := request.RemoteIP;
// 处理代理场景：如果使用了反向代理，可从X-Real-IP或X-Forwarded-For获取真实IP
// 注意：生产环境需验证代理的可靠性，避免伪造IP
if request.Headers['X-Real-IP']<>'' then
    login_ip := request.Headers['X-Real-IP']
else if request.Headers['X-Forwarded-For']<>'' then
    // X-Forwarded-For格式：客户端IP, 代理1IP, 代理2IP...
    login_ip := string(request.Headers['X-Forwarded-For']).split(',')[0];
include('/v1/user/jwt');
var token := json.parse(jwt_token(request.Headers['Authorization']));
if not token.verify then
begin
    print('{"code": 401, "msg": "授权信息无效，'+token.msg+'"}');
    exit;
end;
var data := json.NewObject;
try
    data := json.parse(request.Params);
except
    begin
        print('{"code": 400, "msg": "请求体不是有效的JSON格式"}');
        exit;
    end;
end;
// 验证必要参数
if not regex.ismatch(data.deleteID,'^[1-9]\d*$') and not regex.ismatch(data.fname,'\W{2,255}') then
begin
    print('{"code": 400, "msg": "参数错误！"}');
    exit;
end;
// 配置数据库连接
include('/conn.cfg');
var conn:='mydb';
var formatted_pwd := pwd_fmt(token.msg.UserPwd);
var sql := 'SELECT * FROM tEmployee WHERE FClose=0 AND FUserName=:p1 AND FUserPwd=:p2';
var query := json.parse(db.query(conn,sql,token.msg.UserName,formatted_pwd));
var exec:= json.NewObject; // 预留
if query.code<>200 then
begin
    print(format('{"code": 400, "msg": "%s"}',[query.msg]));
    exit;
end;
if query.data.length()<>1 then
begin
    print('{"code": 403, "msg": "用户名、密码错误，或已被禁用！"}');
    logger.warn(format('用户验证拒绝：IP[%s]用户名[%s]密码[%s]',[login_ip,token.msg.UserName,token.msg.UserPwd]));
    exit;
end;
var level:=query.data[0].FLevel; // 用户权限
var uid:=query.data[0].FID;
if level<>2 then
begin
    print('{"code": 403, "msg": "权限不足！"}');
    logger.warn(format('用户[%s]ID[%d]想新增字典，因权限不足被阻止。',[token.msg.UserName,uid]));
    exit;
end;
// 删除数据
if regex.ismatch(data.deleteID,'^[1-9]\d*$') then
begin
    sql := 'SELECT FID, FName FROM tDictionary WHERE FID=:p1';
    query := json.parse(db.query(conn,sql,data.deleteID));
    if query.data.length()<>1 then
    begin
        print('{"code": 400, "msg": "该记录已被删除，请刷新数据查看！"}');
        logger.warn(format('删除目标不存在：deleteID=[%d]，操作人[%s]',[data.deleteID,token.msg.UserName]));
        exit;
    end;
    exec:=json.parse(db.exec(conn,'DELETE FROM tDictionary WHERE FID=:p1',data.deleteID));
    if (exec.code=200) and (exec.rowcount=1) then
    begin
        print('{"code": 200, "msg": "success"}');
        logger.info(format('用户[%s]ID[%d]删除了字典[%s]ID[%d]。',
            [token.msg.userName,uid,query.data[0].FName,data.deleteID]));
    end else begin
        print('{"code": 500, "msg": "'+exec.msg+'"}');
        logger.info('字典删除操作发生异常：'+exec.msg);
    end;
end else begin
    // 编辑数据
    if not regex.ismatch(data.fid,'^[0-9]\d*$')
    or not regex.ismatch(data.fname,'.{2,255}')
    or not regex.ismatch(data.fcode,'.{1,255}')
    or not regex.ismatch(data.fcoding,'.{1,255}')
    then
    begin
        print('{"code": 403, "msg": "参数错误！"}');
        exit;        
    end;
    // 处理新增字典（fid=0）
    if data.fid=0 then
    begin
        sql:=#'INSERT INTO tDictionary(FName, FCode, FCoding, FNote)
                VALUES (:p1, :p2, :p3, :p4)';
        exec:=json.parse(db.exec(conn,sql,data.fname,data.fcode,data.fcoding,data.fnote));
        if (exec.code=200) and (exec.rowcount=1) then
        begin
            print('{"code": 200, "msg": "success"}');
            logger.info(format('用户[%s]ID[%d]新增了字典[%s]。',
                [token.msg.userName,uid,data.fname]));
        end else begin
            print('{"code": 500, "msg": "'+exec.msg+'"}');
            logger.info('新增字典时发生异常：'+exec.msg);
        end;
    end else begin
        // 处理编辑字典（fid≠0）
        sql:=#'UPDATE tDictionary
            SET FName=:p2, FCode=:p3, FCoding=:p4, FNote=:p5
            WHERE FID = :p1';
        exec:=json.parse(db.exec(conn,sql,data.fid,data.fname,data.fcode,data.fcoding,data.fnote));
        if (exec.code=200) and (exec.rowcount=1) then
        begin
            print('{"code": 200, "msg": "success"}');
            logger.info(format('用户[%s]ID[%d]编辑了字典[%s]ID[%d]。',
                [token.msg.userName,uid,data.fname,data.fid]));
        end else begin
            print('{"code": 500, "msg": "'+exec.msg+'"}');
            logger.info('编辑字典时发生异常：'+exec.msg);
        end;
    end;
end;