package com.ruoyi.web.controller.system;

import java.util.Date;
import java.util.List;
import java.util.Set;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.AccessFromType;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.dz.domain.DzCards;
import com.ruoyi.dz.service.IDzCardsService;
import com.ruoyi.enums.CardTimeStatus;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.service.CommService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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 com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysMenuService;

import javax.servlet.http.HttpServletRequest;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@Api(tags = "系统-登陆")
@RestController
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private CommService commService;

    private final ISysUserService userService;

    private final IDzCardsService cardsService;

    private final ISysConfigService configService;

    public SysLoginController(ISysUserService userService, IDzCardsService cardsService, ISysConfigService configService) {
        this.userService = userService;
        this.cardsService = cardsService;
        this.configService = configService;
    }

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("login")
    @ApiOperation("登陆")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        // 生成令牌
        AjaxResult ajax = loginService.login(loginBody.getMobile(), loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(), loginBody.getUuid(),AccessFromType.back.name());
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    @ApiOperation("个人信息")
    public AjaxResult getInfo(HttpServletRequest request)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        if (!loginUser.getPermissions().equals(permissions))
        {
            loginUser.setPermissions(permissions);
            tokenService.refreshToken(loginUser);
        }
        AjaxResult ajax;
        //H5 wechat frontApp均需要菜单
        String type = request.getHeader("type");
        if(AccessFromType.isFrontApp(type)||AccessFromType.isH5(type)||AccessFromType.isWechat(type)){
            ajax = AjaxResult.success(user);
            ajax.put("card", loginUser.getCard());
            String appConfig = configService.selectConfigByKey("app.common.config");
            com.alibaba.fastjson.JSONObject json = com.alibaba.fastjson.JSONObject.parseObject(appConfig);
            ajax.put("appConfig", json);
        } else {
            ajax = AjaxResult.success();
            ajax.put("user", user);
        }
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        ajax.put("isDefaultModifyPwd", commService.initPasswordIsModify(user.getPwdUpdateDate()));
        ajax.put("isPasswordExpired", commService.passwordIsExpiration(user.getPwdUpdateDate()));
        return ajax;
    }

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

    /**
     * 用户注销，之后不能再登录
     * @param loginBody
     * @return
     */
    @Log(title = "用户注销", businessType = BusinessType.LOGOUT)
    @PostMapping("/logoutPhysical")
    public AjaxResult logout(@RequestBody LoginBody loginBody) {
        SysUser currentUser = SecurityUtils.getLoginUser().getUser();
        userService.deleteUserById(currentUser.getUserId());
        //卡重置为已过期
        if(null!=currentUser.getCardId()){
            DzCards card = cardsService.selectDzCardsByCardId(currentUser.getCardId());
            card.setTimeStatus(CardTimeStatus.Expire.getVal());
            card.setUpdateTime(new Date());
            cardsService.updateDzCards(card);
        }
        return AjaxResult.success("注销成功",currentUser);
    }
}
