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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hzs.activity.base.service.IAcApprovalLogService;
import com.hzs.activity.pick.mapper.AcPickMapper;
import com.hzs.activity.pick.param.AcPickQueryParam;
import com.hzs.activity.pick.param.AcPickSaveDetailParam;
import com.hzs.activity.pick.param.AcPickSaveParam;
import com.hzs.activity.pick.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.activity.pick.vo.ApiPickListVO;
import com.hzs.activity.wares.service.IAcGiftConfigService;
import com.hzs.common.core.constant.RabbitMqConstants;
import com.hzs.common.core.constant.SystemFieldConstants;
import com.hzs.common.core.constant.msg.ActivityMsgConstants;
import com.hzs.common.core.constant.msg.DocumentMsgConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.exception.ServiceException;
import com.hzs.common.core.utils.CommonUtil;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.domain.activity.base.AcApprovalLog;
import com.hzs.common.domain.activity.base.AcPickUpConfig;
import com.hzs.common.domain.activity.base.ext.AcGiftConfigExt;
import com.hzs.common.domain.activity.pick.AcPick;
import com.hzs.common.domain.activity.pick.AcPickLog;
import com.hzs.common.domain.activity.pick.AcPickMemberLog;
import com.hzs.common.domain.activity.pick.ext.AcPickExt;
import com.hzs.common.domain.member.base.CuMember;
import com.hzs.common.domain.sale.product.BdProduct;
import com.hzs.common.util.TransactionUtils;
import com.hzs.member.base.IMemberServiceApi;
import com.hzs.sale.postage.IPostageServiceApi;
import com.hzs.sale.postage.dto.PostageProductDTO;
import com.hzs.sale.product.service.IBdProductService;
import com.hzs.system.sys.dto.ApprovalBusinessResultDTO;
import com.hzs.system.sys.dto.BusinessLogDTO;
import com.hzs.system.sys.dto.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 提货基础表 服务实现类
 */
@Slf4j
@Service
public class AcPickServiceImpl extends ServiceImpl<AcPickMapper, AcPick> implements IAcPickService {

    @Autowired
    private IAcApprovalLogService iAcApprovalLogService;
    @Autowired
    private IAcPickLogService iAcPickLogService;
    @Autowired
    private IAcPickMemberLogService iAcPickMemberLogService;
    @Autowired
    private IAcGiftConfigService iAcGiftConfigService;
    @Autowired
    private IAcPickUpConfigService iAcPickUpConfigService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private IBdProductService iBdProductService;

    @DubboReference
    IMemberServiceApi iMemberServiceApi;
    @DubboReference
    IPostageServiceApi iPostageServiceApi;

    @Override
    public boolean addPickByActivity(Long pkMember, Integer pickType, Long pkBaseConfig, Long pkDataId,
                                     Integer usableQuantity, String pickCover, Date receiveTime, Integer pkPostage,
                                     Long pkCreator, Integer pkCountry, Long pkBaseId, String specsNameId, String specsName) {
        if (baseMapper.addQuantityByActivity(pickType, pkBaseConfig, pkDataId, pkMember, usableQuantity, pkPostage, receiveTime, pkCreator) == 0) {
            AcPick acPick = new AcPick();
            acPick.setPkMember(pkMember);
            acPick.setPickType(pickType);
            if (null != pkBaseConfig) {
                acPick.setPkBaseConfig(pkBaseConfig);
            }
            acPick.setPkDataId(pkDataId);
            acPick.setUsableQuantity(usableQuantity);
            acPick.setPickCover(pickCover);
            if (null != receiveTime) {
                acPick.setReceiveTime(receiveTime);
            }
            if (null != pkPostage) {
                // 处理邮费模板
                acPick.setIsFreeMail(EYesNo.NO.getIntValue());
                acPick.setPkPostage(pkPostage);
            } else {
                acPick.setIsFreeMail(EYesNo.YES.getIntValue());
            }
            acPick.setPkCreator(pkCreator);
            acPick.setPkCountry(pkCountry);
            if (null != pkBaseId) {
                acPick.setPkBaseId(pkBaseId);
            }
            if (null != specsNameId) {
                acPick.setSpecsNameId(specsNameId);
            }
            if (null != specsName) {
                acPick.setSpecsName(specsName);
            }
            return baseMapper.insert(acPick) > 0;
        }
        return true;
    }

    @Override
    public int updatePickUsableByMember(Long pkMember, Integer pickType, Long pkBaseConfig, Long pkDataId, Integer quantity, Long pkModified) {
        return baseMapper.updatePickUsableByMember(pkMember, pickType, pkBaseConfig, pkDataId, quantity, pkModified);
    }

    @Override
    public int updatePickUsableByMemberAndActivityType(Long pkMember, Integer pickType, Long pkBaseConfig,
                                                       Long pkDataId, Integer quantity, Long pkModified) {
        return baseMapper.updatePickUsableByMemberAndActivityType(pkMember, pickType, pkBaseConfig, pkDataId, quantity, pkModified);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updatePickUse(List<AcPickExt> acPickExtList, Integer signSource, List<AcPickMemberLog> acPickMemberLogList) {
        if (ESignSource.BONUS.getValue() == signSource && CollectionUtil.isNotEmpty(acPickMemberLogList)) {
            // 回退数量
            baseMapper.updateBackPickUseBatch(acPickMemberLogList);
            iAcPickMemberLogService.deleteBatch(acPickMemberLogList);
        }
        // 批量更新提货使用数量
        baseMapper.updatePickUseBatch(acPickExtList, acPickExtList.size());

        // 批量插入提货日志
        iAcPickMemberLogService.insertBatch(acPickExtList, 1, signSource);
        return Boolean.TRUE;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updatePickUse(List<AcPickExt> acPickExtList, List<AcPickMemberLog> acPickMemberLogList) {
        if (CollectionUtil.isNotEmpty(acPickMemberLogList)) {
            // 回退数量
            baseMapper.updateBackPickUseBatch(acPickMemberLogList);
            iAcPickMemberLogService.deleteBatch(acPickMemberLogList);
        }
        // 批量更新提货使用数量
        baseMapper.updatePickUseCouponBatch(acPickExtList);
        // 批量插入提货日志
        iAcPickMemberLogService.insertBatchPick(acPickExtList, ESignSource.BONUS.getValue());
        return Boolean.TRUE;
    }

    @Override
    public List<AcPickExt> queryList(AcPickQueryParam param, Integer pkCountry) {
        return baseMapper.queryList(param, pkCountry);
    }

    @Override
    public AcPickExt queryDetail(Long pkId, Integer pkCountry) {
        return baseMapper.queryDetail(pkId, pkCountry);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String pickSubmit(AcPickSaveParam param, LoginUser loginUser) {
        // 会员ID
        Long userId = loginUser.getUserId();
        // 所属国家
        Integer pkCountry = loginUser.getDataCountry();

        // 业务编号
        String businessCode = CommonUtil.createSerialNumber(EOrderPrefix.ACTIVITY_CODE);

        // 操作日志列表
        List<BusinessLogDTO> logDTOList = new ArrayList<>();

//        // 批量保存日志
//        List<AcApprovalLog> approvalLogList = new ArrayList<>();

        // 产品数据map
        Map<Integer, BdProduct> productMap = iBdProductService.queryProductMap(param.getDetailList().stream().map(AcPickSaveDetailParam::getPkProduct).collect(Collectors.toList()), pkCountry);

        // 新増提货列表
        List<AcPick> createList = new ArrayList<>();
        // 修改提货列表
        List<AcPick> updateList = new ArrayList<>();

        for (AcPickSaveDetailParam detailParam : param.getDetailList()) {
//            // 活动审批日志
//            AcApprovalLog acApprovalLog = new AcApprovalLog();
//            acApprovalLog.setApprovalType(EApprovalBusiness.PICK_ADD.getValue());
//            acApprovalLog.setBusinessCode(businessCode);
//            acApprovalLog.setPkCreator(userId);
//            acApprovalLog.setPkCountry(pkCountry);
//            acApprovalLog.setAfterData(JSONUtil.toJsonStr(detailParam));
//            if (null != detailParam.getPkId()) {
//                acApprovalLog.setPkBusiness(detailParam.getPkId());
//            }
//            approvalLogList.add(acApprovalLog);

            // 会员信息
            CuMember cuMember = iMemberServiceApi.queryMember(detailParam.getMemberCode()).getData();
            // 提货ID
            Long pickId = null;
            // 提货类型
            Integer pickType = null != detailParam.getPickType() ? detailParam.getPickType() : EPickType.PICK_PRODUCT.getValue();

            if (null == detailParam.getPkId()) {
                LambdaQueryWrapper<AcPick> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(AcPick::getPickType, pickType);
                queryWrapper.eq(AcPick::getPkBaseConfig, 0);
                queryWrapper.eq(AcPick::getPkDataId, detailParam.getPkProduct());
                queryWrapper.eq(AcPick::getSpecsNameId, detailParam.getSpecsNameId());
                queryWrapper.eq(AcPick::getPkMember, cuMember.getPkId());
                AcPick acPick = this.getOne(queryWrapper);
                if (null != acPick) {
                    pickId = acPick.getPkId();
                }
            } else {
                pickId = detailParam.getPkId();
            }

            AcPick acPick = new AcPick();
            if (null == pickId) {
                // 新增提货数据
                acPick.setPkMember(cuMember.getPkId());
                acPick.setPickType(pickType);
                acPick.setPkDataId(detailParam.getPkProduct().longValue());
                acPick.setSpecsName(detailParam.getSpecsName());
                acPick.setSpecsNameId(detailParam.getSpecsNameId());
                acPick.setUsableQuantity(detailParam.getQuantity());
                acPick.setBaseQuantity(detailParam.getBaseQuantity());
                acPick.setReceiveTime(detailParam.getReceiveTime());
                acPick.setIsFreeMail(detailParam.getIsFreeMail());
                acPick.setPkPostage(detailParam.getPkPostage());
                acPick.setPkCreator(userId);
                acPick.setPkCountry(pkCountry);
                createList.add(acPick);
            } else {
                // 修改提货数据
                acPick.setPkId(pickId);
                acPick.setUsableQuantity(detailParam.getQuantity());
                acPick.setBaseQuantity(detailParam.getBaseQuantity());
                acPick.setReceiveTime(detailParam.getReceiveTime());
                acPick.setIsFreeMail(detailParam.getIsFreeMail());
                acPick.setPkPostage(detailParam.getPkPostage());
                acPick.setPkModified(userId);
                acPick.setModifiedTime(new Date());
                updateList.add(acPick);
            }


            // 产品信息
            BdProduct bdProduct = productMap.get(detailParam.getPkProduct());
            // 操作日志内容
            StringBuilder content = new StringBuilder();
            content.append("会员编号 ").append(detailParam.getMemberCode());
            content.append(" 充值提货卡 ").append(bdProduct.getProductName()).append("(").append(detailParam.getSpecsName()).append(")");
            content.append("，提货基数 ").append(detailParam.getBaseQuantity());
            content.append("，充值数量 ").append(detailParam.getQuantity());
            if (null != detailParam.getReceiveTime()) {
                content.append("，截止日期 ").append(DateUtils.parseDateToFormat(DateUtils.YYYY_MM_DD_HH_MM_SS, detailParam.getReceiveTime()));
            }
            if (EYesNo.YES.getIntValue() == detailParam.getIsFreeMail()) {
                content.append("，包邮；");
            } else {
                content.append("，不包邮；");
            }
            // 封装业务操作日志
            logDTOList.add(BusinessLogDTO.builder()
                    .businessType(EApprovalBusiness.PICK_ADD.getValue())
                    .businessCode(businessCode)
                    .content(content.toString())
                    .pkMember(cuMember.getPkId())
                    .pkCreator(userId)
                    .pkCountry(pkCountry)
                    .freeSignFlag(false)
                    .build());
        }

        // 提货操作日志
        List<AcPickLog> logList = new ArrayList<>();

        // 插入提货数据
        if (CollectionUtil.isNotEmpty(createList)) {
            for (AcPick acPick : createList) {
                this.baseMapper.insert(acPick);

                AcPickLog acPickLog = new AcPickLog();
                acPickLog.setPkPick(acPick.getPkId());
                acPickLog.setQuantity(acPick.getUsableQuantity());
                acPickLog.setPkUser(userId);
                acPickLog.setPkCountry(pkCountry);
                logList.add(acPickLog);
            }
        }
        // 更新提货数据
        if (CollectionUtil.isNotEmpty(updateList)) {
            for (AcPick acPick : updateList) {
                this.baseMapper.updatePickByPkId(acPick);

                AcPickLog acPickLog = new AcPickLog();
                acPickLog.setPkPick(acPick.getPkId());
                acPickLog.setQuantity(acPick.getUsableQuantity());
                acPickLog.setPkUser(userId);
                acPickLog.setPkCountry(pkCountry);
                logList.add(acPickLog);
            }
        }
        // 插入提货操作日志
        iAcPickLogService.insertBatch(logList);

        // 推送业务操作日志
        rabbitTemplate.convertAndSend(RabbitMqConstants.BUSINESS_LOG_EXCHANGE, RabbitMqConstants.BUSINESS_LOG_KEY, logDTOList);
        return null;

//        if (iAcApprovalLogService.saveBatch(approvalLogList)) {
//            // 保存审批日志成功，提交签呈
//
//            // 提交签呈处理
//            R<String> resultR = iApprovalServiceApi.submitOrder(
//                    ApprovalSubmitDTO.builder()
//                            .eApprovalBusiness(EApprovalBusiness.PICK_ADD)
//                            .businessCode(businessCode)
//                            .signType(ESignType.getEnumByValue(param.getSignType()))
//                            .userIdList(param.getUserIdList())
//                            .sendIdList(param.getSendIdList())
//                            .remark(param.getRemark())
//                            .fileList(param.getFileList())
//                            .build(),
//                    loginUser,
//                    null
//            );
//            if (resultR.isSuccess()) {
//                // 推送业务操作日志
//                rabbitTemplate.convertAndSend(RabbitMqConstants.BUSINESS_LOG_EXCHANGE, RabbitMqConstants.BUSINESS_LOG_KEY, logDTOList);
//
//                return null;
//            }
//            throw new BaseException(TransactionUtils.getContent(CommonMsgConstants.OPERATION_FAILED) + ": " + resultR.getMsg());
//        }
//        return TransactionUtils.getContent(CommonMsgConstants.OPERATION_FAILED);
    }

    @Override
    public boolean delPick(AcPickSaveParam param) {
        // 会员ID
        Long userId = param.getLoginUser().getUserId();
        // 所属国家
        Integer pkCountry = param.getLoginUser().getDataCountry();
        // 业务编号
        String businessCode = CommonUtil.createSerialNumber(EOrderPrefix.ACTIVITY_CODE);

        // 操作日志列表
        List<BusinessLogDTO> logDTOList = new ArrayList<>();

        // 删除提货列表
        List<AcPick> updateList = new ArrayList<>();

//        // 批量保存日志
//        List<AcApprovalLog> approvalLogList = new ArrayList<>();

        for (AcPickSaveDetailParam detailParam : param.getDetailList()) {
//            // 活动审批日志
//            AcApprovalLog acApprovalLog = new AcApprovalLog();
//            acApprovalLog.setApprovalType(EApprovalBusiness.PICK_ADD_DEL.getValue());
//            acApprovalLog.setBusinessCode(businessCode);
//            acApprovalLog.setPkCreator(userId);
//            acApprovalLog.setPkCountry(pkCountry);
//            acApprovalLog.setAfterData(JSONUtil.toJsonStr(detailParam));
//            if (null != detailParam.getPkId()) {
//                acApprovalLog.setPkBusiness(detailParam.getPkId());
//            }
//            approvalLogList.add(acApprovalLog);

            // 被操作会员
            CuMember cuMember = iMemberServiceApi.queryMember(detailParam.getMemberCode()).getData();
            // 提货ID
            Long pickId = null;
            if (null == detailParam.getPkId()) {
                LambdaQueryWrapper<AcPick> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(AcPick::getPickType, EPickType.PICK_PRODUCT.getValue());
                queryWrapper.eq(AcPick::getPkBaseConfig, 0);
                queryWrapper.eq(AcPick::getPkDataId, detailParam.getPkProduct());
                queryWrapper.eq(AcPick::getPkMember, cuMember.getPkId());
                AcPick acPick = this.getOne(queryWrapper);
                if (null != acPick) {
                    pickId = acPick.getPkId();
                }
            } else {
                pickId = detailParam.getPkId();
            }

            AcPick acPick = new AcPick();
            if (null != pickId) {
                // 删除提货数据
                acPick.setPkId(pickId);
                acPick.setPkModified(userId);
                acPick.setModifiedTime(new Date());
                updateList.add(acPick);
            } else {
                log.error("提货充值同意处理失败: 更新数据失败");
                throw new ServiceException(TransactionUtils.getContent(DocumentMsgConstants.DOCUMENT_ORDER_ERROR));
            }

            // 操作日志内容
            StringBuilder content = new StringBuilder("删除会员编号 ").append(detailParam.getMemberCode()).append(" 的 ");

            // 查询提货数量
            AcPick delAcPick = this.getById(detailParam.getPkId());
            EPickType ePickType = EPickType.getEnumByValue(delAcPick.getPickType());
            switch (ePickType) {
                case PICK_PRODUCT:
                case PRIZE:
                case COUPON:
                    // 提货产品、抽奖、创客沙棘提货、复购提货、代金券
                    if (null != detailParam.getPkProduct()) {
                        BdProduct product = iBdProductService.getProduct(detailParam.getPkProduct());
                        content.append(ePickType.getLabel()).append("，").append(product.getProductName()).append("(").append(delAcPick.getSpecsName()).append(")；");
                    } else {
                        content.append(ePickType.getLabel()).append("，").append("；");
                    }
                    break;
                case CONSUMPTION_GIFT:
                case DIRECT_PUSH_GIFT:
                case LOTTERY_DRAW:
                    // 消费赠送、直推赠送、抽奖
                    content.append(ePickType.getLabel());
                    List<AcGiftConfigExt> acGiftConfigList = iAcGiftConfigService.queryListByRuleIdList(delAcPick.getPkDataId(), delAcPick.getPkCountry());
                    if (CollectionUtil.isNotEmpty(acGiftConfigList)) {
                        content.append("，");
                        for (AcGiftConfigExt acGiftConfigExt : acGiftConfigList) {
                            content.append(acGiftConfigExt.getProductName()).append("(").append(acGiftConfigExt.getSpecsName()).append(") ");
                        }
                    }
                    content.append("；");
                    break;
                default:
            }
            // 封装业务操作日志
            logDTOList.add(BusinessLogDTO.builder()
                    .businessType(EApprovalBusiness.PICK_ADD_DEL.getValue())
                    .businessCode(businessCode)
                    .content(content.toString())
                    .pkMember(null != cuMember ? cuMember.getPkId() : null)
                    .pkCreator(userId)
                    .pkCountry(pkCountry)
                    .freeSignFlag(false)
                    .build());
        }

        // 更新提货数据
        if (CollectionUtil.isNotEmpty(updateList)) {
            for (AcPick acPick : updateList) {
                this.baseMapper.removePickByPkId(acPick);
            }
        }

        // 推送业务操作日志
        rabbitTemplate.convertAndSend(RabbitMqConstants.BUSINESS_LOG_EXCHANGE, RabbitMqConstants.BUSINESS_LOG_KEY, logDTOList);

//        if (iAcApprovalLogService.saveBatch(approvalLogList)) {
//            // 保存审批日志成功，提交签呈
//            // 提交签呈处理
//            R<String> resultR = iApprovalServiceApi.submitOrder(
//                    ApprovalSubmitDTO.builder()
//                            .eApprovalBusiness(EApprovalBusiness.PICK_ADD_DEL)
//                            .businessCode(businessCode)
//                            .signType(ESignType.getEnumByValue(param.getSignType()))
//                            .userIdList(param.getUserIdList())
//                            .sendIdList(param.getSendIdList())
//                            .remark(param.getRemark())
//                            .fileList(param.getFileList())
//                            .build(),
//                    param.getLoginUser(),
//                    null
//            );
//            if (resultR.isSuccess()) {
//                // 推送业务操作日志
//                rabbitTemplate.convertAndSend(RabbitMqConstants.BUSINESS_LOG_EXCHANGE, RabbitMqConstants.BUSINESS_LOG_KEY, logDTOList);
//
//                return true;
//            }
//            throw new BaseException(TransactionUtils.getContent(CommonMsgConstants.OPERATION_FAILED) + ": " + resultR.getMsg());
//        }
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String pickApprovalAgree(ApprovalBusinessResultDTO resultDTO) {
        // 用户ID
        Long userId = resultDTO.getLoginUser().getUserId();
        // 所属国家
        Integer pkCountry = resultDTO.getLoginUser().getDataCountry();

        List<AcApprovalLog> approvalLogList = iAcApprovalLogService.queryApprovalLogList(resultDTO.getEApprovalBusiness(), resultDTO.getBusinessCode(), pkCountry);
        // 一批审批可能有多个
        AcApprovalLog approvalLog = approvalLogList.get(0);
        if (null == approvalLog) {
            log.error("提货充值同意处理失败: 签呈不存在!");
            return TransactionUtils.getContent(ActivityMsgConstants.PICK_NOT_EXIST);
        }
        if (EAgentApprovalStatus.UNAPPROVED.getValue() != approvalLog.getApprovalStatus()) {
            log.error("提货充值同意处理失败: 签呈已处理");
            return TransactionUtils.getContent(ActivityMsgConstants.PICK_PROCESSED);
        }

        // 新増提货列表
        List<AcPick> createList = new ArrayList<>();
        // 修改提货列表
        List<AcPick> updateList = new ArrayList<>();

        for (AcApprovalLog acApprovalLog : approvalLogList) {
            // 存在业务ID，则为修改
            AcPickSaveDetailParam detailParam = JSONUtil.toBean(acApprovalLog.getAfterData(), AcPickSaveDetailParam.class);
            // 当前会员
            CuMember cuMember = iMemberServiceApi.getMember(detailParam.getMemberCode()).getData();
            // 提货ID
            Long pickId = null;
            // 提货类型
            Integer pickType = null != detailParam.getPickType() ? detailParam.getPickType() : EPickType.PICK_PRODUCT.getValue();

            if (null == detailParam.getPkId()) {
                LambdaQueryWrapper<AcPick> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(AcPick::getPickType, pickType);
                queryWrapper.eq(AcPick::getPkBaseConfig, 0);
                queryWrapper.eq(AcPick::getPkDataId, detailParam.getPkProduct());
                queryWrapper.eq(AcPick::getSpecsNameId, detailParam.getSpecsNameId());
                queryWrapper.eq(AcPick::getPkMember, cuMember.getPkId());
                AcPick acPick = this.getOne(queryWrapper);
                if (null != acPick) {
                    pickId = acPick.getPkId();
                }
            } else {
                pickId = detailParam.getPkId();
            }

            AcPick acPick = new AcPick();
            if (null == pickId) {
                // 新增提货数据
                acPick.setPkMember(cuMember.getPkId());
                acPick.setPickType(pickType);
                acPick.setPkDataId(detailParam.getPkProduct().longValue());
                acPick.setSpecsName(detailParam.getSpecsName());
                acPick.setSpecsNameId(detailParam.getSpecsNameId());
                acPick.setUsableQuantity(detailParam.getQuantity());
                acPick.setBaseQuantity(detailParam.getBaseQuantity());
                acPick.setReceiveTime(detailParam.getReceiveTime());
                acPick.setIsFreeMail(detailParam.getIsFreeMail());
                acPick.setPkPostage(detailParam.getPkPostage());
                acPick.setPkCreator(userId);
                acPick.setPkCountry(pkCountry);
                createList.add(acPick);
            } else {
                // 修改提货数据
                acPick.setPkId(pickId);
                acPick.setUsableQuantity(detailParam.getQuantity());
                acPick.setBaseQuantity(detailParam.getBaseQuantity());
                acPick.setReceiveTime(detailParam.getReceiveTime());
                acPick.setIsFreeMail(detailParam.getIsFreeMail());
                acPick.setPkPostage(detailParam.getPkPostage());
                acPick.setPkModified(userId);
                acPick.setModifiedTime(new Date());
                updateList.add(acPick);
            }
        }

        if (iAcApprovalLogService.updateApprovalLog(resultDTO.getEApprovalBusiness(), resultDTO.getBusinessCode(), pkCountry, userId, EApproveRechargeStatus.AGREE, resultDTO.getApproveRemark())) {
            // 更新修改记录

            // 提货操作日志
            List<AcPickLog> logList = new ArrayList<>();

            // 插入提货数据
            if (CollectionUtil.isNotEmpty(createList)) {
                for (AcPick acPick : createList) {
                    this.baseMapper.insert(acPick);

                    AcPickLog acPickLog = new AcPickLog();
                    acPickLog.setPkPick(acPick.getPkId());
                    acPickLog.setQuantity(acPick.getUsableQuantity());
                    acPickLog.setPkUser(userId);
                    acPickLog.setPkCountry(pkCountry);
                    logList.add(acPickLog);
                }
            }
            // 更新提货数据
            if (CollectionUtil.isNotEmpty(updateList)) {
                for (AcPick acPick : updateList) {
                    this.baseMapper.updatePickByPkId(acPick);

                    AcPickLog acPickLog = new AcPickLog();
                    acPickLog.setPkPick(acPick.getPkId());
                    acPickLog.setQuantity(acPick.getUsableQuantity());
                    acPickLog.setPkUser(userId);
                    acPickLog.setPkCountry(pkCountry);
                    logList.add(acPickLog);
                }
            }
            // 插入提货操作日志
            iAcPickLogService.insertBatch(logList);

            return null;
        }
        log.error("提货充值同意处理失败: 更新数据失败");
        return TransactionUtils.getContent(DocumentMsgConstants.DOCUMENT_ORDER_ERROR);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public String delpickApprovalAgree(ApprovalBusinessResultDTO resultDTO) {
        // 用户ID
        Long userId = resultDTO.getLoginUser().getUserId();
        // 所属国家
        Integer pkCountry = resultDTO.getLoginUser().getDataCountry();

        List<AcApprovalLog> approvalLogList = iAcApprovalLogService.queryApprovalLogList(resultDTO.getEApprovalBusiness(), resultDTO.getBusinessCode(), pkCountry);
        // 一批审批可能有多个
        AcApprovalLog approvalLog = approvalLogList.get(0);
        if (null == approvalLog) {
            log.error("提货充值同意处理失败: 签呈不存在!");
            return TransactionUtils.getContent(ActivityMsgConstants.PICK_NOT_EXIST);
        }
        if (EAgentApprovalStatus.UNAPPROVED.getValue() != approvalLog.getApprovalStatus()) {
            log.error("提货充值同意处理失败: 签呈已处理");
            return TransactionUtils.getContent(ActivityMsgConstants.PICK_PROCESSED);
        }

        // 删除提货列表
        List<AcPick> updateList = new ArrayList<>();

        for (AcApprovalLog acApprovalLog : approvalLogList) {
            // 存在业务ID，则为修改
            AcPickSaveDetailParam detailParam = JSONUtil.toBean(acApprovalLog.getAfterData(), AcPickSaveDetailParam.class);
            // 当前会员
            CuMember cuMember = iMemberServiceApi.getMember(detailParam.getMemberCode()).getData();
            // 提货ID
            Long pickId = null;
            if (null == detailParam.getPkId()) {
                LambdaQueryWrapper<AcPick> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(AcPick::getPickType, EPickType.PICK_PRODUCT.getValue());
                queryWrapper.eq(AcPick::getPkBaseConfig, 0);
                queryWrapper.eq(AcPick::getPkDataId, detailParam.getPkProduct());
                queryWrapper.eq(AcPick::getPkMember, cuMember.getPkId());
                AcPick acPick = this.getOne(queryWrapper);
                if (null != acPick) {
                    pickId = acPick.getPkId();
                }
            } else {
                pickId = detailParam.getPkId();
            }

            AcPick acPick = new AcPick();
            if (null != pickId) {
                // 删除提货数据
                acPick.setPkId(pickId);
                acPick.setPkModified(userId);
                acPick.setModifiedTime(new Date());
                updateList.add(acPick);
            } else {
                log.error("提货充值同意处理失败: 更新数据失败");
                return TransactionUtils.getContent(DocumentMsgConstants.DOCUMENT_ORDER_ERROR);
            }
        }

        if (iAcApprovalLogService.updateApprovalLog(resultDTO.getEApprovalBusiness(), resultDTO.getBusinessCode(), pkCountry, userId, EApproveRechargeStatus.AGREE, resultDTO.getApproveRemark())) {
            // 更新修改记录

            // 更新提货数据
            if (CollectionUtil.isNotEmpty(updateList)) {
                for (AcPick acPick : updateList) {
                    this.baseMapper.removePickByPkId(acPick);
                }
            }

            return null;
        }
        log.error("提货充值同意处理失败: 更新数据失败");
        return TransactionUtils.getContent(DocumentMsgConstants.DOCUMENT_ORDER_ERROR);
    }

    @Override
    public String pickApprovalReject(ApprovalBusinessResultDTO resultDTO) {
        // 用户ID
        Long userId = resultDTO.getLoginUser().getUserId();
        // 所属国家
        Integer pkCountry = resultDTO.getLoginUser().getDataCountry();

        List<AcApprovalLog> approvalLogList = iAcApprovalLogService.queryApprovalLogList(resultDTO.getEApprovalBusiness(), resultDTO.getBusinessCode(), pkCountry);
        // 一批审批可能有多个
        AcApprovalLog approvalLog = approvalLogList.get(0);
        if (null == approvalLog) {
            log.error("提货充值驳回处理失败: 签呈不存在!");
            return TransactionUtils.getContent(ActivityMsgConstants.PICK_NOT_EXIST);
        }
        if (EAgentApprovalStatus.UNAPPROVED.getValue() != approvalLog.getApprovalStatus()) {
            log.error("提货充值驳回处理失败: 签呈已处理");
            return TransactionUtils.getContent(ActivityMsgConstants.PICK_PROCESSED);
        }

        if (iAcApprovalLogService.updateApprovalLog(resultDTO.getEApprovalBusiness(), resultDTO.getBusinessCode(), pkCountry, userId, EApproveRechargeStatus.REJECT, resultDTO.getApproveRemark())) {
            return null;
        }
        log.error("提货充值驳回处理失败: 更新数据失败");
        return TransactionUtils.getContent(DocumentMsgConstants.DOCUMENT_ORDER_ERROR);
    }

    @Override
    public List<ApiPickListVO> pickList(Long pkMember, Integer pkCountry) {
        return baseMapper.pickList(pkMember, pkCountry);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean callbackPickOrder(Long pkMember, String orderCode) {
        LambdaQueryWrapper<AcPickMemberLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AcPickMemberLog::getPkMember, pkMember);
        queryWrapper.eq(AcPickMemberLog::getPickOrder, orderCode);
        queryWrapper.eq(AcPickMemberLog::getDelFlag, EDelFlag.DELETE.getValue());
        AcPickMemberLog acPickMemberLog = iAcPickMemberLogService.getOne(queryWrapper);

        AcPick acPick = this.getById(acPickMemberLog.getPkPick());

        if (baseMapper.updatePickUseById(acPick.getPkId(), acPickMemberLog.getPickQuantity(), acPick.getPkMember()) > 0) {
            // 更新使用数量成功
            UpdateWrapper<AcPickMemberLog> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq(SystemFieldConstants.PK_ID, acPickMemberLog.getPkId());
            updateWrapper.set(SystemFieldConstants.DEL_FLAG, EDelFlag.UN_DELETE.getValue());
            // 更新提货日志状态
            iAcPickMemberLogService.update(updateWrapper);

            return true;
        }
        return false;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean cancelPickOrder(String orderCode, Long userId) {
        LambdaQueryWrapper<AcPickMemberLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AcPickMemberLog::getPickOrder, orderCode);
        AcPickMemberLog acPickMemberLog = iAcPickMemberLogService.getOne(queryWrapper);
        if (null != acPickMemberLog) {
            // 更新提货数量（此方法为统一的扣减，传入负数则为添加）
            if (baseMapper.updatePickUseById(acPickMemberLog.getPkPick(), acPickMemberLog.getPickQuantity() * -1, userId) > 0) {
                // 删除提货日志
                UpdateWrapper<AcPickMemberLog> logUpdateWrapper = new UpdateWrapper<>();
                logUpdateWrapper.eq(SystemFieldConstants.PK_ID, acPickMemberLog.getPkId());
                logUpdateWrapper.set(SystemFieldConstants.DEL_FLAG, EDelFlag.DELETE.getValue());
                iAcPickMemberLogService.update(logUpdateWrapper);
            }
            return true;
        }
        return false;
    }

    @Override
    public BigDecimal postageHandle(AcPick acPick, Integer quantity, Integer recProvince, Integer recCity, Integer pkCountry) {
        // 是否包邮校验
        if (EYesNo.YES.getIntValue() == acPick.getIsFreeMail()) {
            // 包邮
            return BigDecimal.ZERO;
        }

        if (0 != acPick.getPkBaseConfig()) {
            // 新版本活动来源数据，需要查询提货配置，校验包邮数量
            LambdaQueryWrapper<AcPickUpConfig> pickUpConfigQueryWrapper = new LambdaQueryWrapper<>();
            pickUpConfigQueryWrapper.eq(AcPickUpConfig::getPkBaseId, acPick.getPkBaseConfig());
            AcPickUpConfig acPickUpConfig = iAcPickUpConfigService.getOne(pickUpConfigQueryWrapper);
            if (null != acPickUpConfig && quantity > acPickUpConfig.getFreePostageQuantity()) {
                // 包邮
                return BigDecimal.ZERO;
            }
        }

        // 邮费计算产品列表
        List<PostageProductDTO> productList = new ArrayList<>();

        // 根据各种提货不同进行处理
        switch (EPickType.getEnumByValue(acPick.getPickType())) {
            case PICK_PRODUCT:
            case PRIZE:
                // 提货产品处理、迁移抽奖处理
                // 封装邮费查询产品数据列表
                productList.add(PostageProductDTO.builder()
                        .productId(acPick.getPkDataId().intValue())
                        .quantity(quantity)
                        .build());
                break;
            case LOTTERY_DRAW:
            case CONSUMPTION_GIFT:
            case DIRECT_PUSH_GIFT:
                // 抽奖活动、商品赠品活动、消费赠送活动、直推赠送活动
                // 封装邮费查询产品数据列表
                List<AcGiftConfigExt> giftConfigList = iAcGiftConfigService.queryListByRuleIdList(acPick.getPkDataId(), pkCountry);
                for (AcGiftConfigExt acGiftConfigExt : giftConfigList) {
                    productList.add(PostageProductDTO.builder()
                            .productId(acGiftConfigExt.getPkProduct())
                            .quantity(quantity * acGiftConfigExt.getQuantity())
                            .build());
                }
                break;
            default:
        }

        R<BigDecimal> postageR = iPostageServiceApi.queryPostage(acPick.getPkPostage(), productList, recProvince, recCity);
        if (postageR.isSuccess()) {
            return postageR.getData();
        }
        throw new ServiceException(postageR.getMsg());
    }

    @Override
    public int deductionsCouponByOrder(Long pkMember, Long pkOrder) {
        return baseMapper.deductionsCouponByOrder(pkMember, pkOrder);
    }

}
