package com.rj.controller;

import com.rj.entity.LbUser;
import com.rj.service.ILbUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/lbUser")
@Tag(name = "LB 用户", description = "lb_user 增删改查与分页")
public class LbUserController {

    @Autowired
    private ILbUserService lbUserService;

    @PostMapping("/add")
    @Operation(summary = "新增")
    public ResponseEntity<Map<String, Object>> add(
            @Parameter(description = "实体（id 为外部用户 id，需调用方指定）", required = true)
            @RequestBody LbUser entity) {
        Map<String, Object> result = lbUserService.add(entity);
        Boolean success = (Boolean) result.get("success");
        if (success != null && success) {
            return ResponseEntity.ok(result);
        }
        return ResponseEntity.badRequest().body(result);
    }

    @PutMapping("/update")
    @Operation(summary = "编辑")
    public ResponseEntity<Map<String, Object>> update(
            @Parameter(description = "实体", required = true) @RequestBody LbUser entity) {
        Map<String, Object> result = lbUserService.update(entity);
        Boolean success = (Boolean) result.get("success");
        if (success != null && success) {
            return ResponseEntity.ok(result);
        }
        return ResponseEntity.badRequest().body(result);
    }

    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除")
    public ResponseEntity<Map<String, Object>> delete(
            @Parameter(description = "主键（用户 id）", required = true) @PathVariable Long id) {
        Map<String, Object> result = lbUserService.deleteById(id);
        Boolean success = (Boolean) result.get("success");
        if (success != null && success) {
            return ResponseEntity.ok(result);
        }
        return ResponseEntity.badRequest().body(result);
    }

    @GetMapping("/get/{id}")
    @Operation(summary = "根据ID查询")
    public ResponseEntity<Map<String, Object>> getById(
            @Parameter(description = "用户 id", required = true) @PathVariable Long id) {
        LbUser data = lbUserService.getById(id);
        if (data == null) {
            return ResponseEntity.badRequest().body(Map.of("success", false, "message", "记录不存在"));
        }
        return ResponseEntity.ok(Map.of("success", true, "message", "查询成功", "data", data));
    }

    @GetMapping("/list")
    @Operation(summary = "分页查询")
    public ResponseEntity<Map<String, Object>> list(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String tenantId,
            @RequestParam(required = false) Long pid,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String nickname,
            @RequestParam(required = false) String mobile,
            @RequestParam(required = false) String invite,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) Integer isVip,
            @RequestParam(required = false) Integer isResell,
            @RequestParam(required = false) Integer level,
            @RequestParam(required = false) String pname,
            @Parameter(description = "注册开始时间，格式：yyyy-MM-dd HH:mm:ss")
            @RequestParam(required = false) String joinTimeStart,
            @Parameter(description = "注册结束时间，格式：yyyy-MM-dd HH:mm:ss")
            @RequestParam(required = false) String joinTimeEnd,
            @Parameter(description = "更新开始时间，格式：yyyy-MM-dd HH:mm:ss")
            @RequestParam(required = false) String updatedAtStart,
            @Parameter(description = "更新结束时间，格式：yyyy-MM-dd HH:mm:ss")
            @RequestParam(required = false) String updatedAtEnd) {
        Map<String, Object> result =
                lbUserService.pageQuery(
                        current,
                        size,
                        tenantId,
                        pid,
                        username,
                        nickname,
                        mobile,
                        invite,
                        status,
                        isVip,
                        isResell,
                        level,
                        pname,
                        joinTimeStart,
                        joinTimeEnd,
                        updatedAtStart,
                        updatedAtEnd);
        Boolean success = (Boolean) result.get("success");
        if (success != null && success) {
            return ResponseEntity.ok(result);
        }
        if (result.get("message") != null && result.get("message").toString().contains("格式错误")) {
            return ResponseEntity.badRequest().body(result);
        }
        return ResponseEntity.internalServerError().body(result);
    }

    @PostMapping("/sync-from-hxr")
    @Operation(
            summary = "从 hxrd 后台同步用户",
            description =
                    "分页调用 /app/admin/user/select（每页 limit=90），将 data 解析为 LbUser 后立即 upsert 到 lb_user；"
                            + "需配置 hxr.admin.cookie 或 phpsid")
    public ResponseEntity<Map<String, Object>> syncFromHxr(
            @Parameter(description = "租户 id", required = true) @RequestParam String tenantId) {
        Map<String, Object> result = lbUserService.syncFromHxrAdmin(tenantId);
        Boolean success = (Boolean) result.get("success");
        if (success != null && success) {
            return ResponseEntity.ok(result);
        }
        return ResponseEntity.badRequest().body(result);
    }
}
