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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.activity.add.dto.AcAddUpgradeRecordDTO;
import com.hzs.activity.add.mapper.AcAddUpgradeConfigMapper;
import com.hzs.activity.add.param.*;
import com.hzs.activity.add.service.IAcAddUpgradeConfigService;
import com.hzs.common.domain.activity.add.AcAddUpgradeConfig;
import com.hzs.activity.base.param.ActivityParam;
import com.hzs.activity.base.service.IAcBaseConfigService;
import com.hzs.activity.base.service.IAcGoalMemberConfigService;
import com.hzs.activity.base.service.IActivityService;
import com.hzs.common.core.enums.EActType;
import com.hzs.common.core.enums.EApprovalBusiness;
import com.hzs.common.core.enums.EControlType;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.domain.activity.add.AcAddUpgradeRecord;
import com.hzs.common.domain.activity.add.ext.AcAddUpgradeConfigExt;
import com.hzs.common.domain.activity.base.AcBaseConfig;
import com.hzs.common.domain.activity.base.AcGoalMemberConfig;
import com.hzs.common.domain.sale.order.SaOrderItems;
import com.hzs.common.domain.system.config.BdGrade;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.sale.order.param.OrderItemsParam;
import com.hzs.sale.order.param.OrderParam;
import com.hzs.sale.order.param.OrderReturn;
import com.hzs.system.config.dto.GradeDTO;
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.stream.Collectors;

/**
 * <p>
 * 加购升级配置表 服务实现类
 * </p>
 *
 * @author bd
 * @since 2025-10-13
 */
@Service
@Slf4j
public class AcAddUpgradeConfigServiceImpl extends ServiceImpl<AcAddUpgradeConfigMapper, AcAddUpgradeConfig> implements IAcAddUpgradeConfigService {

    @Autowired
    private IActivityService iActivityService;

    @Autowired
    private IAcBaseConfigService baseConfigService;

    @Autowired
    private IAcGoalMemberConfigService iAcGoalMemberConfigService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public String onLinePetition(AcAddUpgradeParam acAddUpgradeParam) {
        log.info("加购升级入参{}", acAddUpgradeParam);
        EApprovalBusiness approvalBusiness = null;
        if (acAddUpgradeParam.getControlType() == EControlType.SAVE.getValue()) {
            approvalBusiness = EApprovalBusiness.PRODUCT_GIFT_ADD;
        } else if (acAddUpgradeParam.getControlType() == EControlType.MODIFY.getValue()) {
            approvalBusiness = EApprovalBusiness.PRODUCT_GIFT_UPDATE;
        } else if (acAddUpgradeParam.getControlType() == EControlType.DELETE.getValue()) {
            approvalBusiness = EApprovalBusiness.PRODUCT_GIFT_REMOVE;
        }

        LoginUser loginUser = acAddUpgradeParam.getLoginUser();
        if (loginUser == null) {
            log.error("登录用户信息为空");
            return "登录用户信息为空";
        }
        if (acAddUpgradeParam.getControlType().equals(EControlType.SAVE.getValue())) {
            ActivityParam activityParam = acAddUpgradeParam.getActivityParam();
            activityParam.setPkCountry(loginUser.getDataCountry());
            activityParam.setPkCreator(loginUser.getUserId());
            activityParam.setActType(EActType.ADD_UPGRADE.getValue());
            // 新增活动基本配置
            AcBaseConfig acBaseConfig = iActivityService.saveBaseConfig(activityParam);
            // 新增加购活动配置
            saveAddUpgradeConfig(acAddUpgradeParam.getAcAddUpgradeConfigParam(), acBaseConfig);
        } else if (acAddUpgradeParam.getControlType().equals(EControlType.MODIFY.getValue())) {
            ActivityParam activityParam = acAddUpgradeParam.getActivityParam();
            activityParam.setPkCountry(loginUser.getDataCountry());
            activityParam.setPkCreator(loginUser.getUserId());
            activityParam.setActType(EActType.ADD_UPGRADE.getValue());
            updateAddUpgradeConfig(activityParam, acAddUpgradeParam.getAcAddUpgradeConfigParam());
        } else if (acAddUpgradeParam.getControlType().equals(EControlType.DELETE.getValue())) {
            ActivityParam activityParam = acAddUpgradeParam.getActivityParam();
            Long pkId = activityParam.getPkId();
            removeAddUpgradeConfig(pkId);
        }
        //日志
        ActivityParam activityParam = acAddUpgradeParam.getActivityParam();
        activityParam.setPkCountry(SecurityUtils.getPkCountry());
        activityParam.setPkCreator(SecurityUtils.getUserId());
        activityParam.setActType(EActType.PRODUCT_GIFT.getValue());
        activityParam.setBusinessCode(acAddUpgradeParam.getActivityParam().getBusinessCode());
        iActivityService.createBaseConfigLog(activityParam, new StringBuffer(), null, approvalBusiness.getValue(), false);
        return null;
    }

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

        List<Integer> orderTypes = baseMapper.selectOrderTypeByBaseId(pkId);
        List<AcAddUpgradeConfigParam> list = new ArrayList<>();
        // 组装加购活动详情
        for (Integer orderType : orderTypes) {
            // 根据活动类型查询活动类型集合
            List<AcAddUpgradeRuleConfigParam> acAddUpgradeRuleConfigParams = baseMapper.selectListByOrderType(pkId, orderType);
            list.add(new AcAddUpgradeConfigParam(orderType, acAddUpgradeRuleConfigParams));
        }

        List<AcGoalMemberConfig> goalMemberConfigList = iAcGoalMemberConfigService.list(new LambdaQueryWrapper<AcGoalMemberConfig>()
                .eq(AcGoalMemberConfig::getPkBaseId, baseConfig.getPkId()));
        activityParam.setAcAddUpgradeConfigParams(list);
        activityParam.setGoalMemberConfigList(goalMemberConfigList);
        activityParam.setPkBaseId(baseConfig.getPkId());
        return AjaxResult.success(activityParam);
    }


    private void removeAddUpgradeConfig(Long pkId) {
        // 删除活动基本配置
        baseConfigService.removeById(pkId);
        // 删除加购活动配置
        baseMapper.delete(new LambdaQueryWrapper<AcAddUpgradeConfig>()
                .eq(AcAddUpgradeConfig::getPkBaseId, pkId));
    }

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

            // 删除活动配置
            baseMapper.delete(new LambdaQueryWrapper<AcAddUpgradeConfig>()
                    .eq(AcAddUpgradeConfig::getPkBaseId, pkId));
            // 添加加购活动配置
            saveAddUpgradeConfig(acAddUpgradeConfigParam, baseConfig);
        }
    }

    private void saveAddUpgradeConfig(List<AcAddUpgradeConfigParam> acAddUpgradeConfigParam, AcBaseConfig acBaseConfig) {
        acAddUpgradeConfigParam.forEach(item -> {
            List<AcAddUpgradeRuleConfigParam> acAddUpgradeRuleConfigParams = item.getAcAddUpgradeRuleConfigParams();
            if (acAddUpgradeRuleConfigParams != null) {
                acAddUpgradeRuleConfigParams.forEach(ac -> {
                    // 获取升级后等级值
                    BdGrade UpGrade = baseMapper.selectGradeValue(ac.getUpgradeLevel());
                    // 获取升级前等级值
                    BdGrade OriginalGrade = baseMapper.selectGradeValue(ac.getOriginalLevel());
                    // 校验升级等级是否小于原等级
                    if (UpGrade.getGradeValue() < OriginalGrade.getGradeValue()) {
                        throw new IllegalArgumentException(
                                String.format("原等级 [%s] 大于升级等级 [%s]，不允许插入！",
                                        OriginalGrade.getGradeName(), UpGrade.getGradeName())
                        );
                    }
                    AcAddUpgradeConfig build = AcAddUpgradeConfig.builder()
                            .pkBaseId(acBaseConfig.getPkId())
                            .orderType(item.getOrderType())
                            .pkWares(ac.getPkWares())
                            .quantity(ac.getQuantity())
                            .originalLevel(ac.getOriginalLevel())
                            .upgradeLevel(ac.getUpgradeLevel())
                            .build();
                    build.setPkCountry(acBaseConfig.getPkCountry());
                    build.setCreationTime(acBaseConfig.getCreationTime());
                    build.setPkCreator(acBaseConfig.getPkCreator());
                    build.setDelFlag(0);
                    baseMapper.insert(build);
                });
            }

        });
    }

    @Override
    public void handleAddUpgrade(OrderParam orderParam, OrderReturn orderReturn) {
        List<OrderItemsParam> orderItemsParams = orderParam.getOrderItemsParams();
        if (CollectionUtil.isEmpty(orderItemsParams)) {
            return;
        }

        List<AcAddUpgradeConfigExt> configExtList = baseMapper.getUpgradeConfig(orderParam.getSpecialArea(), orderReturn.getPkGradeTmp());
        if (CollectionUtil.isNotEmpty(configExtList)) {
            for (AcAddUpgradeConfigExt configExt : configExtList) {
                for (OrderItemsParam orderItemsParam : orderItemsParams) {
                    if (orderItemsParam.getWaresCode().equals(configExt.getWaresCode())
                            && orderItemsParam.getQuantity() >= configExt.getQuantity()) {
                        orderReturn.setPkGradeVal(configExt.getGradeName());
                        return;
                    }
                }
            }
        }
    }

    @Override
    public AcAddUpgradeRecordDTO handleAddUpgrade(Integer specialArea, List<SaOrderItems> orderItemsList, Integer pkGrade) {
        if (CollectionUtil.isEmpty(orderItemsList)) {
            return null;
        }

        List<AcAddUpgradeConfigExt> configExtList = baseMapper.getUpgradeConfig(specialArea, pkGrade);
        if (CollectionUtil.isNotEmpty(configExtList)) {
            for (AcAddUpgradeConfigExt configExt : configExtList) {
                for (SaOrderItems orderItemsParam : orderItemsList) {
                    if (orderItemsParam.getPkWares().equals(configExt.getPkWares())
                            && orderItemsParam.getWaresQuantity() >= configExt.getQuantity()) {
                        AcAddUpgradeRecordDTO dto = new AcAddUpgradeRecordDTO();
                        dto.setAcAddUpgradeRecord(AcAddUpgradeRecord.builder()
                                .pkBaseId(configExt.getPkBaseId())
                                .pkRuleId(configExt.getPkId())
                                .pkOriginGrade(configExt.getOriginalLevel())
                                .pkUpgradeGrade(configExt.getUpgradeLevel())
                                .build());
                        dto.setGradeDTO(GradeDTO.builder()
                                .pkId(configExt.getUpgradeLevel())
                                .gradeValue(configExt.getGradeValue())
                                .gradeName(configExt.getGradeName())
                                .pkAwards(configExt.getPkAwards())
                                .registerAuthority(configExt.getRegisterAuthority())
                                .build());

                        return dto;
                    }
                }
            }
        }
        return null;
    }

}
