package com.boman.wechat.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.boman.common.core.enums.UserStatus;
import com.boman.common.core.exception.BaseException;
import com.boman.common.core.utils.IdUtils;
import com.boman.common.core.utils.ServletUtils;
import com.boman.common.core.utils.StringUtils;
import com.boman.common.core.utils.ip.IpUtils;
import com.boman.common.core.utils.obj.ObjectUtils;
import com.boman.common.redis.service.RedisService;
import com.boman.domain.AppletLoginForm;
import com.boman.domain.SysDept;
import com.boman.domain.SysUser;
import com.boman.domain.constant.CacheConstants;
import com.boman.domain.constant.Constants;
import com.boman.domain.constant.UserEnvConstant;
import com.boman.domain.dto.AppletSessionDTO;
import com.boman.domain.dto.R;
import com.boman.system.api.RemoteDeptService;
import com.boman.system.api.RemoteLogService;
import com.boman.system.api.RemoteUserService;
import com.boman.system.api.model.LoginUser;
import com.boman.wechat.utils.WxCodeSessionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
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;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author shiqian
 * @date 2021年09月08日 17:29
 **/
@RestController
@RequestMapping("applet")
public class AppletLoginController {

    private static final Logger LOGGER = LoggerFactory.getLogger(AppletLoginController.class);

    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;

    @Resource
    private WxCodeSessionUtil codeUtil;
    @Resource
    private RedisService redisService;
    @Resource
    private RemoteUserService remoteUserService;
    @Resource
    private RemoteLogService remoteLogService;
    @Resource
    private RemoteDeptService remoteDeptService;

    @Value("${upkeep}")
    private Boolean upKeep;

    @PostMapping("/login")
    public R<Map<String, Object>> getPhone(@RequestBody AppletLoginForm form) {
        if (upKeep){
            throw new BaseException("当前正在维护");
        }
        AppletSessionDTO dto = codeUtil.jscode2Session(form);
        String phoneNumber = dto.getPhoneNumber();
        if (StringUtils.isBlank(phoneNumber)){
            throw new BaseException("对不起，未获取到手机号");
        }
        SysUser user = remoteUserService.getByPhone(dto.getPhoneNumber());
        if (user == null){
            throw new BaseException("对不起，未获取到相关信息");
        }
        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, "登录成功");
        LOGGER.info("appletLogin, remoteUserService: {}", remoteUserService);
        LoginUser loginUser = remoteUserService.packInfo(user);
        LOGGER.info("appletLogin, loginUser: {}", JSON.toJSONString(loginUser));
        return R.ok(createToken(loginUser));
    }

    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("App");
        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;
    }

    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;
    }

    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;
    }
}
