package com.fdage.controller;

import com.fdage.dto.ResourceTree;
import com.fdage.enums.ResponEnum;
import com.fdage.pojo.TbLog;
import com.fdage.pojo.TbUser;
import com.fdage.request.RequestUser;
import com.fdage.respon.ResponUser;
import com.fdage.service.ILogService;
import com.fdage.service.IResourceService;
import com.fdage.service.IRoleService;
import com.fdage.service.IUserService;
import com.fdage.shiro.JwtUtil2;
import com.fdage.util.AjaxJson;
import com.fdage.util.PasswordUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created by Hb_zzZ on 2019/9/11.
 */
@Slf4j
@Controller
@Api(tags = "sys-登陆模块")
public class LoginController {

    @Autowired
    private IUserService userService;

    @Autowired
    private IResourceService resourceService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private ILogService logService;

    @PostMapping("/login")
    @ResponseBody
    @ApiOperation("登陆1")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userName", value = "用户名", dataType = "String"),
            @ApiImplicitParam(name = "password", value = "密码", dataType = "String")})
    public AjaxJson login(@RequestBody RequestUser bo){
        log.info("RequestUser: {}", bo.toString());
        if(bo == null || StringUtils.isEmpty(bo.getUserName()) || StringUtils.isEmpty(bo.getPassword())){
            return AjaxJson.failure(ResponEnum.NOT_NULL.getCode(), ResponEnum.NOT_NULL.getMessage());
        }

        TbUser user = userService.findByUserName(bo.getUserName());
        if(user == null){
            return AjaxJson.failure(ResponEnum.USER_NOT_EXIST.getCode(), ResponEnum.USER_NOT_EXIST.getMessage());
        }

        String encryptPwd = PasswordUtils.encrypt(bo.getPassword(), bo.getUserName(), PasswordUtils.getStaticSalt());
        if(!encryptPwd.equals(user.getPassword())){
            return AjaxJson.failure(ResponEnum.PASSWORD_ERROR.getCode(), ResponEnum.PASSWORD_ERROR.getMessage());
        }

        // 检查账号是否启用
        if (user.getState() != 0) {
            log.error("账号已停用： {}", user.getUserName());
            return AjaxJson.failure(ResponEnum.USER_STOP_USING.getCode(), ResponEnum.USER_STOP_USING.getMessage());
        }

//        ResponUser result = new ResponUser();
//        BeanUtils.copyProperties(user, result);


        List<ResourceTree> resourcesTreeByUserPermission = resourceService.getResourcesAllByUserPermission(user);
//        log.info("获取权限 success");

        // 获取用户角色
        List<String> roles = userService.findRoleByUserId(user.getId());
//        log.info("获取角色 success");


        // 创建新token
        HashMap<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("userName", user.getUserName());
        tokenMap.put("id", user.getId());
        tokenMap.put("role", roles);


        String token = JwtUtil2.createJWT(-1, tokenMap);

        HashMap<String, Object> result = new HashMap<>();
        result.put("user", user);
        result.put("token", token);
        result.put("permission", resourcesTreeByUserPermission);
        result.put("role", roles);
//        log.info("token create");


        // 更新到 redis, 有效期24h, 旧token无效
        redisTemplate.opsForValue().set(user.getUserName(), token, Long.parseLong("23"), TimeUnit.HOURS);

        TbLog logEntity = new TbLog();
        logEntity.setCreateTime(new Date());
        logEntity.setType("登陆");
        logEntity.setDescription("登陆系统");
        logEntity.setUserId(user.getId());

        logService.save(logEntity);

        return AjaxJson.success(result);
    }
}
