package com.kuyuntech.vrv.platform.controller.auth;


import com.kuyuntech.vrv.coreapi.bean.core.UserBean;
import com.kuyuntech.vrv.coreapi.service.core.AuthService;
import com.kuyuntech.vrv.coreapi.service.core.UserService;
import com.kuyuntech.vrv.coreapi.service.core.VerifyCodeService;
import com.kuyuntech.vrv.coreservice.util.core.ValidateCodeGenerator;
import com.wbspool.fastboot.core.common.bean.ResponseBean;
import com.wbspool.fastboot.core.common.builder.MapBuilder;
import com.wbspool.fastboot.core.web.result.ParamErrorResultBuilder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 登录验证
 *
 * @author
 * @description
 */
@RestController
public class AuthController {

    @Autowired
    private AuthService authService;
    @Autowired
    private UserService userService;

    @Value("${fastboot.auth.login-verify-code:true}")
    private Boolean verifyCodeCheck;

    final VerifyCodeService verifyCodeService;

    public AuthController(VerifyCodeService verifyCodeService) {
        this.verifyCodeService = verifyCodeService;
    }


    /**
     * 获取验证码图片
     *
     * @return
     */
    @RequestMapping
    public void verifyCode(Integer width, Integer height, HttpServletRequest request, HttpServletResponse response) throws IOException {

        String verifyCode = ValidateCodeGenerator.generateVerifyCode(4);
        Long createTime = System.currentTimeMillis();
        System.out.println(createTime);
        System.out.println("VerifyCode: " + verifyCode);


        request.getSession().setAttribute("verifyCode", verifyCode);
        request.getSession().setAttribute("createTime", createTime);

    }

    @RequestMapping
    public Object login(@Validated UserBean userBean, String encrypt, Errors errors, HttpServletRequest request) {


        //校验验证码是否正确
        if (this.verifyCodeCheck) {

            if (StringUtils.isEmpty(userBean.getVerifyCode())) {
                return ParamErrorResultBuilder.newBuilder().paramError("verifyCode", "验证码不能为空").build();
            }

            String verifyCode = (String) request.getSession().getAttribute("verifyCode");

            if (verifyCode == null) {
                return ParamErrorResultBuilder.newBuilder().paramError("verifyCode", "没有获取到验证码").build();
            }

            Long expireTime = 50000L;

            Long createTime = (Long) request.getSession().getAttribute("createTime");

            //判断有效期
//            if ((System.currentTimeMillis() - createTime) > expireTime) {
//                return ParamErrorResultBuilder.newBuilder().paramError("verifyCode", "验证码已过期").build();
//            }

            if (!verifyCode.toLowerCase().equals(userBean.getVerifyCode().toLowerCase())) {
                return ParamErrorResultBuilder.newBuilder().paramError("verifyCode", "验证码错误").build();
            }
        }

        //验证账号和密码
        userBean = this.authService.login(userBean);


        if (userBean == null) {
            return ResponseBean.serverError("账号或密码错误");
        }

        request.getSession().removeAttribute("verifyCode");

        request.getSession().setAttribute("userBean", userBean);

        return ResponseBean.success("登录成功").addData("userBean", userBean);
    }

    /**
     * 更新当前用户密码接口
     *
     * @return
     */
    @RequestMapping
    public Object updateUserPassword(String newPassword, String oldPassword, HttpServletRequest request) {

        UserBean userBean = (UserBean) request.getSession().getAttribute("userBean");

        if (userBean == null) {
            return ResponseBean.unAuthorize("您未登录");
        }

        if (!oldPassword.equals(userBean.getPassword())) {
            return ParamErrorResultBuilder.newBuilder().paramError("oldPassword", "原密码不正确").build();
        }

        if (!this.authService.updateUserPassword(userBean, newPassword)) {
            return ResponseBean.serverError("修改密码失败");
        }

        this.logout(request);

        return ResponseBean.success("密码修改成功，请退出重新登录!");

    }

    @RequestMapping
    public Object logout(HttpServletRequest request) {

        UserBean userBean = (UserBean) request.getSession().getAttribute("userBean");

        if (userBean == null) {
            return ResponseBean.unAuthorize("您未登录");
        }

        request.getSession().invalidate();

        return ResponseBean.serverError("退出成功！");
    }

    /**
     * 获取当前用户信息接口
     *
     * @return
     */
    @RequestMapping
    public Object userInfo(HttpServletRequest request) {

        UserBean userBean = (UserBean) request.getSession().getAttribute("userBean");


        if (userBean == null) {
            return ResponseBean.unAuthorize("您未登录");
        }

        userBean = this.userService.find(userBean);


        Map userMap = MapBuilder.newBuilder()
                .put("realname", userBean.getRealname())
                .put("account", userBean.getAccount())
                .put("phone", userBean.getPhone())
                .put("password", userBean.getPassword())
                .put("roleCode", userBean.getRoleCode())
                .put("roleFlag", userBean.getRoleFlag())
                .put("operatorCode", userBean.getOperatorCode())
                .put("operatorNumber", userBean.getOperatorNumber())
                .put("code", userBean.getCode())
                .put("createTime", userBean.getCreateTime())
                .put("updateTime", userBean.getUpdateTime())
                .build();

        return ResponseBean.success("操作成功！").addData("user", userMap);
    }

}
