package com.cf.imes.module.system.service.organ;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.cf.imes.framework.common.enums.CommonStatusEnum;
import com.cf.imes.framework.common.pojo.PageResult;
import com.cf.imes.framework.common.util.collection.CollectionUtils;
import com.cf.imes.framework.common.util.date.DateUtils;
import com.cf.imes.framework.common.util.json.JsonUtils;
import com.cf.imes.framework.common.util.object.BeanUtils;
import com.cf.imes.framework.common.util.pinyin.PinYinUtils;
import com.cf.imes.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.cf.imes.framework.organ.config.OrganProperties;
import com.cf.imes.framework.organ.core.context.OrganContextHolder;
import com.cf.imes.framework.organ.core.util.OrganUtils;
import com.cf.imes.framework.security.core.util.SecurityFrameworkUtils;
import com.cf.imes.module.system.api.organ.dto.OrgStatisticsIsLapseRespDTO;
import com.cf.imes.module.system.api.organ.dto.OrgStatisticsReqDTO;
import com.cf.imes.module.system.constants.permission.InternalRoleConstants;
import com.cf.imes.module.system.controller.admin.organ.vo.organ.OrganPageReqVO;
import com.cf.imes.module.system.controller.admin.organ.vo.organ.OrganRespVO;
import com.cf.imes.module.system.controller.admin.organ.vo.organ.OrganSaveReqVO;
import com.cf.imes.module.system.controller.admin.organ.vo.organ.OrganSimpleRespVO;
import com.cf.imes.module.system.controller.admin.permission.vo.role.RoleSaveReqVO;
import com.cf.imes.module.system.controller.admin.systemconfig.vo.ProcessSchemeConfig;
import com.cf.imes.module.system.controller.admin.tokenconfig.vo.JwtConfig;
import com.cf.imes.module.system.controller.admin.user.vo.user.UserSaveReqVO;
import com.cf.imes.module.system.convert.organ.OrganConvert;
import com.cf.imes.module.system.dal.dataobject.dict.DictDataDO;
import com.cf.imes.module.system.dal.dataobject.funds.organamount.OrganAmountDO;
import com.cf.imes.module.system.dal.dataobject.lable.LabelDO;
import com.cf.imes.module.system.dal.dataobject.machine.MachineDO;
import com.cf.imes.module.system.dal.dataobject.machine.MachineLimitDO;
import com.cf.imes.module.system.dal.dataobject.oauth2.OAuth2AccessTokenDO;
import com.cf.imes.module.system.dal.dataobject.organ.OrganizationDO;
import com.cf.imes.module.system.dal.dataobject.organ.TenantPackageDO;
import com.cf.imes.module.system.dal.dataobject.permission.MenuDO;
import com.cf.imes.module.system.dal.dataobject.permission.RoleDO;
import com.cf.imes.module.system.dal.dataobject.systemconfig.*;
import com.cf.imes.module.system.dal.dataobject.tokenconfig.TokenConfigDO;
import com.cf.imes.module.system.dal.mysql.dict.DictDataMapper;
import com.cf.imes.module.system.dal.mysql.funds.organamount.OrganAmountMapper;
import com.cf.imes.module.system.dal.mysql.label.LabelMapper;
import com.cf.imes.module.system.dal.mysql.machine.MachineLimitMapper;
import com.cf.imes.module.system.dal.mysql.machine.MachineMapper;
import com.cf.imes.module.system.dal.mysql.organ.OrganMapper;
import com.cf.imes.module.system.dal.mysql.systemconfig.*;
import com.cf.imes.module.system.dal.mysql.tokenconfig.TokenConfigMapper;
import com.cf.imes.module.system.enums.config.SystemConfigTypeEnum;
import com.cf.imes.module.system.enums.permission.RoleCodeEnum;
import com.cf.imes.module.system.enums.permission.RoleTypeEnum;
import com.cf.imes.module.system.service.organ.handler.OrganInfoHandler;
import com.cf.imes.module.system.service.organ.handler.OrganMenuHandler;
import com.cf.imes.module.system.service.permission.MenuService;
import com.cf.imes.module.system.service.permission.PermissionService;
import com.cf.imes.module.system.service.permission.RoleService;
import com.cf.imes.module.system.service.user.AdminUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import jakarta.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

import static com.cf.imes.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.cf.imes.framework.common.util.json.JsonUtils.parseArray;
import static com.cf.imes.module.system.dal.redis.RedisKeyConstants.OAUTH2_ACCESS_TOKEN;
import static com.cf.imes.module.system.enums.ErrorCodeConstants.*;
import static com.cf.imes.module.system.service.tokenconfig.TokenConfigServiceImpl.generateBaseToken;
import static java.util.Collections.singleton;

/**
 * 组织 Service 实现类
 *
 * @author 晨丰科技
 */
@Service
@Validated
@Slf4j
public class OrganServiceImpl implements OrganService {

    @SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
    @Autowired(required = false) // 由于 chenfeng.tenant.enable 配置项，可以关闭多组织的功能，所以这里只能不强制注入
    private OrganProperties organProperties;

    @Resource
    private OrganMapper organMapper;

    @Resource
    private TenantPackageService tenantPackageService;
    @Resource
    @Lazy // 延迟，避免循环依赖报错
    private AdminUserService userService;
    @Resource
    private RoleService roleService;
    @Resource
    private MenuService menuService;
    @Resource
    private PermissionService permissionService;

    @Value("${chenfeng.organ.use-data-code:imes_prod}")
    private String useDataCode;

    @Resource
    private MachineLimitMapper machineLimitMapper;

    @Resource
    private TokenConfigMapper tokenConfigMapper;

    @Resource
    private JwtConfig jwtConfig;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private DictDataMapper dictDataMapper;

    @Resource
    private SystemConfigMapper systemConfigMapper;

    @Resource
    private SystemConfigFilterMapper systemConfigFilterMapper;

    @Resource
    private SystemConfigProcessMapper systemConfigProcessMapper;

    @Resource
    private SystemConfigDataMapper systemConfigDataMapper;

    @Resource
    private SystemConfigSchemeMapper systemConfigSchemeMapper;

    @Resource
    private SystemConfigSealedgeMapper systemConfigSealedgeMapper;

    @Resource
    private MachineMapper machineMapper;

    @Resource
    private LabelMapper labelMapper;

    @Resource
    private OrganAmountMapper organAmountMapper;


    @Override
    public List<Long> getOrganIdList() {
        List<OrganizationDO> organizationDOS = organMapper.selectList();
        return CollectionUtils.convertList(organizationDOS, OrganizationDO::getId);
    }

    @Override
    public OrganizationDO validOrgan(Long id) {
        OrganizationDO organizationDO = getOrgan(id);
        if (organizationDO == null) {
            throw exception(ORGAN_NOT_EXISTS);
        }
        if (organizationDO.getStatus().equals(CommonStatusEnum.DISABLE.getStatus())) {
            throw exception(ORGAN_DISABLE, organizationDO.getName());
        }
        if (DateUtils.isExpired(organizationDO.getExpireTime())) {
            throw exception(ORGAN_EXPIRE, organizationDO.getName());
        }
        if (ObjectUtil.isNull(organizationDO.getPackageId())) {
            throw exception(TENANT_PACKAGE_NOT_EXISTS);
        }
        // 组织套餐相关校验
        Long packageId = organizationDO.getPackageId();
        if (ObjectUtil.isNull(packageId)) {
            throw exception(TENANT_PACKAGE_NOT_EXISTS);
        }
        tenantPackageService.validTenantPackage(packageId);
        return organizationDO;
    }

    @Override
    public List<OrganSimpleRespVO> getSimpleOrganList(String name) {
        List<OrganizationDO> organizationDOS = organMapper.selectList(new LambdaQueryWrapperX<OrganizationDO>()
                .likeIfPresent(OrganizationDO::getName, name)
                .select(OrganizationDO::getId, OrganizationDO::getName));
       return BeanUtils.toBean(organizationDOS, OrganSimpleRespVO.class);
    }

    @Override
    @DSTransactional // 多数据源，使用 @DSTransactional 保证本地事务，以及数据源的切换
    public Long createOrgan(OrganSaveReqVO createReqVO) {
        // 校验组织名称是否重复
        validTenantNameDuplicate(createReqVO.getName(), null);
        // 校验组织域名是否重复
        validTenantWebsiteDuplicate(createReqVO.getWebsite(), null);
        // 校验组织手机号是否重复
        validContactMobileDuplicate(createReqVO.getContactMobile(),null);
        // 校验套餐被禁用
        TenantPackageDO tenantPackage = tenantPackageService.validTenantPackage(createReqVO.getPackageId());

        // 创建组织
        OrganizationDO tenant = BeanUtils.toBean(createReqVO, OrganizationDO.class);
        String pinyinFull = PinYinUtils.convertToPinyin(tenant.getName());
        if(CharSequenceUtil.isNotBlank(pinyinFull)) {
            pinyinFull = pinyinFull.replace(" ", "");
        }
        tenant.setPinyinFull(pinyinFull);
        tenant.setLarge(createReqVO.getLarge() == null ? Boolean.FALSE : createReqVO.getLarge());
        tenant.setPinyinInitial(PinYinUtils.convertFirstChar(tenant.getName()));
        //todo 未来还需要判断是否大客户，大客户有自己dataCode
        tenant.setDataSourceCode(useDataCode);

        organMapper.insert(tenant);
        Long organId = tenant.getId();
        if (!tenant.getLarge()) {
            tenant.setDbNo(organId.intValue() % 8);
        }
        tenant.setTableNo(organId.intValue() % 256);
        organMapper.updateById(tenant);
        // 创建组织的管理员
        OrganUtils.execute(organId, () -> {
            // 创建角色
            /*Long roleId = createRole(tenantPackage, organId);*/
            // 创建用户，并分配角色
            Long userId = createUser(InternalRoleConstants.ORGAN_ADMIN_ROLE_ID, createReqVO, organId);
            // 修改组织的管理员
            organMapper.updateById(new OrganizationDO().setId(tenant.getId()).setContactUserId(userId));
        });


        // 往组织机台授权表新增信息
        MachineLimitDO machineLimitDO = MachineLimitDO.builder()
                .organId(tenant.getId())
                .build();
        machineLimitMapper.insert(machineLimitDO);

        // 复制系统配置里的相关配置
        copySystemConfig(tenant.getId());

        // 创建组织套餐
        organAmountMapper.insert(OrganAmountDO.builder()
                .organId(tenant.getId())
                .build());

        return tenant.getId();
    }

    private Long createUser(Long roleId, OrganSaveReqVO createReqVO, Long organId) {
        // 创建用户
        UserSaveReqVO reqVO = OrganConvert.INSTANCE.convert02(createReqVO);
        reqVO.setOrganId(organId);
        Long userId = userService.createUser(reqVO);
        // 分配角色
        permissionService.assignUserRole(userId, singleton(roleId), organId);
        return userId;
    }

    private Long createRole(TenantPackageDO tenantPackage, Long organId) {
        // 创建角色
        RoleSaveReqVO reqVO = new RoleSaveReqVO();
        reqVO.setName(RoleCodeEnum.TENANT_ADMIN.getName()).setCode(RoleCodeEnum.TENANT_ADMIN.getCode())
                .setSort(0).setRemark("系统自动生成").setOrganId(organId);
        Long roleId = roleService.createRole(reqVO, RoleTypeEnum.SYSTEM.getType());
        // 分配权限
        permissionService.assignRoleMenu(roleId, tenantPackage.getMenuIds(), organId);
        return roleId;
    }

    @Override
    @DSTransactional // 多数据源，使用 @DSTransactional 保证本地事务，以及数据源的切换
    public void updateOrgan(OrganSaveReqVO updateReqVO) {
        Long organId = updateReqVO.getId();
        // 校验存在
        OrganizationDO tenant = validateUpdateTenant(organId);
        // 校验组织名称是否重复
        validTenantNameDuplicate(updateReqVO.getName(), organId);
        // 校验组织域名是否重复
        validTenantWebsiteDuplicate(updateReqVO.getWebsite(), organId);
        // 校验组织手机号是否重复
        validContactMobileDuplicate(updateReqVO.getContactMobile(),organId);
        // 校验套餐被禁用
        TenantPackageDO tenantPackage = tenantPackageService.validTenantPackage(updateReqVO.getPackageId());
        if(!Objects.equals(tenant.getName(), updateReqVO.getName())) {
            String pinyinFull = PinYinUtils.convertToPinyin(tenant.getName());
            if(CharSequenceUtil.isNotBlank(pinyinFull)) {
                pinyinFull = pinyinFull.replace(" ", "");
            }
            tenant.setPinyinFull(pinyinFull);
            tenant.setPinyinInitial(PinYinUtils.convertFirstChar(tenant.getName()));

        }


        // 如果手机号更新，需要同步更新 token 管理的 token
        if(!Objects.equals(tenant.getContactMobile(), updateReqVO.getContactMobile())){

            List<TokenConfigDO> tokenConfigDOS = tokenConfigMapper.selectConfigByOrganId(organId);
            if(CollUtil.isNotEmpty(tokenConfigDOS)) {
                tokenConfigDOS.forEach(f -> {
                    f.setAppToken(generateBaseToken(organId, updateReqVO.getContactMobile(), f.getAppType(), jwtConfig.getSecret()));
                });
                tokenConfigMapper.updateBatch(tokenConfigDOS);
            }
        }

        // 更新组织
        OrganizationDO updateObj = BeanUtils.toBean(updateReqVO, OrganizationDO.class);
        organMapper.updateById(updateObj);
        // 如果套餐发生变化，则修改其角色的权限
        if (ObjectUtil.notEqual(tenant.getPackageId(), updateReqVO.getPackageId())) {
            permissionService.flushCacheWhenTenantPackageChange(List.of(tenant.getId()));
        }
        if (CommonStatusEnum.DISABLE.getStatus().equals(updateReqVO.getStatus())) {
            // 移除机构下用户的token
            scanAndCompareDeptAndDelToken(String.format(OAUTH2_ACCESS_TOKEN, "*"), organId);
        }
    }

    private void validTenantNameDuplicate(String name, Long id) {
        OrganizationDO tenant = organMapper.selectByName(name);
        if (tenant == null) {
            return;
        }
        // 如果 id 为空，说明不用比较是否为相同名字的组织
        if (id == null) {
            throw exception(ORGAN_NAME_DUPLICATE, name);
        }
        if (!tenant.getId().equals(id)) {
            throw exception(ORGAN_NAME_DUPLICATE, name);
        }
    }

    private void validTenantWebsiteDuplicate(String website, Long id) {
        if (CharSequenceUtil.isEmpty(website)) {
            return;
        }
        OrganizationDO tenant = organMapper.selectByWebsite(website);
        if (tenant == null) {
            return;
        }
        // 如果 id 为空，说明不用比较是否为相同名字的组织
        if (id == null) {
            throw exception(ORGAN_WEBSITE_DUPLICATE, website);
        }
        if (!tenant.getId().equals(id)) {
            throw exception(ORGAN_WEBSITE_DUPLICATE, website);
        }
    }


    private void validContactMobileDuplicate(String contactMobile,Long organId) {

        List<OrganizationDO> organizationDOS = organMapper.selectByContactMobile(contactMobile,organId);


        if(CollUtil.isNotEmpty(organizationDOS)){
            throw exception(ORGAN_CONTACTMOBILE_DUPLICATE,contactMobile);
        }
    }




    @Override
    @DSTransactional
    public void updateOrganRoleMenu(Long organId, Set<Long> menuIds) {
        OrganUtils.execute(organId, () -> {
            // 获得所有角色
            List<RoleDO> roles = roleService.getMeAndDefaultRoleList();
            roles.forEach(role -> Assert.isTrue(organId.equals(role.getOrganId()) || role.getOrganId().equals(InternalRoleConstants.INTERNAL_ROLE_ORGAN_ID), "角色({}/{}) 组织不匹配",
                    role.getId(), role.getOrganId(), organId)); // 兜底校验
            // 重新分配每个角色的权限
            roles.forEach(role -> {
                // 如果是组织管理员，重新分配其权限为组织套餐的权限
                if (Objects.equals(role.getCode(), RoleCodeEnum.TENANT_ADMIN.getCode())) {
                    permissionService.assignRoleMenu(role.getId(), menuIds, organId);
                    log.info("[updateTenantRoleMenu][组织管理员({}/{}) 的权限修改为({})]", role.getId(), role.getOrganId(), menuIds);
                    return;
                }
                // 如果是其他角色，则去掉超过套餐的权限
                Set<Long> roleMenuIds = permissionService.getRoleMenuListByRoleId(role.getId());
                roleMenuIds = CollUtil.intersectionDistinct(roleMenuIds, menuIds);
                permissionService.assignRoleMenu(role.getId(), roleMenuIds, organId);
                log.info("[updateTenantRoleMenu][角色({}/{}) 的权限修改为({})]", role.getId(), role.getOrganId(), roleMenuIds);
            });
        });
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteOrgan(Long id) {
        // 校验存在
        validateUpdateTenant(id);
        // 校验机构内用户操作
        checkCurrentWhenOperate(id);
        // 删除
        organMapper.deleteById(id);
        // 删除关联的用户
        userService.deleteOrgUsers(id);
        // 移除机构下用户的token
        scanAndCompareDeptAndDelToken(String.format(OAUTH2_ACCESS_TOKEN, "*"), id);
    }

    /**
     * 轮训redis token，移除对应机构下的用户的token
     *
     * @param keyPattern
     * @param organId
     */
    private void scanAndCompareDeptAndDelToken(String keyPattern, Long organId) {
        // 根据keyPattern scan匹配的redis key
        List<String> matchKeys = new ArrayList<>();
        Cursor<String> cursor = stringRedisTemplate.scan(ScanOptions.scanOptions().match(keyPattern).count(200).build());
        while (cursor.hasNext()) {
            matchKeys.add(cursor.next());
        }
        cursor.close();
        if (CollUtil.isNotEmpty(matchKeys)) {
            for (String key : matchKeys) {
                // 获取key下的用户信息
                OAuth2AccessTokenDO oAuth2AccessTokenDO = JsonUtils.parseObject(stringRedisTemplate.opsForValue().get(key), OAuth2AccessTokenDO.class);
                if (ObjectUtil.equal(organId, oAuth2AccessTokenDO.getOrganId())) {
                    // 用户id匹配上了删除redis中的token缓存
                    stringRedisTemplate.delete(key);
                    return;
                }
            }
        }
    }

    /**
     * 检查是否操作当前组织
     */
    private void checkCurrentWhenOperate(Long organId) {
        if (ObjectUtil.equal(organId, SecurityFrameworkUtils.getUserOrganId())) {
            throw exception(ORGAN_USER_OPER_NOT_ALLOW);
        }
    }

    private OrganizationDO validateUpdateTenant(Long id) {
        OrganizationDO tenant = organMapper.selectById(id);
        if (tenant == null) {
            throw exception(ORGAN_NOT_EXISTS);
        }
        // 内置组织，不允许删除
        /*if (isSystemTenant(tenant)) {
            throw exception(ORGAN_CAN_NOT_UPDATE_SYSTEM);
        }*/
        return tenant;
    }

    @Override
    public OrganizationDO getOrgan(Long id) {
        return organMapper.selectById(id);
    }

    @Override
    public PageResult<OrganizationDO> getOrganPage(OrganPageReqVO pageReqVO) {
        if(CharSequenceUtil.isNotBlank(pageReqVO.getName())) {
            pageReqVO.setPyFirstChar(PinYinUtils.convertFirstChar(pageReqVO.getName()));
            pageReqVO.setPyAll(PinYinUtils.convertToPinyin(pageReqVO.getName()).replace(" ", ""));
        } else {
            // 避免name为空外部传入拼音查询字段
            pageReqVO.setPyFirstChar(null);
            pageReqVO.setPyAll(null);
        }
        return organMapper.selectPage(pageReqVO);
    }

    @Override
    public OrganizationDO getOrganByName(String name) {
        return organMapper.selectByName(name);
    }

    @Override
    public OrganizationDO getOrganByWebsite(String website) {
        return organMapper.selectByWebsite(website);
    }

    @Override
    public Long getOrganCountByPackageId(Long packageId) {
        return organMapper.selectCountByPackageId(packageId);
    }

    @Override
    public List<OrganizationDO> getOrganListByPackageId(Long packageId) {
        return organMapper.selectListByPackageId(packageId);
    }

    @Override
    public void handleOrganInfo(OrganInfoHandler handler,Long organId) {
        // 如果禁用，则不执行逻辑
        if (isTenantDisable()) {
            return;
        }
        // 获得组织
        OrganizationDO tenant = getOrgan(ObjectUtil.isNotNull(organId) ? organId : OrganContextHolder.getRequiredOrganId());
        // 执行处理器
        handler.handle(tenant);
    }

    @Override
    public void handleOrganMenu(OrganMenuHandler handler) {
        // 如果禁用，则不执行逻辑
        if (isTenantDisable()) {
            return;
        }
        // 获得组织，然后获得菜单
        OrganizationDO tenant = getOrgan(OrganContextHolder.getRequiredOrganId());
        Set<Long> menuIds;

        //menuIds = tenantPackageService.getTenantPackage(tenant.getPackageId()).getMenuIds();

        if (isSystemTenant(tenant) || (SecurityFrameworkUtils.isCfOrg() && SecurityFrameworkUtils.isManageEndPoint())) { // 系统组织，菜单是全量的
            menuIds = CollectionUtils.convertSet(menuService.getMenuList(), MenuDO::getId);
        } else {
            menuIds = tenantPackageService.getTenantPackage(tenant.getPackageId()).getMenuIds();
        }
        // 执行处理器
        handler.handle(menuIds);
    }

    private static boolean isSystemTenant(OrganizationDO tenant) {
        return Objects.equals(tenant.getPackageId(), OrganizationDO.PACKAGE_ID_SYSTEM);
    }

    private boolean isTenantDisable() {
        return organProperties == null || Boolean.FALSE.equals(organProperties.getEnable());
    }

    @Override
    public Map<String, Integer> orgTotal() {
        Map<String, Integer> map = new HashMap<>();

        // 组织总数
        Integer orgTotal = organMapper.selectOrgCount();
        map.put("orgTotal", orgTotal);
        // 当日新增数
        Integer orgAdd = organMapper.selectOrgCountAdd();
        map.put("orgAdd", orgAdd);
        // 当日状态-删除
        Integer orgDel = organMapper.selectOrgCountDel();
        map.put("orgDel", orgDel);
        // 当日沉寂数 (组织中所有用户30天未登录)
        // 获得30天前的时间，赋值时间为0：00：00
        Date date = DateUtil.offsetDay(new Date(), -30);
        Integer orgSilent = organMapper.selectOrgSilentCount(DateUtil.beginOfDay(date).toLocalDateTime());
        map.put("orgSilent", orgSilent);
        return map;
    }

    @Override
    public List<OrgStatisticsIsLapseRespDTO> orgCountAddByOrderDateAdd(OrgStatisticsReqDTO reqVO) {
        return organMapper.selectOrgCountAddByOrderDate(reqVO);
    }

    @Override
    public List<OrgStatisticsIsLapseRespDTO> orgCountLapseByOrderDate(OrgStatisticsReqDTO reqVO) {
        return organMapper.selectOrgCountLapseByOrderDate(reqVO);
    }

    @Override
    public List<OrganRespVO> orgCountExpire(LocalDateTime today, LocalDateTime afterDay) {
        return BeanUtils.toBean(organMapper.selectOrgCountExpire(today, afterDay), OrganRespVO.class);
    }

    @Override
    public List<OrganRespVO> orgCountExpired(LocalDateTime alertDay) {
        return BeanUtils.toBean(organMapper.selectOrgCountExpired(alertDay), OrganRespVO.class);
    }




    // 系统配置数据复制
    private void copySystemConfig(Long organId) {

        List<DictDataDO> dictDataDOS = dictDataMapper.selectListByStatusAndDictType(CommonStatusEnum.ENABLE.getStatus(), "copy_data_organ");
        if(CollUtil.isEmpty(dictDataDOS)){
            return;
        }

        String value = dictDataDOS.get(0).getValue();

        Long copyOrganId = Long.valueOf(value);


        // 自定义板编号
        List<SystemConfigDO> systemConfigDOS = systemConfigMapper.selectList(new LambdaQueryWrapperX<SystemConfigDO>()
                .eq(SystemConfigDO::getType, SystemConfigTypeEnum.CUSTOM_PLATE_NO.getType())
                .eq(SystemConfigDO::getOrganId, copyOrganId)
                .eq(SystemConfigDO::getDeleted, false));

        if(CollUtil.isNotEmpty(systemConfigDOS)){
            Optional<SystemConfigDO> configDO = systemConfigDOS.stream().max(Comparator.comparing(SystemConfigDO::getVersion));
            if (configDO.isPresent()) {
                SystemConfigDO systemConfigDO = configDO.get();
                systemConfigMapper.insert(SystemConfigDO.builder()
                        .name(systemConfigDO.getName())
                        .status(systemConfigDO.getStatus())
                        .sort(systemConfigDO.getSort())
                        .type(systemConfigDO.getType())
                        .setting(systemConfigDO.getSetting())
                        .organId(organId)
                        .build());
            }
        }


        // 板件分线
        List<SystemConfigFilterDO> systemConfigFilterDOS = systemConfigFilterMapper.selectList(new LambdaQueryWrapperX<SystemConfigFilterDO>()
                .eq(SystemConfigFilterDO::getOrganId, copyOrganId)
                .eq(SystemConfigFilterDO::getDeleted, false)
                .eq(SystemConfigFilterDO::getType, SystemConfigTypeEnum.INTELLIGENT_BRANCH.getType()));
        if(CollUtil.isNotEmpty(systemConfigFilterDOS)){
            systemConfigFilterDOS.forEach(f->{
                f.setId(null);
                f.setOrganId(organId);
                f.setCreateTime(null);
                f.setCreator(null);
                f.setUpdateTime(null);
                f.setUpdater(null);
            });

            systemConfigFilterMapper.insertBatch(systemConfigFilterDOS);
        }


        // 加工分线
        List<SystemConfigProcessDO> systemConfigProcessDOS = systemConfigProcessMapper.selectList(new LambdaQueryWrapperX<SystemConfigProcessDO>()
                .eq(SystemConfigProcessDO::getOrganId, copyOrganId)
                .eq(SystemConfigProcessDO::getDeleted, false)
                .eq(SystemConfigProcessDO::getType, SystemConfigTypeEnum.PROCESSING_SCREENING.getType()));
        if(CollUtil.isNotEmpty(systemConfigProcessDOS)){
            systemConfigProcessDOS.forEach(f->{
                f.setId(null);
                f.setOrganId(organId);
                f.setCreateTime(null);
                f.setCreator(null);
                f.setUpdateTime(null);
                f.setUpdater(null);
            });

            systemConfigProcessMapper.insertBatch(systemConfigProcessDOS);
        }


        // 数据处理
        List<SystemConfigDataDO> systemConfigDataDOS = systemConfigDataMapper.selectList(new LambdaQueryWrapperX<SystemConfigDataDO>()
                .eq(SystemConfigDataDO::getOrganId, copyOrganId)
                .eq(SystemConfigDataDO::getDeleted, false)
                .eq(SystemConfigDataDO::getType, SystemConfigTypeEnum.DATA_PROCESSING.getType()));
        if(CollUtil.isNotEmpty(systemConfigDataDOS)){
            systemConfigDataDOS.forEach(f->{
                f.setId(null);
                f.setOrganId(organId);
                f.setCreateTime(null);
                f.setCreator(null);
                f.setUpdateTime(null);
                f.setUpdater(null);
            });

            systemConfigDataMapper.insertBatch(systemConfigDataDOS);
        }


        // 加工方案,(需要复制的组织ID，需要添加数据的组织ID)
        copyConfigSchemeMachineAndLabel(copyOrganId,organId);


        // 封边条对应
        List<SystemConfigSealedgeDO> systemConfigSealedgeDOS = systemConfigSealedgeMapper.selectList(new LambdaQueryWrapperX<SystemConfigSealedgeDO>()
                .eq(SystemConfigSealedgeDO::getOrganId, copyOrganId)
                .eq(SystemConfigSealedgeDO::getDeleted, false)
                .eq(SystemConfigSealedgeDO::getType, SystemConfigTypeEnum.SEALEDGE.getType()));
        if(CollUtil.isNotEmpty(systemConfigSealedgeDOS)){
            systemConfigSealedgeDOS.forEach(f->{
                f.setId(null);
                f.setOrganId(organId);
                f.setCreateTime(null);
                f.setCreator(null);
                f.setUpdateTime(null);
                f.setUpdater(null);
            });

            systemConfigSealedgeMapper.insertBatch(systemConfigSealedgeDOS);
        }

    }



    // 复制加工方案组以及里面的机台信息以及标签的配置信息
    private void copyConfigSchemeMachineAndLabel(Long copyOrganId,Long organId){

        List<SystemConfigSchemeDO> systemConfigSchemeDOS = systemConfigSchemeMapper.selectList(new LambdaQueryWrapperX<SystemConfigSchemeDO>()
                .eq(SystemConfigSchemeDO::getOrganId, copyOrganId)
                .eq(SystemConfigSchemeDO::getDeleted, false)
                .eq(SystemConfigSchemeDO::getType, SystemConfigTypeEnum.PROCESS_SCHEME.getType()));


        if(CollUtil.isNotEmpty(systemConfigSchemeDOS)){

            // 加工方案组的配置信息
            List<ProcessSchemeConfig> processSchemeConfigs = new ArrayList<>();

            systemConfigSchemeDOS.forEach(f->{
                f.setId(null);
                f.setOrganId(organId);
                f.setCreateTime(null);
                f.setCreator(null);
                f.setUpdateTime(null);
                f.setUpdater(null);

                try {
                    processSchemeConfigs.addAll(parseArray(f.getSetting(), ProcessSchemeConfig.class));
                } catch (Exception e) {
                    log.error("加工方案组复制数据异常"+e.getMessage());
                }
            });


            List<String> machineIds = processSchemeConfigs.stream().map(ProcessSchemeConfig::getAnalyzer).distinct().toList();
            List<MachineDO> machineDOS = machineMapper.selectBatchIds(machineIds);
            if(CollUtil.isNotEmpty(machineDOS)){
                machineDOS.forEach(f->{
                    f.setId(null);
                    f.setOrganId(organId);
                    f.setCreateTime(null);
                    f.setCreator(null);
                    f.setUpdateTime(null);
                    f.setUpdater(null);
                });


                List<Long> labelIds = machineDOS.stream().map(MachineDO::getLabelId).distinct().toList();
                List<LabelDO> labelDOS = labelMapper.selectBatchIds(labelIds);
                if(CollUtil.isNotEmpty(labelDOS)){
                    labelDOS.forEach(f->{
                        f.setId(null);
                        f.setOrganId(organId);
                        f.setCreateTime(null);
                        f.setCreator(null);
                        f.setUpdateTime(null);
                        f.setUpdater(null);
                    });

                    labelMapper.insertBatch(labelDOS);
                }

                machineMapper.insertBatch(machineDOS);
            }

            systemConfigSchemeMapper.insertBatch(systemConfigSchemeDOS);
        }
    }



}
