package com.sptg.gateway.controller.permissions;

import com.sptg.common.core.beans.ResultBean;
import com.sptg.common.core.beans.ResultEnum;
import com.sptg.common.core.constant.HttpConstant;
import com.sptg.common.core.constant.SysLogConstant;
import com.sptg.common.core.util.CookieUtils;
import com.sptg.common.core.util.WebUtils;
import com.sptg.common.security.annotation.Security;
import com.sptg.common.security.service.SecurityServiceInterface;
import com.sptg.permissions.api.dto.LoginDto;
import com.sptg.permissions.api.entity.Account;
import com.sptg.permissions.api.feigns.AccountAuthenticationFeign;
import com.sptg.permissions.api.feigns.AccountFeign;
import com.sptg.statistics.api.entity.SysOperationLog;
import com.sptg.statistics.api.feigns.SysOperationLogFeign;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;

/**
 * title: AuthenticationController
 * package: com.sptg.gateway.controller.permissions
 * description: 用户认证-控制器
 *
 *                  
 *                 
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/permissions/authentication")
public class AuthenticationController {

    /* -------------------------------------------------- 接口注入 -------------------------------------------------- */

    private final AccountAuthenticationFeign accountAuthenticationFeign;
    private final SecurityServiceInterface<Account> securityServiceInterface;
    private final SysOperationLogFeign sysOperationLogFeign;
    private final AccountFeign accountFeign;

    /* --------------------------------------------------- 控制器 --------------------------------------------------- */

    /**
     * 功能描述: 登陆接口
     * @param dto 登陆信息
     * @return ResultBean
     *                  
     *                       
     */
    @PostMapping(value = "/login")
    public ResultBean login(LoginDto dto){
        ResultBean<Account> resultBean = this.accountAuthenticationFeign.login(dto);
        //  判断是否登陆成功
        if (!resultBean.getCode().equals(ResultEnum.SUCCESS.getCode())){
            return resultBean;
        }
        //  用户信息
        Account account = resultBean.getData();
        //  创建用户令牌
        String token = this.securityServiceInterface.createUserToken(account);
        //  生成cookie
        CookieUtils.setCookie(HttpConstant.ACCESS_TOKEN,token);
        //  登录日志
        SysOperationLog sysOperationLog = new SysOperationLog(SysLogConstant.LOGIN_EVENT,WebUtils.getIp(),account);

        account.setLastLoginDate(new Date());
        account.setLastLoginIp(WebUtils.getIp());

        ResultBean<Boolean> updateResult = accountFeign.updateById(account);

        sysOperationLogFeign.info(sysOperationLog);
        //  判断是否记住密码
        if (dto.getRememberMe() == 1){
            int overOutTime = 60 * 60 * 24;
            String content = System.currentTimeMillis() + overOutTime + ":" + account.getId() + ":" + account.getLoginPwd();
            CookieUtils.setCookie(HttpConstant.REMEMBER_ME,content,overOutTime);
        }
        return new ResultBean<>(ResultEnum.SUCCESS, token);
    }

    /**
     * 功能描述: 退出登陆
     * @return 视图  --->> 返回登陆页面
     *                  
     *                       
     */
    @Security
    @GetMapping(value = "/logout")
    public ModelAndView logout(){
        Account account = this.securityServiceInterface.getOnLineUser();
        this.securityServiceInterface.removeUserToken();
        CookieUtils.deleteCookie(HttpConstant.REMEMBER_ME);
        //登出日志
        SysOperationLog sysOperationLog = new SysOperationLog(SysLogConstant.OUT_LOGIN_EVENT,WebUtils.getIp(),account);
        sysOperationLogFeign.info(sysOperationLog);
        return new ModelAndView("redirect:/permissions/authentication/login");
    }

    /**
     * 修改密码
     * @return
     */
    @Security
    @GetMapping(value = "/modifyPwd")
    public ModelAndView modifyPwd(){
        return new ModelAndView("permissions/password-change");
    }

    /**
     * 获取当前登录账号信息
     * @return
     */
    @Security
    @GetMapping(value = "/getCurrentAccount")
    public ResultBean getCurrentAccount(){
        //  获取当前在线用户信息
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        return new ResultBean(ResultEnum.SUCCESS, onLineUser);
    }


    /**
     * 功能描述: 登陆视图
     * @return ModelAndView
     *                  
     * date:  2018/10/29 23:17
     */
    @GetMapping(value = "/login")
    public ModelAndView login(){
        //  判断是否已登录
        if (null != this.securityServiceInterface.getOnLineUser()){
            return new ModelAndView("redirect:/");
        }
        //  判断是否使用记住我功能
        String value = CookieUtils.getCookieValue(HttpConstant.REMEMBER_ME);
        if (StringUtils.hasText(value)){
            try {
                String[] array = value.split(":");
                int len = 3;
                if (len == array.length) {
                    //  判断是否超时
                    long overOutTime = Long.parseLong(array[0]);
                    if (System.currentTimeMillis() < overOutTime) {
                        long id = Long.parseLong(array[1]);
                        //  自动登陆
                        Account account = this.accountAuthenticationFeign.authLogin(new LoginDto(id, array[2]));
                        if (null != account) {
                            //  登陆成功 创建用户令牌
                            String token = this.securityServiceInterface.createUserToken(account);
                            //  生成cookie
                            CookieUtils.setCookie(HttpConstant.ACCESS_TOKEN,token);
                            //  重定向至首页
                            return new ModelAndView("redirect:/");
                        }
                    }
                }
            }catch (Exception e){
                //  自动登陆时出现异常,打印日志并删除自动记住我cookie
                log.error(e.getMessage());
                CookieUtils.deleteCookie(HttpConstant.REMEMBER_ME);
            }
        }
        return new ModelAndView("permissions/login");
    }

}
