package com.ruoyi.web.controller.system;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.User;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServiceUtil;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.ss.menu.domain.Menu;
import com.ruoyi.ss.menu.domain.MenuVO;
import com.ruoyi.ss.menu.service.IMenuService;
import com.ruoyi.ss.user.domain.UserVO;
import com.ruoyi.ss.user.service.IUserService;
import com.ruoyi.ss.withdraw.mapper.WithdrawMapper;
import com.ruoyi.ss.withdraw.service.IWithdrawService;
import com.ruoyi.system.service.ISysMenuService;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Set;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@Slf4j
@RestController
public class SysLoginController extends BaseController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IMenuService appMenuService;

    @Autowired
    private IWithdrawService withdrawService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid(),"1",null);
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * app账号密码登录
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/appLogin")
    public AjaxResult appLogin(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), null,
                null,"2",loginBody.getJsCode());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取token用于测试
     *
     * @param userId 用户id
     * @return 结果
     */
    @GetMapping("/getToken")
    public AjaxResult getToken(Long userId)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.getToken(userId);
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        User user = userService.selectUserById(getUserId());
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }


    /**
     * 获取app用户信息(简化信息)
     *
     * @return 用户信息
     */
    @GetMapping("getAppInfo")
    public AjaxResult getAppInfo()
    {
        AjaxResult ajax = AjaxResult.success();
        UserVO user = userService.selectAppUserById(getUserId());
        if(ObjectUtil.isNotNull(user)){
            BigDecimal withdrawableAmount = userService.getWithdrawAbleAmount(user);
            user.setWithdrawalAmount(withdrawableAmount);
        }
        BigDecimal totalWithdrawAmount = withdrawService.cumulativeWithdrawalAmount(user.getUserId());
        if(ObjectUtil.isNull(totalWithdrawAmount)){
            totalWithdrawAmount = BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
        }
        user.setTotalWithdrawAmount(totalWithdrawAmount);
        // 根据用户角色查询所有菜单
        ajax.put("user", user);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }


    @PostMapping("/appCodeLogin")
    public AjaxResult appCodeLogin(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.appCodeLogin(loginBody);
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 微信登录
     */
    @PostMapping("/wxlogin")
    public AjaxResult wxlogin(String mobileCode,String jsCode) {
        log.info("【微信登录/wxlogin】areaId参数：【mobileCode={}】", mobileCode);
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.wxloing(mobileCode,jsCode);
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 根据openid静默登录
     */
    @PostMapping("/loginByopenid")
    public AjaxResult loginByopenid(String jsCode) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.loginByopenid(jsCode);
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 忘记密码
     */
    @PostMapping("/forgotPassword")
    public AjaxResult forgotPassword(@RequestBody LoginBody loginBody)
    {
        log.info("忘记密码:loginBody:【{}】", JSON.toJSONString(loginBody));
        return AjaxResult.success(loginService.forgetAppPwd(loginBody));
    }

}
