package com.shanghaichengdi.ghjgitem.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.shanghaichengdi.ghjgitem.constant.Constants;
import com.shanghaichengdi.ghjgitem.constant.HttpStatus;
import com.shanghaichengdi.ghjgitem.domain.SysDatashareUser;
import com.shanghaichengdi.ghjgitem.enums.OutsideInterface;
import com.shanghaichengdi.ghjgitem.service.RedisService;
import com.shanghaichengdi.ghjgitem.service.SysDatashareServiceNewService;
import com.shanghaichengdi.ghjgitem.service.SysDatashareUserService;
import com.shanghaichengdi.ghjgitem.util.ApiUtils;
import com.shanghaichengdi.ghjgitem.util.JwtUtils;
import com.shanghaichengdi.ghjgitem.vo.request.AuthRequest;
import com.shanghaichengdi.ghjgitem.vo.request.FrequencyCacheReq;
import com.shanghaichengdi.ghjgitem.vo.response.ReturnMsg;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@CrossOrigin
@RequestMapping("/auth")
@Slf4j
public class AuthController {

  @Resource
  private SysDatashareUserService sysDatashareUserService;
  @Resource
  private SysDatashareServiceNewService datashareServiceNewService;
  @Resource
  private RedisService redisService;
  @Value("${cache.token.expire}")
  private Integer tokenExpire;


  @PostMapping("/getToken")
  public ReturnMsg getToken(@RequestBody @Validated AuthRequest request) {
    List<SysDatashareUser> datashareUserList = sysDatashareUserService.list(
        Wrappers.<SysDatashareUser>lambdaQuery().eq(SysDatashareUser::getKey, request.getKey())
            .eq(SysDatashareUser::getSecret, request.getSecret())
            .eq(SysDatashareUser::getIsvalid, 1));
    if (CollectionUtils.isEmpty(datashareUserList)) {
      return ReturnMsg.error(HttpStatus.NO_CONTENT, "系统中未找到该用户信息");
    }
    SysDatashareUser sysDatashareUser = datashareUserList.get(0);
    Map<String, Object> claims = new HashMap<>();
    claims.put(sysDatashareUser.getKey(), sysDatashareUser.getId());
    String tokenString;
    if (!Objects.isNull(sysDatashareUser.getToken()) && Boolean.TRUE.equals(redisService.hasKey(
        Constants.TOKEN + Constants.SPLIT, sysDatashareUser.getToken()))) {
      tokenString = sysDatashareUser.getToken();
    } else {
      tokenString = JwtUtils.generateJwt(claims, Constants.JWT_KEY);
      redisService.setStringCache(Constants.TOKEN + Constants.SPLIT, tokenString,
          JSONObject.toJSONString(sysDatashareUser), tokenExpire,
          TimeUnit.MINUTES);
      sysDatashareUser.setToken(tokenString);
      sysDatashareUser.setUpdateTime(new Date());
      sysDatashareUserService.updateById(sysDatashareUser);
    }
    return ReturnMsg.success(tokenString);
  }

  @GetMapping("/checkToken/{tokenString}")
  public ReturnMsg checkToken(@PathVariable("tokenString") String tokenString) {
    Objects.requireNonNull(tokenString,"tokenString不可为空");
    Map<String, String> map = new HashMap<>();
    map.put("token", tokenString);
    String result = ApiUtils.api(map, OutsideInterface.AUTH_URL.getUrlString(), "checkToken");
    return ReturnMsg.success(result);
  }

  @PostMapping("/refresh/frequency")
  public ReturnMsg refreshFrequency(@RequestBody FrequencyCacheReq req) {
    datashareServiceNewService.refreshFrequency(req.getClientList());
    return ReturnMsg.success("缓存刷新成功");
  }

  @GetMapping("/test/{token}")
  public ReturnMsg test(@PathVariable("token") String token) {
    String o = redisService.getValue(Constants.TOKEN + Constants.SPLIT, token);
    return ReturnMsg.success(o);
  }
}
