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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cf.imes.framework.common.enums.CommonStatusEnum;
import com.cf.imes.framework.common.exception.ServiceException;
import com.cf.imes.framework.common.pojo.PageResult;
import com.cf.imes.framework.common.util.collection.CollectionUtils;
import com.cf.imes.framework.common.util.object.BeanUtils;
import com.cf.imes.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.cf.imes.framework.security.core.util.SecurityFrameworkUtils;
import com.cf.imes.module.system.controller.admin.organ.vo.packages.TenantPackagePageReqVO;
import com.cf.imes.module.system.controller.admin.organ.vo.packages.TenantPackageSaveReqVO;
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.mysql.organ.TenantPackageMapper;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.cf.imes.module.system.dal.redis.RedisKeyConstants;
import com.cf.imes.module.system.service.permission.PermissionService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import jakarta.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Set;

import static com.cf.imes.module.system.enums.ErrorCodeConstants.*;

/**
 * 组织套餐 Service 实现类
 *
 * @author 晨丰科技
 */
@Service
@Validated
public class TenantPackageServiceImpl implements TenantPackageService {

    @Resource
    private TenantPackageMapper tenantPackageMapper;

    @Resource
    @Lazy // 避免循环依赖的报错
    private OrganService organService;

    @Resource
    private PermissionService permissionService;

    @Override
    public Long createTenantPackage(TenantPackageSaveReqVO createReqVO) {
        // 唯一性校验
        validateTenantPackageUnique(createReqVO);
        // 插入
        TenantPackageDO tenantPackage = BeanUtils.toBean(createReqVO, TenantPackageDO.class);
        tenantPackageMapper.insert(tenantPackage);
        // 返回
        return tenantPackage.getId();
    }

    @Override
    @DSTransactional // 多数据源，使用 @DSTransactional 保证本地事务，以及数据源的切换
    @CacheEvict(value = RedisKeyConstants.TENANT_PACKAGE_MENU_IDS, key = "#updateReqVO.id")
    public void updateTenantPackage(TenantPackageSaveReqVO updateReqVO) {
        // 唯一性校验
        validateTenantPackageUnique(updateReqVO);
        // 校验存在
        TenantPackageDO tenantPackage = validateTenantPackageExists(updateReqVO.getId());
        if (Boolean.FALSE.equals(SecurityFrameworkUtils.isSuperAdmin()) &&
                (Objects.equals(tenantPackage.getId(), SYSTEM_ORGAN_PACKAGE_ID) || Objects.equals(tenantPackage.getId(), SYSTEM_SUPER_PACKAGE_ID))) {
            throw new ServiceException(TENANT_PACKAGE_DEPT_EXIT);
        }

        // 更新
        TenantPackageDO updateObj = BeanUtils.toBean(updateReqVO, TenantPackageDO.class);
        tenantPackageMapper.updateById(updateObj);
        // 如果菜单发生变化，则修改每个组织的菜单
        if (!CollUtil.isEqualList(tenantPackage.getMenuIds(), updateReqVO.getMenuIds())) {
            List<OrganizationDO> tenants = organService.getOrganListByPackageId(tenantPackage.getId());
            permissionService.flushCacheWhenTenantPackageChange(CollectionUtils.convertList(tenants, OrganizationDO::getId));
        }
    }

    @Override
    @CacheEvict(value = RedisKeyConstants.TENANT_PACKAGE_MENU_IDS, key = "#id")
    public void deleteTenantPackage(Long id) {
        // 校验存在
        validateTenantPackageExists(id);
        if(Objects.equals(id, SYSTEM_ORGAN_PACKAGE_ID) || Objects.equals(id, SYSTEM_SUPER_PACKAGE_ID)) {
            throw new ServiceException(TENANT_PACKAGE_DELETED_EXIT);
        }

        // 校验正在使用
        validateOrganUsed(id);
        // 删除
        tenantPackageMapper.deleteById(id);
    }

    private TenantPackageDO validateTenantPackageExists(Long id) {
        TenantPackageDO tenantPackage = tenantPackageMapper.selectById(id);
        if (tenantPackage == null) {
            throw new ServiceException(TENANT_PACKAGE_NOT_EXISTS);
        }
        return tenantPackage;
    }

    /**
     * 校验唯一性约束
     * @param reqVO
     */
    private void validateTenantPackageUnique(TenantPackageSaveReqVO reqVO) {
        Long packageId = reqVO.getId();
        LambdaQueryWrapper<TenantPackageDO> wrapper = new LambdaQueryWrapperX<TenantPackageDO>().eq(TenantPackageDO::getName, reqVO.getName());
        if (ObjectUtil.isNotNull(packageId)) {
            wrapper.ne(TenantPackageDO::getId, packageId);
        }
        if (tenantPackageMapper.exists(wrapper)) {
            throw new ServiceException(TENANT_PACKAGE_NAME_UNIQE_ERROR);
        }
    }

    private void validateOrganUsed(Long id) {
        if (organService.getOrganCountByPackageId(id) > 0) {
            throw new ServiceException(TENANT_PACKAGE_USED);
        }
    }

    @Override
    public TenantPackageDO getTenantPackage(Long id) {
        return tenantPackageMapper.selectById(id);
    }

    @Override
    public PageResult<TenantPackageDO> getTenantPackagePage(TenantPackagePageReqVO pageReqVO) {
        return tenantPackageMapper.selectPage(pageReqVO);
    }

    @Override
    public TenantPackageDO validTenantPackage(Long id) {
        TenantPackageDO tenantPackage = tenantPackageMapper.selectById(id);
        if (tenantPackage == null) {
            throw new ServiceException(TENANT_PACKAGE_NOT_EXISTS);
        }
        if (tenantPackage.getStatus().equals(CommonStatusEnum.DISABLE.getStatus())) {
            throw new ServiceException(TENANT_PACKAGE_DISABLE, tenantPackage.getName());
        }
        return tenantPackage;
    }

    @Override
    public List<TenantPackageDO> getTenantPackageListByStatus(Integer status) {
        return tenantPackageMapper.selectListByStatus(status);
    }

    @Override
    @Cacheable(value = RedisKeyConstants.TENANT_PACKAGE_MENU_IDS, key = "#id", unless = "#result == null", cacheManager = "redisCacheManager")
    public Set<Long> getTenantPackageMenuIds(Long id) {
        validateTenantPackageExists(id);
        TenantPackageDO tenantPackageDO = tenantPackageMapper.selectOne(new LambdaQueryWrapper<TenantPackageDO>().eq(TenantPackageDO::getId, id).select(TenantPackageDO::getMenuIds));
        if (ObjectUtil.isNotNull(tenantPackageDO)) {
            return tenantPackageDO.getMenuIds();
        } else {
            return null;
        }
    }

    @Override
    @Cacheable(value = RedisKeyConstants.TENANT_PACKAGE_MENU_IDS, key = "#productId", unless = "#result == null or #result.isEmpty()", cacheManager = "redisCacheManager")
    public Set<Long> getProductTenantPackageMenuIds(Long productId) {
        TenantPackageDO tenantPackageDO = tenantPackageMapper.selectOne(new LambdaQueryWrapper<TenantPackageDO>().eq(TenantPackageDO::getProductId, productId).select(TenantPackageDO::getMenuIds));
        if (ObjectUtil.isNotNull(tenantPackageDO)) {
            return tenantPackageDO.getMenuIds();
        } else {
            return Set.of();
        }
    }
}
