package com.casic.missiles.controller;

import com.casic.missiles.core.base.controller.BaseController;
import com.casic.missiles.core.base.response.ResponseData;
import com.casic.missiles.core.base.response.SuccessResponseData;
import com.casic.missiles.core.common.constant.Const;
import com.casic.missiles.core.log.LogManager;
import com.casic.missiles.core.log.factory.LogTaskFactory;
import com.casic.missiles.core.shiro.ShiroKit;
import com.casic.missiles.core.shiro.ShiroUser;
import com.casic.missiles.core.util.RSAUtils;
import com.casic.missiles.core.util.ToolUtil;
import com.casic.missiles.modular.contant.PermissionContant;
import com.casic.missiles.modular.system.dto.LoginResult;
import com.casic.missiles.modular.system.model.User;
import com.casic.missiles.modular.system.service.IUserService;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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 javax.servlet.http.HttpServletRequest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

/**
 * 仅为mock登录使用
 */
@Controller
@RequestMapping("/app")
public class CardLoginController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(CardLoginController.class);

    @Autowired
    private IUserService userService;

    /**
     * cardByToken
     */
    @GetMapping("/tokenByCard")
    @ResponseBody
    public Object cardByToken(HttpServletRequest request, String card) {
        super.getSession().setAttribute(PermissionContant.IS_APP, true);
        SuccessResponseData resultData = new SuccessResponseData();
        if (ToolUtil.isEmpty(card)) {
            return ResponseData.error("用户身份证号不能为空");
        }
        Subject currentUser = ShiroKit.getSubject();

        try {
            Map<String, String> key = RSAUtils.genKeyPair();
            ShiroKit.getSession().setAttribute(PermissionContant.PRIVATE_KEY, key.get(RSAUtils.RSAPrivateKey));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        User user = userService.getByAccount(card);
        if (user == null) {
            return ResponseData.error("该账户暂未同步,请联系管理员");
        }

        //查询用户名密码
        UsernamePasswordToken token = new UsernamePasswordToken(user.getAccount(), Const.DEFAULT_PWD.toCharArray());
        token.setRememberMe(false);
        try {
            currentUser.login(token);

        } catch (Exception e) {
            e.printStackTrace();
        }
        ShiroUser shiroUser = ShiroKit.getUser();
        super.getSession().setAttribute("shiroUser", shiroUser);
        super.getSession().setAttribute("username", shiroUser.getAccount());
        String devId = null;
        if(ToolUtil.isNotEmpty(shiroUser.getDevices())){
            devId =  shiroUser.getDevices().get(0).getImei();
        }

//        LogFactory.createLoginLog(LogType.LOGIN, shiroUser.getId(), "登录成功", null);
        super.getSession().setAttribute(PermissionContant.SESSION_KEY, shiroUser.getId());

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

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

}
