package com.cool.store.service.impl;

import com.alibaba.fastjson.JSON;
import com.cool.store.constants.CommonConstants;
import com.cool.store.context.LoginUserInfo;
import com.cool.store.context.DataSourceContext;
import com.cool.store.dao.*;
import com.cool.store.dto.login.RefreshUser;
import com.cool.store.entity.EnterpriseUserDO;
import com.cool.store.entity.SysRoleDO;
import com.cool.store.enums.ErrorCodeEnum;
import com.cool.store.enums.UserStatusEnum;
import com.cool.store.exception.ServiceException;
import com.cool.store.service.LoginService;
import com.cool.store.utils.RedisUtilPool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.Objects;

/**
 * @author zhangchenbiao
 * @FileName: LoginServiceImpl
 * @Description:
 * @date 2023-05-23 9:57
 */
@Service
@Slf4j
public class LoginServiceImpl implements LoginService {
    @Resource
    private EnterpriseUserDAO enterpriseUserDAO;
    @Resource
    private SysRoleDAO sysRoleDAO;
    @Resource
    private RedisUtilPool redisUtilPool;
    @Resource
    private EnterpriseUserRoleDAO enterpriseUserRoleDAO;
    @Value("${corp.id:null}")
    private String corpId;

    @Override
    public Object feiShuLogin(String userId, Boolean needRefreshToken, String avatar) {
        log.info("isvLogin, corpId={}, userId={}", userId);
        DataSourceContext.clearDataSourceType();
        if (StringUtils.isEmpty(userId)) {
            throw new ServiceException(ErrorCodeEnum.USER_NOT_EXIST);
        }
        LoginUserInfo currentUser = new LoginUserInfo();
        // 查企业用户
        EnterpriseUserDO enterpriseUser = enterpriseUserDAO.getUserInfoById(userId);
        if(enterpriseUser == null){
            throw new ServiceException(ErrorCodeEnum.NOT_AUTH);
        }
        SysRoleDO sysRole = sysRoleDAO.getHighestPriorityRoleByUserId(userId);
        if(UserStatusEnum.FREEZE.getCode().equals(enterpriseUser.getUserStatus())){
            throw new ServiceException(ErrorCodeEnum.USER_FREEZE);
        }
        if(UserStatusEnum.WAIT_AUDIT.getCode().equals(enterpriseUser.getUserStatus())){
            throw new ServiceException(ErrorCodeEnum.USER_WAIT_AUDIT);
        }
        //用户是否已有头像
        Boolean hasAvatar = StringUtils.isNotEmpty(enterpriseUser.getAvatar()) && !enterpriseUser.getAvatar().contains(CommonConstants.DEFAULT_AVATAR);
        String finalAvatar = hasAvatar ? enterpriseUser.getAvatar() : avatar;
        enterpriseUser.setAvatar(finalAvatar);
        enterpriseUser.setFaceUrl(finalAvatar);
        currentUser.setUserId(enterpriseUser.getUserId());
        currentUser.setIsAdmin(enterpriseUser.getIsAdmin());
        currentUser.setMobile(enterpriseUser.getMobile());
        currentUser.setSysRole(sysRole);
        currentUser.setCorpId(corpId);
        currentUser.setAvatar(enterpriseUser.getAvatar());
        //生成令牌
        RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
        String token = randomNumberGenerator.nextBytes().toHex();
        currentUser.setName(enterpriseUser.getName());
        currentUser.setAccessToken(token);
        redisUtilPool.setString(MessageFormat.format(CommonConstants.ACCESS_TOKEN_KEY, token), JSON.toJSONString(currentUser), CommonConstants.ACCESS_TOKEN_EXPIRE);
        redisUtilPool.setString(currentUser.getUserId(), token);
        log.info("[" + enterpriseUser.getName() + "; action_token："+ token + "; userId：" + currentUser.getUserId()  +"]登入系统成功");
        return currentUser;
    }

}
