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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.activity.base.param.ActivityParam;
import com.hzs.activity.base.param.ConsumeRuleConfigParam;
import com.hzs.activity.base.service.IAcApprovalLogService;
import com.hzs.activity.base.service.IAcBaseConfigService;
import com.hzs.activity.base.service.IAcGoalMemberConfigService;
import com.hzs.activity.base.service.IActivityService;
import com.hzs.activity.base.vo.AcMemberConsumeRuleVo;
import com.hzs.activity.base.vo.ConsumeRuleConfigVo;
import com.hzs.activity.consume.mapper.AcMemberConsumeRuleMapper;
import com.hzs.activity.consume.service.IAcMemberConsumeRuleService;
import com.hzs.activity.recommend.param.AcRecommendParam;
import com.hzs.activity.wares.service.IAcGiftConfigService;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.utils.CommonUtil;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.domain.activity.base.AcApprovalLog;
import com.hzs.common.domain.activity.base.AcBaseConfig;
import com.hzs.common.domain.activity.base.AcGiftConfig;
import com.hzs.common.domain.activity.base.AcGoalMemberConfig;
import com.hzs.common.domain.activity.base.ext.AcGiftConfigExt;
import com.hzs.common.domain.activity.consume.AcConsumeRuleConfig;
import com.hzs.common.domain.activity.consume.AcConsumeShieldConfig;
import com.hzs.common.domain.activity.consume.AcMemberConsumeRule;
import com.hzs.common.domain.activity.consume.ext.AcMemberConsumeRuleExt;
import com.hzs.common.domain.activity.wares.AcWaresRuleConfig;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.system.sys.IApprovalServiceApi;
import com.hzs.system.sys.dto.ApprovalBusinessResultDTO;
import com.hzs.system.sys.dto.ApprovalSubmitDTO;
import com.hzs.system.sys.dto.LoginUser;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

import java.util.Date;
import java.util.List;

/**
 * @description: 会员消费赠送活动规则配置
 * @author: zhang jing
 * @date: 2024/11/28 11:30
 * @param:
 * @return:
 **/
@Service
public class AcMemberConsumeRuleServiceImpl extends ServiceImpl<AcMemberConsumeRuleMapper, AcMemberConsumeRule> implements IAcMemberConsumeRuleService {

    @Autowired
    private IAcApprovalLogService acApprovalLogService;
    @Autowired
    private IActivityService iActivityService;
    @DubboReference
    IApprovalServiceApi approvalServiceApi;
    @Autowired
    private IAcBaseConfigService baseConfigService;
    @Autowired
    private IAcGiftConfigService waresGiftConfigService;
    @Autowired
    private IAcGoalMemberConfigService iAcGoalMemberConfigService;


    /**
     * @description: 会员消费赠送发起签呈
     * @author: zhang jing
     * @date: 2024/11/29 9:42
     * @param: [memberConsumeRuleVo]
     * @return: java.lang.Boolean
     **/
    @Override
    public Boolean onLinePetition(AcMemberConsumeRuleVo memberConsumeRuleVo) {
        EApprovalBusiness approvalBusiness = null;
        if (memberConsumeRuleVo.getControlType() == EControlType.SAVE.getValue()) {
            approvalBusiness = EApprovalBusiness.MEMBER_CONSUME_GIFT_ADD;
        } else if (memberConsumeRuleVo.getControlType() == EControlType.MODIFY.getValue()) {
            approvalBusiness = EApprovalBusiness.MEMBER_CONSUME_GIFT_UPDATE;
        } else if (memberConsumeRuleVo.getControlType() == EControlType.DELETE.getValue()) {
            approvalBusiness = EApprovalBusiness.MEMBER_CONSUME_GIFT_REMOVE;
        }
        Boolean b = submitApproval(memberConsumeRuleVo, approvalBusiness);
        ActivityParam activityParam = memberConsumeRuleVo.getActivityParam();
        activityParam.setPkCountry(SecurityUtils.getPkCountry());
        activityParam.setPkCreator(SecurityUtils.getUserId());
        activityParam.setActType(EActType.MEMBER_CONSUMPTION.getValue());
        //日志
        iActivityService.createBaseConfigLog(activityParam, new StringBuffer(), null, approvalBusiness.getValue(), false);
        return b;
    }

    /**
     * @description: 发起签呈
     * @author: zhang jing
     * @date: 2024/11/29 9:44
     * @param: [memberConsumeRuleVo, approvalBusiness]
     * @return: java.lang.Boolean
     **/
    public Boolean submitApproval(AcMemberConsumeRuleVo memberConsumeRuleVo, EApprovalBusiness approvalBusiness) {
        //保存审批日志
        AcApprovalLog approvalLog = saveApprovalLog(memberConsumeRuleVo, approvalBusiness);
        ApprovalSubmitDTO approvalSubmitDTO = ApprovalSubmitDTO.builder().eApprovalBusiness(approvalBusiness)
                .businessCode(approvalLog.getBusinessCode())
                .businessData(JSONObject.toJSONString(memberConsumeRuleVo.getActivityParam()))
                .signType(ESignType.getEnumByValue(memberConsumeRuleVo.getSignType())).userIdList(memberConsumeRuleVo.getUserIdList())
                .sendIdList(memberConsumeRuleVo.getSendIdList()).remark(memberConsumeRuleVo.getRemark()).fileList(memberConsumeRuleVo.getFileList())
                .build();
        R<String> submit = approvalServiceApi.submit(approvalSubmitDTO, memberConsumeRuleVo.getLoginUser());
        if (!submit.isSuccess()) {
            throw new RuntimeException("旅游活动参数提交审批失败！");
        }
        return submit.isSuccess();
    }

    /**
     * @description: 保存审批日志
     * @author: zhang jing
     * @date: 2024/11/29 9:44
     * @param: [memberConsumeRuleVo, approvalBusiness]
     * @return: com.hzs.common.domain.activity.base.AcApprovalLog
     **/
    public AcApprovalLog saveApprovalLog(AcMemberConsumeRuleVo memberConsumeRuleVo, EApprovalBusiness approvalBusiness) {
        Integer controlType = memberConsumeRuleVo.getControlType();
        String afterData = JSONUtil.toJsonStr(memberConsumeRuleVo);
        String beforeData = controlType.equals(EControlType.SAVE.getValue()) ? JSONUtil.toJsonStr(memberConsumeRuleVo) : null;
        //业务单号
        String businessCode = CommonUtil.createSerialNumber(EOrderPrefix.ACTIVITY_CODE.getValue());
        memberConsumeRuleVo.getActivityParam().setBusinessCode(businessCode);
        AcApprovalLog approvalLog = AcApprovalLog.builder().approvalType(approvalBusiness.getValue())
                .beforeData(beforeData).businessCode(businessCode).controlType(controlType)
                .approvalStatus(EApproveRechargeStatus.WAIT.getValue()).afterData(afterData)
                .build();
        approvalLog.setPkCreator(memberConsumeRuleVo.getLoginUser().getUserId());
        approvalLog.setPkCountry(memberConsumeRuleVo.getLoginUser().getDataCountry());

        acApprovalLogService.save(approvalLog);
        return approvalLog;
    }



    /**
     * @description: 会员消费赠送审批
     * @author: zhang jing
     * @date: 2024/11/29 16:33
     * @param: [businessResult]
     * @return: java.lang.String
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String approvalAgree(ApprovalBusinessResultDTO businessResult) {
        EApprovalBusiness eApprovalBusiness = businessResult.getEApprovalBusiness();
        String businessCode = businessResult.getBusinessCode();
        LoginUser loginUser = businessResult.getLoginUser();
        AcApprovalLog approvalLog = acApprovalLogService.queryApprovalLog(eApprovalBusiness, businessCode, loginUser.getDataCountry());
        if (null == approvalLog) {
            return "审批数据不存在！";
        }
        Integer controlType = approvalLog.getControlType();
        String data = approvalLog.getAfterData();
        if (StringUtils.isNotEmpty(data)) {
            AcMemberConsumeRuleVo memberConsumeRuleVo = JSONUtil.toBean(data, AcMemberConsumeRuleVo.class);
            if (controlType.equals(EControlType.SAVE.getValue())) {
                ActivityParam activityParam = memberConsumeRuleVo.getActivityParam();
                activityParam.setPkCountry(loginUser.getDataCountry());
                activityParam.setPkCreator(loginUser.getUserId());
                activityParam.setActType(EActType.MEMBER_CONSUMPTION.getValue());
                memberConsumeRuleVo.setActivityParam(activityParam);
                saveMemberConsumeRule(memberConsumeRuleVo);
                //日志
                //   IActivityService.createBaseConfigLog(activityParam, new StringBuffer(), pkBaseId, EApprovalBusiness.CONSUME_GIFT_ADD.getValue(), true);
                return null;
            } else if (controlType.equals(EControlType.MODIFY.getValue())) {
                ActivityParam activityParam = memberConsumeRuleVo.getActivityParam();
                activityParam.setPkCountry(loginUser.getDataCountry());
                activityParam.setPkCreator(loginUser.getUserId());
                activityParam.setActType(EActType.MEMBER_CONSUMPTION.getValue());
                memberConsumeRuleVo.setActivityParam(activityParam);
                updateConsumptionGift(memberConsumeRuleVo);
                //     IActivityService.createBaseConfigLog(activityParam, new StringBuffer(), activityParam.getPkBaseId(), EApprovalBusiness.CONSUME_GIFT_UPDATE.getValue(), true);
                return null;
            }else if (controlType.equals(EControlType.DELETE.getValue())) {
                ActivityParam activityParam = memberConsumeRuleVo.getActivityParam();
                Long pkBaseId = activityParam.getPkBaseId();
                AcBaseConfig baseConfig = baseConfigService.getById(pkBaseId);
                removeActivity(pkBaseId.intValue());
//                //   IActivityService.removeBaseConfigLog(baseConfig, new StringBuffer(), activityParam.getPkBaseId(), EApprovalBusiness.CONSUME_GIFT_REMOVE.getValue(), true);
            }
        }
        return null;
    }



    /**
     * 新增消费赠送规格
     *
     * @param mcrVo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long saveMemberConsumeRule(AcMemberConsumeRuleVo mcrVo) {
        // 增加基础配置
        AcBaseConfig baseConfig = iActivityService.saveBaseConfig(mcrVo.getActivityParam());
        // 目标群体配置
        iActivityService.saveGoalMemberConfig(mcrVo.getActivityParam(), baseConfig);
        // 消费赠送规格配置
        saveConsumeRuleConfigService(mcrVo, baseConfig);
        return baseConfig.getPkId();
    }

    /**
     * @description:修改会员消费赠送规则
     * @author: zhang jing
     * @date: 2024/12/2 16:17
     * @param: [mcrVo]
     * @return: void
     **/
    @Override
    public void updateConsumptionGift(AcMemberConsumeRuleVo mcrVo) {
        Long pkId = mcrVo.getActivityParam().getPkId();
        // 查询基础信息，修改活动主表
        AcBaseConfig baseConfig = BeanUtil.copyProperties(mcrVo.getActivityParam(), AcBaseConfig.class);
        baseConfigService.updateById(baseConfig);
        //删除会员消费活动赠品配置表
        if(CollectionUtil.isNotEmpty(mcrVo.getMcrList())){
            for(AcMemberConsumeRuleExt mcrex:mcrVo.getMcrList()){
                // 消费赠送规格配置
                LambdaQueryWrapper<AcGiftConfig> delGif = new LambdaQueryWrapper<>();
                delGif.eq(AcGiftConfig::getPkRuleId, mcrex.getPkId());
                waresGiftConfigService.remove(delGif);
            }
        }
        //删除会员消费活动规则表
        LambdaQueryWrapper<AcMemberConsumeRule> delmcr = new LambdaQueryWrapper<>();
        delmcr.eq(AcMemberConsumeRule::getPkBaseId, pkId);
        baseMapper.delete(delmcr);
        //删除目标群体
        LambdaQueryWrapper<AcGoalMemberConfig> delgmc = new LambdaQueryWrapper<>();
        delgmc.eq(AcGoalMemberConfig::getPkBaseId, pkId);
        iAcGoalMemberConfigService.remove(delgmc);
        // 新增目标群体配置
        iActivityService.saveGoalMemberConfig(mcrVo.getActivityParam(), baseConfig);
        //新增会员消费规则
        saveConsumeRuleConfigService(mcrVo, baseConfig);
    }

    /**
     * @description: 新增会员消费活动规则和活动赠品
     * @author: zhang jing
     * @date: 2024/12/2 16:43
     * @param: [mcrVo, baseConfig]
     * @return: void
     **/
    public void saveConsumeRuleConfigService(AcMemberConsumeRuleVo mcrVo, AcBaseConfig baseConfig) {
        List<AcMemberConsumeRuleExt> mcrList = mcrVo.getMcrList();
        for (AcMemberConsumeRuleExt mcr : mcrList) {
            /**
             * 新增会员消费规则配置
             */
            Date date=new Date();
            mcr.setPkBaseId(baseConfig.getPkId());
            mcr.setCreationTime(date);
            mcr.setPkCreator(mcrVo.getLoginUser().getUserId());
            mcr.setPkCountry(mcrVo.getLoginUser().getDataCountry());
            baseMapper.insert(mcr);
                /**
                 * 活动赠品配置
                 */
                List<AcGiftConfigExt> giftConfigExList = mcr.getWgcList();
                List<AcGiftConfig> giftConfigList = new ArrayList<>();
                for (AcGiftConfigExt giftConfigExt : giftConfigExList) {
                    giftConfigExt.setPkRuleId(mcr.getPkId());
                    giftConfigExt.setActType(baseConfig.getActType());
                    giftConfigExt.setPkCreator(baseConfig.getPkCreator());
                    giftConfigExt.setPkCountry(baseConfig.getPkCountry());
                    AcGiftConfig acGiftConfig = BeanUtil.copyProperties(giftConfigExt, AcGiftConfig.class);
                    giftConfigList.add(acGiftConfig);
                }
                waresGiftConfigService.saveBatch(giftConfigList);

        }
    }

    /**
     * @description: 删除会员消费活动
     * @author: zhang jing
     * @date: 2024/12/2 17:08
     * @param: [pkId]
     * @return: void
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeActivity(Integer pkId) {
        baseConfigService.removeById(pkId);
        LambdaQueryWrapper<AcMemberConsumeRule> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AcMemberConsumeRule::getPkBaseId, pkId);
        baseMapper.delete(queryWrapper);
        //删除会员活动规则-赠送商品表
        LambdaQueryWrapper<AcGiftConfig> qw = new LambdaQueryWrapper<>();
        qw.eq(AcGiftConfig::getPkRuleId, pkId);
        List<AcGiftConfig> list = waresGiftConfigService.list(qw);
        for (AcGiftConfig acgc : list) {
            LambdaQueryWrapper<AcGiftConfig> qe = new LambdaQueryWrapper<>();
            qe.eq(AcGiftConfig::getPkRuleId, acgc.getPkId());
            waresGiftConfigService.remove(qe);
        }
        //删除会员消费活动规则表
        LambdaQueryWrapper<AcMemberConsumeRule> delmcr = new LambdaQueryWrapper<>();
        delmcr.eq(AcMemberConsumeRule::getPkBaseId, pkId);
        baseMapper.delete(delmcr);
        //删除目标群体
        LambdaQueryWrapper<AcGoalMemberConfig> delgmc = new LambdaQueryWrapper<>();
        delgmc.eq(AcGoalMemberConfig::getPkBaseId, pkId);
        iAcGoalMemberConfigService.remove(delgmc);
    }

    @Override
    public List<AcMemberConsumeRuleExt> listRuleAndProduct(Date startDate, Date endDate, Integer pkGrade, Integer memberPoint, Integer pkCountry) {
        return baseMapper.listRuleAndProduct(startDate, endDate, pkGrade, memberPoint, pkCountry);
    }

}
