package com.hotwj.platform.resourceManagement.company.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hotwj.platform.common.utils.PasswordUtils;
import com.hotwj.platform.resourceManagement.company.domain.*;
import com.hotwj.platform.resourceManagement.company.domain.bo.SysCompanyBo;
import com.hotwj.platform.resourceManagement.company.domain.vo.SysCompanyVo;
import com.hotwj.platform.resourceManagement.company.mapper.*;
import com.hotwj.platform.resourceManagement.company.service.ISysCompanyService;
import com.hotwj.platform.resourceManagement.companySafetyManager.domain.HotCompanySafetyManager;
import com.hotwj.platform.resourceManagement.companySafetyManager.mapper.HotCompanySafetyManagerMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.oss.core.OssClient;
import org.dromara.common.oss.factory.OssFactory;
import org.dromara.system.domain.SysRoleMenu;
import org.dromara.system.domain.SysUser;
import org.dromara.system.domain.SysUserRole;
import org.dromara.system.mapper.SysRoleMenuMapper;
import org.dromara.system.mapper.SysUserMapper;
import org.dromara.system.mapper.SysUserRoleMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayOutputStream;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import static com.hotwj.platform.resourceManagement.company.service.ISysUserLoginPortService.BUSINESS_ADMIN_ROLE_ID;
import static com.hotwj.platform.resourceManagement.company.service.ISysUserLoginPortService.ENTERPRISE_PORT;

/**
 * 企业基本信息Service业务层处理
 *
 * @author shihongwei
 * @date 2025-12-02
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SysCompanyServiceImpl implements ISysCompanyService {

    @Value("${company.register-url}")
    private String companyRegisterUrl;

    private final SysCompanyMapper baseMapper;
    private final HotCompanyBankAccountMapper hotCompanyBankAccountMapper;
    private final HotCompanyThirdPlatformMapper hotCompanyThirdPlatformMapper;
    private final SysCompanyRoleMapper sysCompanyRoleMapper;
    private final SysCompanyRoleMenuMapper sysCompanyRoleMenuMapper;
    private final SysUserLoginPortMapper sysUserLoginPortMapper;
    private final SysUserMapper sysUserMapper;
    private final SysUserRoleMapper sysUserRoleMapper;
    private final SysRoleMenuMapper sysRoleMenuMapper;
    private final HotCompanySafetyManagerMapper hotCompanySafetyManagerMapper;

    /**
     * 查询企业基本信息
     *
     * @param id 主键
     * @return 企业基本信息
     */
    @Override
    public SysCompanyVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询企业基本信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 企业基本信息分页列表
     */
    @Override
    public TableDataInfo<SysCompanyVo> queryPageList(SysCompanyBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysCompany> lqw = buildQueryWrapper(bo);
        Page<SysCompanyVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 按多个区和多个ID分页查询企业基本信息列表
     *
     * @param bo          查询条件
     * @param pageQuery   分页参数
     * @param regionCodes 区代码列表
     * @param ids         企业ID列表
     * @return 企业基本信息分页列表
     */
    @Override
    public TableDataInfo<SysCompanyVo> queryPageListByRegionAndIds(SysCompanyBo bo, PageQuery pageQuery, List<String> regionCodes, List<Long> ids) {
        LambdaQueryWrapper<SysCompany> lqw = buildQueryWrapper(bo);
        if (CollUtil.isNotEmpty(regionCodes)) {
            lqw.in(SysCompany::getRegionCode, regionCodes);
        }
        if (CollUtil.isNotEmpty(ids)) {
            lqw.in(SysCompany::getId, ids);
        }
        Page<SysCompanyVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 按多个区划分页查询企业基本信息列表
     *
     * @param bo          查询条件
     * @param pageQuery   分页参数
     * @param regionCodes 区代码列表
     * @return 企业基本信息分页列表
     */
    @Override
    public TableDataInfo<SysCompanyVo> queryPageListByRegionCodes(SysCompanyBo bo, PageQuery pageQuery, List<String> regionCodes) {
        LambdaQueryWrapper<SysCompany> lqw = buildQueryWrapper(bo);
        if (CollUtil.isNotEmpty(regionCodes)) {
            lqw.in(SysCompany::getRegionCode, regionCodes);
        }
        Page<SysCompanyVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的企业基本信息列表
     *
     * @param bo 查询条件
     * @return 企业基本信息列表
     */
    @Override
    public List<SysCompanyVo> queryList(SysCompanyBo bo) {
        return queryList(bo, null);
    }

    /**
     * 查询符合条件的企业基本信息列表
     *
     * @param bo  查询条件
     * @param ids ID列表
     * @return 企业基本信息列表
     */
    @Override
    public List<SysCompanyVo> queryList(SysCompanyBo bo, List<Long> ids) {
        LambdaQueryWrapper<SysCompany> lqw = buildQueryWrapper(bo);
        if (CollUtil.isNotEmpty(ids)) {
            lqw.in(SysCompany::getId, ids);
        }
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysCompany> buildQueryWrapper(SysCompanyBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysCompany> lqw = Wrappers.lambdaQuery();
        lqw.orderByDesc(SysCompany::getCreateTime);
        lqw.like(StringUtils.isNotBlank(bo.getCompanyName()), SysCompany::getCompanyName, bo.getCompanyName());
        lqw.like(StringUtils.isNotBlank(bo.getCompanyShortName()), SysCompany::getCompanyShortName, bo.getCompanyShortName());
        lqw.eq(StringUtils.isNotBlank(bo.getCompanyType()), SysCompany::getCompanyType, bo.getCompanyType());
        lqw.eq(StringUtils.isNotBlank(bo.getIndustry()), SysCompany::getIndustry, bo.getIndustry());
        lqw.like(StringUtils.isNotBlank(bo.getLegalPersonName()), SysCompany::getLegalPersonName, bo.getLegalPersonName());
        lqw.like(StringUtils.isNotBlank(bo.getResponsibleName()), SysCompany::getResponsibleName, bo.getResponsibleName());
        lqw.like(StringUtils.isNotBlank(bo.getResponsibleMobile()), SysCompany::getResponsibleMobile, bo.getResponsibleMobile());
        lqw.eq(StringUtils.isNotBlank(bo.getRegisteredAddress()), SysCompany::getRegisteredAddress, bo.getRegisteredAddress());
        lqw.eq(StringUtils.isNotBlank(bo.getOfficeAddress()), SysCompany::getOfficeAddress, bo.getOfficeAddress());
        lqw.eq(StringUtils.isNotBlank(bo.getOfficePhone()), SysCompany::getOfficePhone, bo.getOfficePhone());
        lqw.eq(StringUtils.isNotBlank(bo.getSealUrl()), SysCompany::getSealUrl, bo.getSealUrl());
        lqw.eq(StringUtils.isNotBlank(bo.getRegionCode()), SysCompany::getRegionCode, bo.getRegionCode());
        lqw.eq(StringUtils.isNotBlank(bo.getProvinceCode()), SysCompany::getProvinceCode, bo.getProvinceCode());
        lqw.eq(StringUtils.isNotBlank(bo.getCityCode()), SysCompany::getCityCode, bo.getCityCode());
        lqw.eq(bo.getStatus() != null, SysCompany::getStatus, bo.getStatus());
        lqw.eq(bo.getIsDeleted() != null, SysCompany::getIsDeleted, bo.getIsDeleted());
        return lqw;
    }

    /**
     * 新增企业基本信息
     *
     * @param bo 企业基本信息
     * @return 是否新增成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(SysCompanyBo bo) {
        SysCompany add = MapstructUtils.convert(bo, SysCompany.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }

        // -- 插入子表数据
        insertBankAccounts(bo, add);

        insertThirdAccounts(bo, add);

        // 添加负责人到用户表
        addResponsibleUser(bo);

        // 生成驾驶员邀请码
        if (flag) {
            boolean updated = ensureInvitationCode(add);
            if (updated) {
                baseMapper.updateById(add);
            }
        }
        return flag;
    }

    /**
     * 确保企业有有效的驾驶员邀请码
     */
    private boolean ensureInvitationCode(SysCompany company) {
        // 检查邀请码是否存在
        boolean needGenerate = false;
        if (StrUtil.isBlank(company.getDriverInvitationCode())) {
            needGenerate = true;
        }

        if (needGenerate) {
            // 1. 生成邀请码
            String code = IdUtil.fastSimpleUUID();
            company.setDriverInvitationCode(code);
            // 邀请码长期有效，不设置过期时间
            company.setDriverInvitationCodeExpireTime(null);

            // 2. 生成二维码
            // 注册页面路径
            String registerUrl = companyRegisterUrl + "/pages/register?inviteCode=" + code + "&companyId=" + company.getId();

            try {
                // 生成二维码图片
                java.awt.image.BufferedImage image = QrCodeUtil.generate(registerUrl, 300, 300);
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                ImgUtil.writePng(image, out);
                byte[] bytes = out.toByteArray();

                // 上传OSS
                OssClient ossClient = OssFactory.instance();
                String suffix = ".png";
                String contentType = "image/png";
                var result = ossClient.uploadSuffix(bytes, suffix, contentType);
                company.setDriverInvitationQrCodeUrl(result.getUrl());
            } catch (Exception e) {
                log.error("生成驾驶员邀请码二维码失败", e);
            }
            return true;
        }
        return false;
    }

    public void insertThirdAccounts(SysCompanyBo bo, SysCompany add) {
        if (CollUtil.isNotEmpty(bo.getThirdPlatforms())) {
            List<HotCompanyThirdPlatform> thirdPlatforms = MapstructUtils.convert(bo.getThirdPlatforms(), HotCompanyThirdPlatform.class);
            thirdPlatforms.forEach(thirdPlatform -> thirdPlatform.setCompanyId(add.getId()));
            hotCompanyThirdPlatformMapper.insertBatch(thirdPlatforms);
        }
    }

    public void updateBankAccounts(SysCompanyBo bo, SysCompany update) {
        if (CollUtil.isNotEmpty(bo.getBankAccounts())) {
            List<HotCompanyBankAccount> bankAccounts = MapstructUtils.convert(bo.getBankAccounts(), HotCompanyBankAccount.class);
            bankAccounts.forEach(bankAccount -> {
                bankAccount.setCompanyId(update.getId());
                if (bankAccount.getId() == null) {
                    hotCompanyBankAccountMapper.insert(bankAccount);
                } else {
                    if (bankAccount.getIsDeleted() != null && bankAccount.getIsDeleted() == 1) {
                        hotCompanyBankAccountMapper.deleteById(bankAccount);
                    } else {
                        hotCompanyBankAccountMapper.updateById(bankAccount);
                    }
                }
            });

        }
    }

    public void updateThirdAccounts(SysCompanyBo bo, SysCompany update) {
        if (CollUtil.isNotEmpty(bo.getThirdPlatforms())) {
            List<HotCompanyThirdPlatform> thirdPlatforms = MapstructUtils.convert(bo.getThirdPlatforms(), HotCompanyThirdPlatform.class);
            thirdPlatforms.forEach(thirdPlatform -> {
                thirdPlatform.setCompanyId(update.getId());
                if (thirdPlatform.getId() == null) {
                    hotCompanyThirdPlatformMapper.insert(thirdPlatform);
                } else {
                    if (thirdPlatform.getIsDeleted() != null && thirdPlatform.getIsDeleted() == 1) {
                        hotCompanyThirdPlatformMapper.deleteById(thirdPlatform);
                    } else {
                        hotCompanyThirdPlatformMapper.updateById(thirdPlatform);
                    }
                }
            });
        }
    }

    public void insertBankAccounts(SysCompanyBo bo, SysCompany add) {
        if (CollUtil.isNotEmpty(bo.getBankAccounts())) {
            List<HotCompanyBankAccount> bankAccounts = MapstructUtils.convert(bo.getBankAccounts(), HotCompanyBankAccount.class);
            bankAccounts.forEach(bankAccount -> bankAccount.setCompanyId(add.getId()));
            hotCompanyBankAccountMapper.insertBatch(bankAccounts);
        }
    }

    /**
     * 添加负责人到用户表
     *
     * @param bo 企业基本信息
     */
    public void addResponsibleUser(SysCompanyBo bo) {
        Long companyId = bo.getId();
        String responsibleMobile = bo.getResponsibleMobile();
        String responsibleName = bo.getResponsibleName();

        List<SysUser> sysUsers = sysUserMapper.selectList(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getPhonenumber, responsibleMobile));
        Long userId = null;

        // 就算是多个企业管理员共用一个手机号，SysUser应该只有一个
        if (CollUtil.isNotEmpty(sysUsers)) {
            if (sysUsers.size() > 1) {
                throw new IllegalArgumentException("手机号已存在多个用户");
            }
            userId = sysUsers.get(0).getUserId();
        }

        // 用户不存在，创建用户并设置角色
        if (userId == null) {
            SysUser sysUser = new SysUser();
            sysUser.setPhonenumber(responsibleMobile);
            sysUser.setNickName(responsibleName);
            sysUser.setUserName(responsibleMobile);
            // 主密码保留（兼容旧逻辑，或作为默认密码），但也需要设置子密码
            sysUser.setPassword(PasswordUtils.createDefaultPassword(responsibleMobile));
            sysUser.setUserType("sys_user");
            sysUser.setStatus("0");
            sysUserMapper.insert(sysUser);
            userId = sysUser.getUserId();
        }

        // 无论用户是新创建还是已存在，都需要确保有该企业的登录端口，并初始化子密码
        // 检查是否存在登录端口
        LambdaQueryWrapper<SysUserLoginPort> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserLoginPort::getCompanyId, companyId)
                .eq(SysUserLoginPort::getUserId, userId)
                .eq(SysUserLoginPort::getLoginPort, ENTERPRISE_PORT);
        SysUserLoginPort sysUserLoginPort = sysUserLoginPortMapper.selectOne(wrapper);

        if (sysUserLoginPort == null) {
            // 不存在，创建新的登录端口
            sysUserLoginPort = new SysUserLoginPort();
            sysUserLoginPort.setCompanyId(companyId);
            sysUserLoginPort.setUserId(userId);
            sysUserLoginPort.setUsername(responsibleName);
            sysUserLoginPort.setLoginPort(ENTERPRISE_PORT);
            sysUserLoginPort.setIsDefault(1);
            sysUserLoginPort.setStatus(1);
            // 初始化子密码：手机号 + "hot"
            sysUserLoginPort.setSubPassword(PasswordUtils.createDefaultPassword(responsibleMobile));
            sysUserLoginPortMapper.insert(sysUserLoginPort);
        } else {
            // 已存在，检查是否有子密码，如果没有则补充
            if (StringUtils.isBlank(sysUserLoginPort.getSubPassword())) {
                sysUserLoginPort.setSubPassword(PasswordUtils.createDefaultPassword(responsibleMobile));
                sysUserLoginPortMapper.updateById(sysUserLoginPort);
            }
        }

        // 确保有企业管理员角色
        Long roleId = createEnterpriseAdminRole(companyId, userId, responsibleName);

        // 查找是否已存在该人员记录
        LambdaQueryWrapper<HotCompanySafetyManager> smWrapper = new LambdaQueryWrapper<>();
        smWrapper.eq(HotCompanySafetyManager::getCompanyId, companyId)
                .eq(HotCompanySafetyManager::getPhone, responsibleMobile);
        HotCompanySafetyManager safetyManager = hotCompanySafetyManagerMapper.selectOne(smWrapper);

        if (safetyManager == null) {
            safetyManager = new HotCompanySafetyManager();
            safetyManager.setCompanyId(companyId);
            safetyManager.setName(responsibleName);
            safetyManager.setPhone(responsibleMobile);
            safetyManager.setUserId(userId);
            // 设置为企业负责人
            safetyManager.setCompanyHead(1L);
            // 企业负责人权限变更
            safetyManager.setPermissionType("company_admin");
            safetyManager.setPermissionRoleId(roleId);

            safetyManager.setIsResigned(0L);
            safetyManager.setStatus(1L);
            hotCompanySafetyManagerMapper.insert(safetyManager);
            log.info("[企业负责人] 创建安全管理人员记录 companyId={}, userId={}, managerId={}", companyId, userId, safetyManager.getId());
        } else {
            // 更新现有记录
            safetyManager.setName(responsibleName);
            safetyManager.setUserId(userId);
            safetyManager.setCompanyHead(1L);
            safetyManager.setPermissionType("company_admin");
            safetyManager.setPermissionRoleId(roleId);
            safetyManager.setIsResigned(0L);
            safetyManager.setStatus(1L);
            hotCompanySafetyManagerMapper.updateById(safetyManager);
            log.info("[企业负责人] 更新安全管理人员记录 companyId={}, userId={}, managerId={}", companyId, userId, safetyManager.getId());
        }
    }

    public Long createEnterpriseAdminRole(Long companyId, Long userId, String username) {
        // 1. Check/Create SysCompanyRole
        LambdaQueryWrapper<SysCompanyRole> roleWrapper = new LambdaQueryWrapper<>();
        roleWrapper.eq(SysCompanyRole::getCompanyId, companyId)
                .eq(SysCompanyRole::getRoleKey, "company_admin");
        SysCompanyRole role = sysCompanyRoleMapper.selectOne(roleWrapper);

        if (role == null) {
            role = new SysCompanyRole();
            role.setCompanyId(companyId);
            role.setRoleName("企业管理员（默认）");
            role.setRoleKey("company_admin");
            role.setRoleSort(1);
            role.setStatus("0"); // 0 normal
            role.setRemark("自动生成的企业管理员角色");
            role.setCreatorUserId(null);
            sysCompanyRoleMapper.insert(role);
            // 赋予所有菜单权限
            List<SysRoleMenu> sysRoleMenus = sysRoleMenuMapper.selectList(
                    new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRoleId, BUSINESS_ADMIN_ROLE_ID)
            );
            if (CollUtil.isNotEmpty(sysRoleMenus)) {
                Long roleId = role.getId();
                List<SysCompanyRoleMenu> companyRoleMenus = sysRoleMenus.stream().map(sysRoleMenu -> {
                    SysCompanyRoleMenu companyRoleMenu = new SysCompanyRoleMenu();
                    companyRoleMenu.setCompanyRoleId(roleId);
                    companyRoleMenu.setMenuId(sysRoleMenu.getMenuId());
                    return companyRoleMenu;
                }).toList();
                sysCompanyRoleMenuMapper.insertBatch(companyRoleMenus);
            }
        }
        Long roleId = role.getId();

        return roleId;
    }

    /**
     * 修改企业基本信息
     *
     * @param bo 企业基本信息
     * @return 是否修改成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(SysCompanyBo bo) {
        // 获取旧的企业信息以比对负责人是否变更
        SysCompany oldCompany = baseMapper.selectById(bo.getId());
        SysCompany update = MapstructUtils.convert(bo, SysCompany.class);

        if (oldCompany != null) {
            if (update.getDriverInvitationCode() == null) {
                update.setDriverInvitationCode(oldCompany.getDriverInvitationCode());
                update.setDriverInvitationCodeExpireTime(oldCompany.getDriverInvitationCodeExpireTime());
                update.setDriverInvitationQrCodeUrl(oldCompany.getDriverInvitationQrCodeUrl());
            }
        }

        ensureInvitationCode(update);

        validEntityBeforeSave(update);
        boolean flag = baseMapper.updateById(update) > 0;

        // 更新子表的操作
        updateBankAccounts(bo, update);
        updateThirdAccounts(bo, update);

        // 修改企业负责人是否用户信息也需要变更??
        if (oldCompany != null) {
            // 1. 处理旧负责人：移除相关权限，标记离职（仅当负责人手机号变更时）
            String oldMobile = oldCompany.getResponsibleMobile();
            if (StrUtil.isNotBlank(oldMobile) && !StrUtil.equals(oldMobile, bo.getResponsibleMobile())) {
                SysUser oldUser = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getPhonenumber, oldMobile));
                if (oldUser != null) {
                    Long oldUserId = oldUser.getUserId();
                    // 移除该用户在当前企业的角色关联
                    sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>()
                            .eq(SysUserRole::getUserId, oldUserId)
                            .eq(SysUserRole::getLoginPort, ENTERPRISE_PORT)
                            .eq(SysUserRole::getCompanyId, bo.getId()));

                    // 移除该用户与企业的关联关系
                    sysUserLoginPortMapper.delete(new LambdaQueryWrapper<SysUserLoginPort>()
                            .eq(SysUserLoginPort::getUserId, oldUserId)
                            .eq(SysUserLoginPort::getLoginPort, ENTERPRISE_PORT)
                            .eq(SysUserLoginPort::getCompanyId, bo.getId()));

                    hotCompanySafetyManagerMapper.deleteCompanyHeadByPhone(bo.getId(), oldMobile);
                }
            }

            // 2. 添加新负责人：创建用户（如果不存在）、赋予权限、添加安全管理人员记录
            addResponsibleUser(bo);
        }

        return flag;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysCompany entity) {
    }

    /**
     * 校验并批量删除企业基本信息信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public String checkInviteCode(Long companyId, String inviteCode) {
        if (companyId == null) {
            throw new ServiceException("企业ID不能为空");
        }
        if (StringUtils.isBlank(inviteCode)) {
            throw new ServiceException("邀请码不能为空");
        }
        SysCompany company = baseMapper.selectById(companyId);
        if (company == null) {
            throw new ServiceException("企业不存在");
        }
        if (!inviteCode.equals(company.getDriverInvitationCode())) {
            throw new ServiceException("邀请码无效");
        }
        // 校验是否过期(如果有过期时间的话)
        // if (company.getDriverInvitationCodeExpireTime() != null && company.getDriverInvitationCodeExpireTime().before(new Date())) {
        //    throw new ServiceException("邀请码已过期");
        // }
        return company.getCompanyName();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void resetAllInviteCodes() {
        // 1. 查出所有未删除的企业
        List<SysCompany> companyList = baseMapper.selectList(new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<SysCompany>()
                .eq(SysCompany::getIsDeleted, 0));

        if (CollUtil.isEmpty(companyList)) {
            return;
        }

        log.info("开始重置所有企业邀请码，共 {} 家", companyList.size());

        // 2. 遍历重置
        for (SysCompany company : companyList) {
            try {
                // 清空现有邀请码，强制 ensureInvitationCode 重新生成
                company.setDriverInvitationCode(null);
                boolean updated = ensureInvitationCode(company);
                if (updated) {
                    baseMapper.updateById(company);
                }
            } catch (Exception e) {
                log.error("重置企业邀请码失败: companyId={}, name={}", company.getId(), company.getCompanyName(), e);
            }
        }
        log.info("重置所有企业邀请码完成");
    }

    /**
     * 根据邀请码查询企业信息
     *
     * @param code 邀请码
     * @return 企业信息
     */
    @Override
    public SysCompanyVo queryByInviteCode(String code) {
        if (StringUtils.isBlank(code)) {
            return null;
        }
        LambdaQueryWrapper<SysCompany> lqw = Wrappers.lambdaQuery();
        lqw.eq(SysCompany::getDriverInvitationCode, code);

        return baseMapper.selectVoOne(lqw);
    }
}
