package com.casic.missiles.controller;

import cn.hutool.core.util.StrUtil;
import com.casic.missiles.core.application.enums.LoginType;
import com.casic.missiles.core.base.controller.BaseController;
import com.casic.missiles.core.model.auth.AuthUser;
import com.casic.missiles.core.model.auth.CasicCustomToken;
import com.casic.missiles.core.shiro.ShiroKit;
import com.casic.missiles.core.util.RSAUtils;
import com.casic.missiles.model.response.SuccessResponseData;
import com.casic.missiles.modular.domain.constants.PermissionConstants;
import com.casic.missiles.modular.interfaces.log.LogManager;
import com.casic.missiles.modular.interfaces.log.factory.LogTaskFactory;
import com.casic.missiles.modular.system.dto.LoginSuccessDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.security.NoSuchAlgorithmException;
import java.util.Map;

import static com.casic.missiles.core.util.HttpContext.getIp;


/**
 * 仅为mock登录使用
 *
 * @author lenovo
 */
@Controller
@RequestMapping("/route")
@Slf4j
public class MockController extends BaseController {

    /**
     * 获取mockToken
     */
    @GetMapping("/mockToken")
    @ResponseBody
    public Object mockToken(String username, String password) {
        super.getSession().setAttribute(PermissionConstants.IS_APP, false);
        SuccessResponseData resultData = new SuccessResponseData();
        if (StrUtil.hasEmpty(username, password)) {
            username = "admin";
            password = "111111";
        }
        Subject currentUser = ShiroKit.getSubject();

        try {
            Map<String, String> key = RSAUtils.genKeyPair();
            ShiroKit.getSession().setAttribute(PermissionConstants.PRIVATE_KEY, key.get(RSAUtils.RSAPrivateKey));

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        //token自定义
        CasicCustomToken token = new CasicCustomToken(username, password);
        token.setType(LoginType.PASSWORD);
        token.setRememberMe(false);

        try {
            currentUser.login(token);
        } catch (Exception e) {
            e.printStackTrace();
        }
        AuthUser shiroUser = ShiroKit.getUser();
        super.getSession().setAttribute("shiroUser", shiroUser);
        super.getSession().setAttribute("username", shiroUser.getAccount());
        super.getSession().setAttribute(PermissionConstants.SESSION_KEY, shiroUser.getId());

        LogManager.me().executeLog(LogTaskFactory.loginLog(shiroUser.getId(), getIp()));

        ShiroKit.getSession().setAttribute("sessionFlag", true);
        resultData.setData(new LoginSuccessDTO(ShiroKit.getSession().getId().toString(), null));
        resultData.setMessage("登录成功");
        return resultData;
    }
}
