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


import com.kuyuntech.vrv.coreapi.bean.core.UserBean;
import com.kuyuntech.vrv.coreapi.bean.core.VerifyCodeBean;
import com.kuyuntech.vrv.coreapi.constant.core.VerifyCodeStatus;
import com.kuyuntech.vrv.coreapi.constant.core.VerifyCodeType;
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.domain.core.VerifyCode;
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.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.NativeWebRequest;

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

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

    @Autowired
    private RedisTemplate redisTemplate;

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

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

    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);
        System.out.println(verifyCode);

        VerifyCodeBean verifyCodeBean = this.verifyCodeService.add(VerifyCodeBean.builder().type(VerifyCodeType.IMG).verified(VerifyCodeStatus.UN_VERIFY).expireTime(verifyCodeExpireTime).verifyCode(verifyCode).build());

        redisTemplate.opsForValue().set("verifyCodeBean", verifyCodeBean);
        //request.getSession().setAttribute("verifyCodeBean", verifyCodeBean);

        response.setContentType("application/force-download");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(verifyCode, "UTF-8"));

        ValidateCodeGenerator.outputImage(width != null ? width : 300, height != null ? height : 100, response.getOutputStream(), verifyCode);

    }

    @RequestMapping
    public Object login(UserBean userBean, HttpServletRequest request) {


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

            VerifyCodeBean verifyCodeBean = (VerifyCodeBean) redisTemplate.opsForValue().get("verifyCodeBean");
            //    VerifyCodeBean verifyCodeBean = (VerifyCodeBean) request.getSession().getAttribute("verifyCodeBean");

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

            String verifyCode = verifyCodeBean.getVerifyCode();

            System.out.println(verifyCode);

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

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

            // String verifyCode = verifyCodeBean.getVerifyCode();


            //判断有效期
//            if ((System.currentTimeMillis() - verifyCodeBean.getCreateTime().getTime()) > verifyCodeBean.getExpireTime()) {
//                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("账号或密码错误");
        }

        redisTemplate.delete("verifyCodeBean");
        //request.getSession().removeAttribute("verifyCodeBean");

        redisTemplate.opsForValue().set("userBean", userBean);
        //  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) redisTemplate.opsForValue().get("userBean");
        //   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("密码修改成功，请退出重新登录!");

    }

    /**
     * 登出
     *
     * @param request
     * @return
     */
    @RequestMapping
    public Object logout(HttpServletRequest request) {

        UserBean userBean = (UserBean) redisTemplate.opsForValue().get("userBean");

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

        //request.getSession().invalidate();
        redisTemplate.delete("userBean");

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

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

        UserBean userBean = (UserBean) redisTemplate.opsForValue().get("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);
    }

}
