package com.hzs.activity.declaration.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hzs.activity.base.param.ActivityParam;
import com.hzs.activity.base.service.IAcBaseConfigService;
import com.hzs.activity.base.service.IActivityService;
import com.hzs.activity.declaration.mapper.AcDeclarationGiftConfigMapper;
import com.hzs.activity.declaration.param.AcDeclarationConfigParam;
import com.hzs.activity.declaration.param.AcDeclarationDetailParam;
import com.hzs.activity.declaration.param.AcDeclarationParam;
import com.hzs.activity.declaration.param.AcDeclarationProductParam;
import com.hzs.activity.declaration.service.IAcDeclarationGiftConfigService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.activity.declaration.service.IAcDeclarationGiftDetailService;
import com.hzs.common.domain.activity.declaration.AcDeclarationGiftConfig;
import com.hzs.common.domain.activity.declaration.AcDeclarationGiftDetail;
import com.hzs.common.core.constant.CountryConstants;
import com.hzs.common.core.enums.EActType;
import com.hzs.common.core.enums.EApprovalBusiness;
import com.hzs.common.core.enums.ERegistrationAuthority;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.domain.activity.base.AcBaseConfig;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.sale.product.service.IBdProductService;
import com.hzs.system.config.IGradeServiceApi;
import com.hzs.system.sys.dto.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author bd
 * @since 2025-10-13
 */
@Service
@Slf4j
public class AcDeclarationGiftConfigServiceImpl extends ServiceImpl<AcDeclarationGiftConfigMapper, AcDeclarationGiftConfig> implements IAcDeclarationGiftConfigService {

    @Autowired
    private IActivityService iActivityService;

    @Autowired
    private IAcBaseConfigService baseConfigService;

    @Autowired
    private IAcDeclarationGiftDetailService iAcDeclarationGiftDetailService;

    @Autowired
    private IBdProductService iBdProductService;
    @Autowired
    private IAcBaseConfigService iAcBaseConfigService;
    @Autowired
    private IAcDeclarationGiftConfigService iAcDeclarationGiftConfigService;
    @Autowired
    private IGradeServiceApi iGradeServiceApi;

    @Override
    public AjaxResult getDetail(Integer pkId) {
        AcBaseConfig baseConfig = baseConfigService.getById(pkId);
        AcDeclarationDetailParam activityParam = BeanUtil.copyProperties(baseConfig, AcDeclarationDetailParam.class);

        List<AcDeclarationGiftConfig> list = baseMapper.selectList(new LambdaQueryWrapper<AcDeclarationGiftConfig>()
                .eq(AcDeclarationGiftConfig::getPkBaseId, pkId)
                .eq(AcDeclarationGiftConfig::getDelFlag, 0));
        ArrayList<AcDeclarationConfigParam> acDeclarationConfigParams = new ArrayList<>();
        list.forEach(item -> {
            AcDeclarationConfigParam acDeclarationConfigParam = BeanUtil.copyProperties(item, AcDeclarationConfigParam.class);
            List<AcDeclarationProductParam> declarationConfigParams = iAcDeclarationGiftDetailService.listByPKRuleId(item.getPkId());
            acDeclarationConfigParam.setAcDeclarationProductParamList(declarationConfigParams);
            acDeclarationConfigParams.add(acDeclarationConfigParam);
        });

        activityParam.setAcDeclarationConfigParams(acDeclarationConfigParams);
        activityParam.setPkBaseId(baseConfig.getPkId());
        return AjaxResult.success(activityParam);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String saveConfig(AcDeclarationParam acDeclarationParam) {
        LoginUser loginUser = acDeclarationParam.getLoginUser();
        if (loginUser == null) {
            log.error("登录用户信息为空");
            return "登录用户信息为空";
        }
        String validated = validateDuplicateConfig(acDeclarationParam);
        if (validated != null) {
            return validated;
        }
        ActivityParam activityParam = acDeclarationParam.getActivityParam();
        activityParam.setPkCountry(loginUser.getDataCountry());
        activityParam.setPkCreator(loginUser.getUserId());
        activityParam.setActType(EActType.DECLARATION_GIFT.getValue());
        // 新增活动基本配置
        AcBaseConfig acBaseConfig = iActivityService.saveBaseConfig(activityParam);
        // 新增加购活动配置
        saveDeclarationConfig(acDeclarationParam.getAcDeclarationConfigParams(), acBaseConfig);
        //日志
        activityParam.setBusinessCode(acDeclarationParam.getActivityParam().getBusinessCode());
        iActivityService.createBaseConfigLog(activityParam, new StringBuffer(), null, EApprovalBusiness.AC_DECLARATION_GIFT_ADD.getValue(), false);
        return null;
    }

    private String validateDuplicateConfig(AcDeclarationParam acDeclarationParam) {
        List<AcDeclarationConfigParam> acDeclarationConfigParams = acDeclarationParam.getAcDeclarationConfigParams();

        // 获取当前时间还有效的报单赠送活动
        LambdaQueryWrapper<AcBaseConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.le(AcBaseConfig::getActStartDate, new Date())
                .ge(AcBaseConfig::getActEndDate, new Date())
                .eq(AcBaseConfig::getActType, EActType.DECLARATION_GIFT.getValue())
                .eq(AcBaseConfig::getDelFlag, 0);
        if (acDeclarationParam.getActivityParam().getPkId() != null) {
            queryWrapper.ne(AcBaseConfig::getPkId, acDeclarationParam.getActivityParam().getPkId());
        }
        List<AcBaseConfig> validBaseConfigs = iAcBaseConfigService.list(queryWrapper);

        // 先把新增组合转换成List
        List<String> newComboList = acDeclarationConfigParams.stream()
                .filter(Objects::nonNull)
                .map(cfg -> ERegistrationAuthority.getEnumByValue(cfg.getRegisterAuthority()).getLabel()
                        + "_" + iGradeServiceApi.getGrade(cfg.getSpecifyLevel()).getData().getGradeName())
                .collect(Collectors.toList());

        // 校验新增组合内部是否有重复
        Map<String, Long> newCountMap = newComboList.stream()
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        Set<String> internalDuplicates = newCountMap.entrySet().stream()
                .filter(entry -> entry.getValue() > 1)
                .map(Map.Entry::getKey)
                .collect(Collectors.toSet());

        if (!internalDuplicates.isEmpty()) {
            return "新增活动配置内部存在重复的报单等级+指定等级组合: " + internalDuplicates;
        }

        // 校验新增组合是否与已有数据库组合重复
        if (!CollectionUtils.isEmpty(validBaseConfigs)) {
            List<Long> baseIds = validBaseConfigs.stream()
                    .map(AcBaseConfig::getPkId)
                    .collect(Collectors.toList());

            List<AcDeclarationGiftConfig> existingConfigs = iAcDeclarationGiftConfigService.list(
                    new LambdaQueryWrapper<AcDeclarationGiftConfig>()
                            .in(AcDeclarationGiftConfig::getPkBaseId, baseIds)
                            .eq(AcDeclarationGiftConfig::getDelFlag, 0)
            );

            Set<String> existingComboSet = existingConfigs.stream()
                    .map(cfg -> ERegistrationAuthority.getEnumByValue(cfg.getRegisterAuthority()).getLabel()
                            + "_" + iGradeServiceApi.getGrade(cfg.getSpecifyLevel()).getData().getGradeName())
                    .collect(Collectors.toSet());

            Set<String> dbDuplicates = newComboList.stream()
                    .filter(existingComboSet::contains)
                    .collect(Collectors.toSet());

            if (!dbDuplicates.isEmpty()) {
                return "新增活动配置中存在与已有活动重复的报单等级+指定等级组合: " + dbDuplicates;
            }
        }

        return null;

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String updateConfig(AcDeclarationParam acDeclarationParam) {
        LoginUser loginUser = acDeclarationParam.getLoginUser();
        if (loginUser == null) {
            log.error("登录用户信息为空");
            return "登录用户信息为空";
        }
        String validated = validateDuplicateConfig(acDeclarationParam);
        if (validated != null) {
            return validated;
        }
        ActivityParam activityParam = acDeclarationParam.getActivityParam();
        activityParam.setPkCountry(loginUser.getDataCountry());
        activityParam.setPkCreator(loginUser.getUserId());
        activityParam.setActType(EActType.DECLARATION_GIFT.getValue());
        updateDeclarationConfig(activityParam, acDeclarationParam.getAcDeclarationConfigParams());
        iActivityService.createBaseConfigLog(activityParam, new StringBuffer(), null, EApprovalBusiness.AC_DECLARATION_GIFT_UPDATE.getValue(), false);
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String deleteConfig(Long pkId) {
        Long userId = SecurityUtils.getUserId();
        if (userId == null) {
            log.error("登录用户信息为空");
            return "登录信息用户为空";
        }
        AcBaseConfig baseConfig = baseConfigService.getById(pkId);
        ActivityParam activityParam = BeanUtil.copyProperties(baseConfig, ActivityParam.class);
        removeDeclarationConfig(pkId);
        iActivityService.createBaseConfigLog(activityParam, new StringBuffer(), null, EApprovalBusiness.AC_DECLARATION_GIFT_REMOVE.getValue(), false);
        return null;
    }


    private void removeDeclarationConfig(Long pkId) {
        // 删除活动基本配置
        baseConfigService.removeById(pkId);
        // 删除报单赠送
        baseMapper.delete(new LambdaQueryWrapper<AcDeclarationGiftConfig>()
                .eq(AcDeclarationGiftConfig::getPkBaseId, pkId));
        // 删除报单赠送详情配置
        iAcDeclarationGiftDetailService.remove(new LambdaQueryWrapper<AcDeclarationGiftDetail>()
                .eq(AcDeclarationGiftDetail::getPkBaseId, pkId));
    }

    private void updateDeclarationConfig(ActivityParam activityParam, List<AcDeclarationConfigParam> acDeclarationConfigParams) {
        {
            Long pkId = activityParam.getPkId();
            // 查询基础信息
            AcBaseConfig baseConfig = BeanUtil.copyProperties(activityParam, AcBaseConfig.class);
            baseConfig.setPkId(activityParam.getPkId());
            baseConfigService.updateById(baseConfig);

            // 删除活动配置
            baseMapper.delete(new LambdaQueryWrapper<AcDeclarationGiftConfig>()
                    .eq(AcDeclarationGiftConfig::getPkBaseId, pkId));
            // 删除活动详情配置
            iAcDeclarationGiftDetailService.remove(new LambdaQueryWrapper<AcDeclarationGiftDetail>()
                    .eq(AcDeclarationGiftDetail::getPkBaseId, pkId));
            // 添加加购活动配置
            saveDeclarationConfig(acDeclarationConfigParams, baseConfig);
        }
    }

    private void saveDeclarationConfig(List<AcDeclarationConfigParam> acDeclarationConfigParams, AcBaseConfig acBaseConfig) {
        acDeclarationConfigParams.forEach(item -> {
            if (item != null) {
                AcDeclarationGiftConfig build = AcDeclarationGiftConfig.builder()
                        .pkBaseId(acBaseConfig.getPkId())
                        .registerAuthority(item.getRegisterAuthority())
                        .specifyLevel(item.getSpecifyLevel())
                        .build();
                build.setPkCountry(acBaseConfig.getPkCountry());
                build.setCreationTime(acBaseConfig.getCreationTime());
                build.setPkCreator(acBaseConfig.getPkCreator());
                build.setDelFlag(0);
                baseMapper.insert(build);
                item.getAcDeclarationProductParamList().forEach(item1 -> {
                    if (item1 != null) {
                        AcDeclarationGiftDetail acDeclarationGiftDetail = AcDeclarationGiftDetail.builder()
                                .pkBaseId(acBaseConfig.getPkId())
                                .pkRuleId(build.getPkId())
                                .pkProduct(item1.getPkProduct())
                                .specsName(item1.getSpecsName())
                                .specsNameId(item1.getSpecsNameId())
                                .quantity(item1.getQuantity())
                                .build();
                        acDeclarationGiftDetail.setPkCountry(acBaseConfig.getPkCountry());
                        acDeclarationGiftDetail.setCreationTime(acBaseConfig.getCreationTime());
                        acDeclarationGiftDetail.setPkCreator(acBaseConfig.getPkCreator());
                        acDeclarationGiftDetail.setDelFlag(0);
                        iAcDeclarationGiftDetailService.save(acDeclarationGiftDetail);
                    }
                });

            }
        });
    }

    @Override
    public void handleDeclarationData() {
        // 所属国家
        Integer pkCountry = CountryConstants.CHINA_COUNTRY;
        // 更新提货列表
        baseMapper.updateOrInsertPick(pkCountry);

    }

}
