package com.dxhy.auth.controller;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.dxhy.admin.sys.config.AdminConfig;
import com.dxhy.admin.sys.config.SysConfig;
import com.dxhy.auth.service.AuthService;
import com.dxhy.common.aspect.SysLog;
import com.dxhy.common.constant.UserConstant;
import com.dxhy.common.utils.R;
import com.dxhy.common.utils.Rsaencrypt;
import com.dxhy.common.vo.JwtAuthenticationRequest;

import lombok.extern.slf4j.Slf4j;

/**
 * @author jiaohongyang
 */
@RestController
@RequestMapping("jwt")
@Slf4j
public class AuthController {
    @Value("${jwt.token-header}")
    private String tokenHeader;

    @Resource
    private AuthService authService;

    @RequestMapping(value = "token", method = RequestMethod.POST)
    @SysLog("用户登录")
    public ResponseEntity<R> createAuthenticationToken(@RequestBody JwtAuthenticationRequest authenticationRequest)
        throws Exception {
        log.info(authenticationRequest.getUsername() + " require logging...");
        String token = null;
        // 请求中不包含key参数为正常标品登陆，包含key参数为亚宝报销登录
        if (StringUtils.isNotBlank(authenticationRequest.getUsername())
            && StringUtils.isNotBlank(authenticationRequest.getPassword())) {
            // 登录页面登录
            token = authService.login(authenticationRequest);
        } else if (StringUtils.isNotBlank(authenticationRequest.getKey())) {
            String content =
                AdminConfig.saaskey + authenticationRequest.getTimestamp() + authenticationRequest.getUsername();
            log.info("亚宝登陆接口，组装加密参数:{}", content);
            String md5Hex = DigestUtils.md5Hex(content);
            log.info("加密后参数为：{}，对比请求参数：{}", md5Hex, authenticationRequest.getKey());
            if (!authenticationRequest.getKey().equals(md5Hex)) {
                return ResponseEntity.ok(R.error(40001, "用户不存在或账户密码错误!"));
            }
            // 将用户名重新加密，密码按用户名+时间戳加密进行登录
            String enUserName = Rsaencrypt.encrypt(authenticationRequest.getUsername(), UserConstant.PUBLIC_KEY);
            String enPassword = Rsaencrypt.encrypt(authenticationRequest.getUsername() + System.currentTimeMillis(),
                UserConstant.PUBLIC_KEY);
            authenticationRequest.setUsername(enUserName);
            authenticationRequest.setPassword(enPassword);
            token = authService.login(authenticationRequest);
        } else if (StringUtils.isNotBlank(authenticationRequest.getTicket())) {
            // CAS登录

            Map<String, String> map = authService.casLogin(authenticationRequest);
            if ("0000".equals(map.get("code"))) {
                token = map.get("token");
            } else if ("0001".equals(map.get("code"))) {
                return ResponseEntity.ok(R.error(40001, "用户不存在或账户密码错误!"));
            } else if ("9999".equals(map.get("code"))) {
                log.info("登录失败原因:{}", map.get("message"));
                return ResponseEntity.ok(R.error(40001, "用户不存在或账户密码错误!"));
            }

        }
        if (StringUtils.isNotBlank(token)) {
            if (SysConfig.TRUE.equals(token)) {
                return ResponseEntity.ok(R.error(40002, "该用户已被禁用，请联系管理员进行恢复！"));
            }
            log.info("token:    " + token);
            return ResponseEntity.ok(R.ok().put("data", token));
        } else {
            return ResponseEntity.ok(R.error(40001, "用户不存在或账户密码错误!"));
        }
    }

    @RequestMapping(value = "refresh", method = RequestMethod.GET)
    public ResponseEntity<R> refreshAndGetAuthenticationToken(HttpServletRequest request) throws Exception {
        String token = request.getHeader(tokenHeader);
        String refreshedToken = authService.refresh(token);
        return ResponseEntity.ok(R.ok().put("data", refreshedToken));
    }

    @RequestMapping(value = "verify", method = RequestMethod.GET)
    public ResponseEntity<R> verify(String token) throws Exception {
        authService.validate(token);
        return ResponseEntity.ok(R.ok());
    }

}
