package easydo.technology.controller;

import java.util.HashMap;
import java.util.Map;

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

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import easydo.technology.annotation.WebLog;
import easydo.technology.components.JdbcClient;
import easydo.technology.model.OaPurchaseInfo;
import easydo.technology.model.SysUser;
import easydo.technology.service.OAService;
import easydo.technology.system.security.config.bean.SecurityProperties;
import easydo.technology.system.security.security.TokenProvider;
import easydo.technology.system.security.service.OnlineUserService;
import easydo.technology.system.security.service.dto.JwtUserDto;
import easydo.technology.utils.StringUtil;
import lombok.extern.java.Log;
@Log
@RestController
@RequestMapping("/oa")
public class OaController {
    @Value("${OA.host}")
    String oaHost;
    @Value("${OA.getUsernamePath}")
    String oaUsernamePath;
    @Value("${OA.getUserInfoPath}")
    String oaUserInfoPath;
    @Resource
    SecurityProperties properties;

    @Resource
    JdbcClient jdbcClient;
    @Resource
    AuthenticationManagerBuilder authenticationManagerBuilder;
    @Resource
    TokenProvider tokenProvider;
    @Resource
    OnlineUserService onlineUserService;
    @Resource
    OAService oaService;
    @Value("${PURCHASE.redirectUrl}")
    String redirectUrl;

    /**
     * 提供给OA登陆地址
     * 接收一个ticket参数
     */
    @WebLog
    @GetMapping("/ssoLogin")
    public ModelAndView login(@RequestParam String ticket) {
        log.info("ticket==============>" + ticket);
        if (null != ticket) {
            try {
                String username = oaService.getUsername(ticket);
                if (StringUtil.isNotEmpty(username)) {
                    String telnumber = oaService.getTelNumber(username);
                    SysUser sysUser = new SysUser();
                    sysUser.setPhone(telnumber);
                    sysUser = jdbcClient.getJdbcModel(sysUser);
                    if (StringUtil.isNotEmpty(sysUser.getUserId())) {
                        ModelAndView modelAndView = new ModelAndView();
                        modelAndView.setViewName("redirect:" + redirectUrl + "?userId=" + sysUser.getUserId());
                        log.info("redirect=========>" + modelAndView.toString());
                        return modelAndView;
                    }
                }
            } catch (Exception e) {
               log.warning("oa no auth");
            }
        }
        // 登录失败 直接跳转到登录页面
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("redirect:" + redirectUrl);
        return modelAndView;
    }

    @RequestMapping("/getUserToken")
    public Object getUserToken(@RequestBody SysUser sysUser, HttpServletRequest request) throws Exception {
        sysUser = jdbcClient.getJdbcModel(sysUser);
        String password = sysUser.getOriginPassword();
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                sysUser.getUsername(), password);
        Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        // 生成令牌
        String token = tokenProvider.createToken(authentication);
        final JwtUserDto jwtUserDto = (JwtUserDto) authentication.getPrincipal();
        // 保存在线信息
        onlineUserService.save(jwtUserDto, token, request);
        // 返回 token 与 用户信息
        Map<String, Object> authInfo = new HashMap<String, Object>(2) {
            {
                put("token", properties.getTokenStartWith() + token);
                put("user", jwtUserDto);
            }
        };
        return new ResponseEntity<>(authInfo, HttpStatus.OK);
    }

    @WebLog
    @RequestMapping("/updateStatus")
    public Object updateStatus(@RequestBody OaPurchaseInfo OaPurchaseInfo) throws Exception {
        jdbcClient.jdbcUpdateById(OaPurchaseInfo);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}
