package com.mini.capi.sys.App;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mini.capi.biz.domain.ApiMenus;
import com.mini.capi.biz.domain.ApiModule;
import com.mini.capi.biz.domain.ApiUser;
import com.mini.capi.biz.service.ApiMenusService;
import com.mini.capi.biz.service.ApiModuleService;
import com.mini.capi.biz.service.ApiUserService;
import com.mini.capi.model.ApiResult;
import com.mini.capi.model.auth.Result;
import com.mini.capi.sys.domain.ModuleMenuDTO;
import com.mini.capi.utils.KeyUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import lombok.Data;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/Sys/login")
public class loginController {


    @Resource
    private ApiUserService userService;

    @Resource
    private ApiModuleService moduleService;

    @Resource
    private ApiMenusService menusService;


    @Data
    public static class LoginParams implements Serializable {
        private String account;
        private String password;
    }


    @Data
    public static class ApiUserDTO implements Serializable {

        private String userId;

        /**
         * 登录名称
         */
        private String username;

        /**
         * 用户名称
         */
        private String uname;

        private String token;

        // 构造方法（从实体类转换）
        public ApiUserDTO(ApiUser apiUser, String token) {
            this.userId = apiUser.getUserId();
            this.username = apiUser.getApiUser();
            this.uname = apiUser.getUname();
            this.token = token;
        }
    }

    /**
     * 密码校验（生产环境需替换为加密比对）
     */
    private boolean verifyPassword(String rawPassword, String encodedPassword) {
        return Objects.equals(rawPassword, encodedPassword);
    }


    /**
     * 用户登录
     */
    @PostMapping("/userLogin")
    public Result login(@RequestBody LoginParams user, HttpSession session) {
        try {
            QueryWrapper<ApiUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("api_user", user.getAccount())
                    .eq("ustatus", 1);
            ApiUser apiUser = userService.getOne(queryWrapper);
            if (apiUser == null) {
                return Result.error(101, "账户不存在");
            }
            if (!verifyPassword(user.getPassword(), apiUser.getApiPswd())) {
                // 可记录登录失败日志，用于后续风控
                return Result.error(102, "账户或密码错误");
            }
            session.setAttribute("userInfo", apiUser);
            ApiUserDTO userDTO = new ApiUserDTO(apiUser, KeyUtil.ObjKey(32, 0));
            return Result.success("登录成功", userDTO);
        } catch (Exception e) {
            return Result.error(103, "登录失败，请稍后重试");
        }
    }

    @PostMapping("/userLogout")
    public Result loginOut(HttpSession session) {
        try {
            session.removeAttribute("userInfo");   // 只清 token
            session.invalidate();
            return Result.error(200, "退出成功");
        } catch (Exception e) {
            return Result.error(500, "退出失败");
        }
    }


    @GetMapping("/getModules")
    public ApiResult<List<ModuleMenuDTO>> getModules() {
        List<ApiModule> apiModules = moduleService.list();
        List<ModuleMenuDTO> menuDTOList = new ArrayList<>();
        for (ApiModule apiModule : apiModules) {
            ModuleMenuDTO menuDTO = new ModuleMenuDTO(apiModule.getModuleName(), apiModule.getModuleCode(), apiModule.getCIcon(), apiModule.getCHref(), getMenus(apiModule.getModuleCode()));
            menuDTOList.add(menuDTO);
        }
        return ApiResult.success(menuDTOList);
    }


    public List<ApiMenus> getMenus(String moduleCode) {
        QueryWrapper<ApiMenus> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("module_code", moduleCode);
        return menusService.list(queryWrapper);
    }
}
