package com.ruoyi.web.controller.wechat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.UserEnvConstant;
import com.ruoyi.common.core.domain.dto.AppletLoginForm;
import com.ruoyi.common.core.domain.dto.AppletSessionDTO;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.core.redis.RedisService;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.ObjectUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.WxCodeSessionUtil;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.SettledMerchants;
import com.ruoyi.system.service.ISettledMerchantsService;
import com.ruoyi.system.service.ISysLogininforService;
import com.ruoyi.system.service.ISysUserService;
import eu.bitwalker.useragentutils.UserAgent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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 ISysUserService iSysUserService;
    @Resource
    private ISysLogininforService iSysLogininforService;
    @Autowired
    private ISettledMerchantsService settledMerchantsService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private TokenService tokenService;


    @PostMapping("/login")
    public R<Map<String, Object>> getPhone(@RequestBody AppletLoginForm form) {

        AppletSessionDTO dto = codeUtil.jscode2Session(form);
        String phoneNumber = dto.getPhoneNumber();
        if (StringUtils.isBlank(phoneNumber)) {
            throw new BaseException("对不起，未获取到手机号");
        }
        SysUser user = iSysUserService.getByPhone(dto.getPhoneNumber());
        if (user == null) {
            throw new BaseException("对不起，未获取到相关信息");
        }
        String userName = user.getUserName();
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            throw new BaseException("对不起，您的账号：" + userName + " 已被删除");
        }

        if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            throw new BaseException("对不起，您的账号：" + userName + " 已停用");
        }


        LOGGER.info("appletLogin, remoteUserService: {}", iSysUserService);
        //获取当前用户信息
        LoginUser loginUser = new LoginUser();
        loginUser.setUser(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.getUser().getUserId());
        loginUser.setUserName(loginUser.getUser().getUserName());
        loginUser.setIpaddr(IpUtils.getIpAddr(ServletUtils.getRequest()));

        JSONObject userEnv = packUserEnv(loginUser);
        loginUser.setUserEnv(userEnv);
        //loginUser.setLoginType("App");

        //设置用户代理信息
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        loginUser.setIpaddr(ip);
        loginUser.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
        loginUser.setBrowser(userAgent.getBrowser().getName());
        loginUser.setOs(userAgent.getOperatingSystem().getName());

        refreshToken(loginUser);

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

        //获取商家的信息
        SettledMerchants settledMerchants = settledMerchantsService.selectByPhone(loginUser.getUser().getUserName());
        map.put("settledMerchants", settledMerchants);
        map.put("userId", loginUser.getUser().getUserId());
        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());
        redisCache.setCacheObject(userKey, loginUser, (int)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;
    }
}
