package com.boman.common.security.service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.boman.common.core.utils.*;
import com.boman.common.core.enums.UserStatus;
import com.boman.common.core.exception.BaseException;
import com.boman.common.core.utils.obj.ObjectUtils;
import com.boman.domain.SysUser;
import com.boman.domain.constant.UserEnvConstant;
import com.boman.domain.dto.R;
import com.boman.system.api.RemoteDeptService;
import com.boman.domain.SysDept;
import org.apache.commons.collections4.MapUtils;
import org.apache.poi.ss.usermodel.DateUtil;
import com.boman.system.api.RemoteLogService;
import com.boman.system.api.RemoteUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.boman.domain.constant.CacheConstants;
import com.boman.domain.constant.Constants;
import com.boman.common.core.utils.ip.IpUtils;
import com.boman.common.redis.service.RedisService;
import com.boman.system.api.model.LoginUser;

import static com.boman.domain.constant.Constants.*;

/**
 * token验证处理
 *
 * @author ruoyi
 */
@Component
public class TokenService {

    private static final Logger LOGGER = LoggerFactory.getLogger(TokenService.class);
    @Autowired
    private RedisService redisService;
    @Resource
    private RemoteDeptService remoteDeptService;
    @Resource
    private RemoteUserService remoteUserService;
    @Resource
    private RemoteLogService remoteLogService;

    @Autowired
    private TokenService tokenService;

    private final static long EXPIRE_TIME = Constants.TOKEN_EXPIRE * 60;

    private final static long EXPIRE_TIME_QR = 3 * 60;

    private final static String ACCESS_TOKEN = CacheConstants.LOGIN_TOKEN_KEY;

    protected static final long MILLIS_SECOND = 1000;

    /**
     * 创建令牌
     */
    public Map<String, Object> createToken(LoginUser loginUser) {
        // 生成token
        String token = IdUtils.fastUUID();
        loginUser.setToken(token);
        loginUser.setUserid(loginUser.getSysUser().getId());
        loginUser.setUsername(loginUser.getSysUser().getUserName());
        loginUser.setIpaddr(IpUtils.getIpAddr(ServletUtils.getRequest()));

        JSONObject userEnv = packUserEnv(loginUser);
        loginUser.setUserEnv(userEnv);
        loginUser.setLoginType("PC");
        refreshToken(loginUser);

        // 保存或更新用户token
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("access_token", token);
        map.put("expires_in", EXPIRE_TIME);
        redisService.setCacheObject(ACCESS_TOKEN + token, loginUser, EXPIRE_TIME, TimeUnit.SECONDS);
        return map;
    }

    private JSONObject packUserEnv(LoginUser loginUser) {
        JSONObject userEnv = new JSONObject();
        userEnv.put(UserEnvConstant.USER_ID, loginUser.getUserid());
        userEnv.put(UserEnvConstant.USERNAME, loginUser.getUsername());

        SysDept dept = loginUser.getSysUser().getDept();
        userEnv.put(UserEnvConstant.USER_DEPT_ID, loginUser.getSysUser().getDeptId());
        userEnv.put(UserEnvConstant.USER_DEPT_NAME, dept.getDeptName());

        Long parentId = dept.getParentId();
        SysDept parentDept = remoteDeptService.getById(parentId);
        if (ObjectUtils.isNotEmpty(parentDept)) {
            userEnv.put(UserEnvConstant.USER_PARENT_DEPT_ID, parentDept.getId());
            userEnv.put(UserEnvConstant.USER_PARENT_DEPT_NAME, parentDept.getDeptName());
        }

        return userEnv;
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser() {
        return getLoginUser(ServletUtils.getRequest());
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            String userKey = getTokenKey(token);
            LoginUser user = redisService.getCacheObject(userKey);
            return user;
        }
        return null;
    }

    /**
     * 设置用户身份信息
     */
    public void setLoginUser(LoginUser loginUser) {
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNotEmpty(loginUser.getToken())) {
            refreshToken(loginUser);
        }
    }

    public void delLoginUser(String token) {
        if (StringUtils.isNotEmpty(token)) {
            String userKey = getTokenKey(token);
            redisService.deleteObject(userKey);
        }
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    public void refreshToken(LoginUser loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + EXPIRE_TIME * MILLIS_SECOND);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUser.getToken());
        redisService.setCacheObject(userKey, loginUser, EXPIRE_TIME, TimeUnit.SECONDS);
    }

    private String getTokenKey(String token) {
        return ACCESS_TOKEN + token;
    }

    /**
     * 生成二维码
     *
     * @return
     */
    public String getQrCode() {
        String uuid = UUID.randomUUID().toString();
        redisService.setCacheObject(uuid, EMPOWER, EXPIRE_TIME_QR, TimeUnit.SECONDS);
        return uuid;
    }

    /**
     * 判断二维码是否被扫描
     *
     * @param uuid
     * @return
     */
    public R<?> getPool(String uuid) {
        //todo 为什么一直在进入这个地方
        //System.out.println("检测[   " + uuid + "   ]是否登录");
        R<?> r = new R<>();
        r.setMsg("un_scan");
        if (redisService.getCacheObject(uuid) == null){
            return  r;
        }
        String cacheObject = redisService.getCacheObject(uuid).toString();
        try {
            if (StringUtils.isBlank(cacheObject)) {
                r.setMsg("该二维码已经失效,请重新获取");
            } else if (cacheObject.equals(SUCCESS.toString())) {
                r.setMsg("has_scan");
            } else if (cacheObject.length() > 3) {
                SysUser user = remoteUserService.getByPhone(cacheObject.toString());
                LoginUser loginUser = remoteUserService.packInfo(user);
                //获取token
                Map<String, Object> token = tokenService.createToken(loginUser);
                Object accessToken = token.get("access_token");
                r.setCode(SUCCESS);
                r.setMsg(LOGIN_SUCCESS_APP+accessToken);
                redisService.deleteObject(uuid);
                return r;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return r;
    }

    /**
     * 用户扫码成功,改变redis中的值
     *
     * @param uuid
     * @return
     */
    public R<String> scanCode(String uuid) {
        R<String> r = new R<>();
        Integer code = redisService.getCacheObject(uuid);
        r.setCode(SUCCESS);
        r.setData(uuid);
        if (code == null) {
            r.setCode(FAIL);
            r.setMsg("该二维码已经失效,请重新获取");
        }
        if (code != null) {
            redisService.setCacheObject(uuid, SUCCESS);
        }
        return r;
    }


    public R<Map<String, Object>> appletLogin(String phoneNumber) {
        SysUser user = remoteUserService.getByPhone(phoneNumber);
        String userName = user.getUserName();
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            remoteLogService.saveLogininfor(userName, Constants.LOGIN_FAIL, "对不起，您的账号已被删除");
            throw new BaseException("对不起，您的账号：" + userName + " 已被删除");
        }

        if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            remoteLogService.saveLogininfor(userName, Constants.LOGIN_FAIL, "用户已停用，请联系管理员");
            throw new BaseException("对不起，您的账号：" + userName + " 已停用");
        }

        remoteLogService.saveLogininfor(userName, Constants.LOGIN_SUCCESS, "登录成功");
        LoginUser loginUser = remoteUserService.packInfo(user);
        LOGGER.info("appletLogin, loginUser: {}", JSON.toJSONString(loginUser));
        return R.ok(createToken(loginUser));
    }
}