package com.cool.store.service.impl;

import com.alibaba.fastjson.JSON;
import com.cool.store.constants.CommonConstants;
import com.cool.store.constants.RedisConstant;
import com.cool.store.dao.EnterpriseUserDAO;
import com.cool.store.entity.EnterpriseUserDO;
import com.cool.store.entity.SysRoleDO;
import com.cool.store.enums.ErrorCodeEnum;
import com.cool.store.enums.JoinModeEnum;
import com.cool.store.enums.Role;
import com.cool.store.enums.UserStatusEnum;
import com.cool.store.exception.ServiceException;
import com.cool.store.mapper.SysRoleMapper;
import com.cool.store.service.EnterpriseService;
import com.cool.store.userholder.CurrentUser;
import com.cool.store.userholder.RefreshUser;
import com.cool.store.utils.RedisUtilPool;
import com.cool.store.utils.poi.DateUtils;
import com.cool.store.utils.poi.constant.Constants;
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.ParseException;
import java.util.Date;
import java.util.Objects;

/**
 * @Author suzhuhong
 * @Date 2025/5/29 16:34
 * @Version 1.0
 */
@Service
@Slf4j
public class EnterpriseServiceImpl implements EnterpriseService {

    @Resource
    EnterpriseUserDAO enterpriseUserDAO;

    @Resource
    SysRoleMapper sysRoleMapper;

    @Resource
    RedisUtilPool redisUtilPool;

    @Value("${mybatis.configuration.variables.enterpriseId}")
    private String eid;

    @Override
    public CurrentUser getLoginInfo(String mobile) {
        CurrentUser currentUser = new CurrentUser();
        EnterpriseUserDO enterpriseUser = enterpriseUserDAO.selectByMobile(mobile);
        if (Objects.isNull(enterpriseUser)){
            throw  new ServiceException(ErrorCodeEnum.MOBILE_NOT_EXIST);
        }
        if(UserStatusEnum.WAIT_AUDIT.getCode().equals(enterpriseUser.getUserStatus())){
            throw new ServiceException(ErrorCodeEnum.USER_ACCOUNT_WAIT_AUDIT);
        }
        //账号冻结
        if(UserStatusEnum.FREEZE.getCode().equals(enterpriseUser.getUserStatus())){
            throw new ServiceException(ErrorCodeEnum.USER_FREEZE);
        }
        SysRoleDO sysRoleDoByUserId = sysRoleMapper.getHighestPrioritySysRoleDoByUserId(enterpriseUser.getUserId());
        if(sysRoleDoByUserId==null){
            // 如果没有最高优先级的，给未分配的角色
            sysRoleDoByUserId = sysRoleMapper.getRoleByRoleEnum(Role.EMPLOYEE.getRoleEnum());
        }
        currentUser.setId(enterpriseUser.getId());
        currentUser.setUserId(enterpriseUser.getUserId());
        currentUser.setAccount(enterpriseUser.getUserId());
        currentUser.setDbName("coolcollege_intelligent_10027");
        currentUser.setDepartmentIds(enterpriseUser.getDepartments());
        currentUser.setRoles(enterpriseUser.getRoles());
        currentUser.setLanguage(enterpriseUser.getLanguage());
        currentUser.setIsAdmin(enterpriseUser.getIsAdmin());

        //设置当前登录人使用的企业相关信息
        currentUser.setRoleAuth(sysRoleDoByUserId.getRoleAuth());
        currentUser.setSysRoleDO(sysRoleDoByUserId);
        currentUser.setEnterpriseId(eid);
        currentUser.setEnterpriseName("正新集团");
        currentUser.setEnterpriseLogo("https://oss-store.coolcollege.cn/eid/214ac5a3a517472a87268e02a2e6410a/2405/79049713395952825.jpg");
        currentUser.setActive(enterpriseUser.getActive());
        // 企业开通时间
        try {
            currentUser.setOpenTime(DateUtils.parseDate("2024-05-09 18:54:28",DateUtils.YYYY_MM_DD_HH_MM_SS));
        } catch (ParseException e) {
            log.error("时间转换异常");
        }
        currentUser.setAvatar(enterpriseUser.getAvatar());
        currentUser.setEmail(enterpriseUser.getEmail());
        // 水印增加员工工号
        if (StringUtils.isNotEmpty(enterpriseUser.getJobnumber())) {
            currentUser.setJobnumber(enterpriseUser.getJobnumber());
        }
        // 水印增加员工职位
        if (StringUtils.isNotEmpty(enterpriseUser.getPosition())) {
            currentUser.setPosition(enterpriseUser.getPosition());
        }
        currentUser.setMobile(enterpriseUser.getMobile());
        currentUser.setName(enterpriseUser.getName());

        currentUser.setDingCorpId("wpayJeDAAAklx_q1jGhyGUd4yEh8vV_g");

        currentUser.setAccessToken(getToken());
        currentUser.setAppType("qw_self_dkf");
        currentUser.setUnionid(enterpriseUser.getUnionid());
        currentUser.setUserType(enterpriseUser.getUserType());
        redisUtilPool.setString(RedisConstant.ACCESS_TOKEN_PREFIX + currentUser.getAccessToken(), JSON.toJSONString(currentUser), CommonConstants.ACTION_TOKEN_EXPIRE);
        return currentUser;
    }

    @Override
    public RefreshUser getRefreshUser(String userId, String mobile) {
        if (StringUtils.isBlank(mobile)) {
            EnterpriseUserDO userInfo = enterpriseUserDAO.getUserInfoById(userId);
            mobile = userInfo.getMobile();
        }
        String refreshToken = getToken();
        RefreshUser refreshUser = new RefreshUser(userId, refreshToken, mobile);
        redisUtilPool.setString(RedisConstant.REFRESH_TOKEN_PREFIX + refreshToken, JSON.toJSONString(refreshUser), CommonConstants.REFRESH_TOKEN_EXPIRE);
        return refreshUser;
    }

    @Override
    public void checkUser(String userId,Integer joinMode) {
        EnterpriseUserDO userInfo = enterpriseUserDAO.getUserInfoById(userId);
        if (userInfo !=null){
            //校验当前人员是否是加盟部 581
            String departments = userInfo.getDepartments();
            //如果departments包含/581/ 加盟部
            if (com.cool.store.utils.poi.StringUtils.isNotBlank(departments) && departments.contains("/581/")) {
                //加盟部 FRANCHISE_COMPANIES
                if (!JoinModeEnum.isFranchise(joinMode)){
                    throw new ServiceException(ErrorCodeEnum.JOIN_MODE_NOT_ALLOW_OPERATE);
                }
            }
        }
    }

    public static void main(String[] args) {
        try {
            System.out.println(DateUtils.parseDate("2024-05-09 18:54:28",DateUtils.YYYY_MM_DD_HH_MM_SS));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    public String getToken() {
        RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
        return randomNumberGenerator.nextBytes().toHex();
    }
}
