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

import cn.hutool.core.bean.BeanUtil;
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.service.IActivityService;
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.draw.mapper.AcDrawGiftRuleConfigMapper;
import com.hzs.activity.draw.param.DrawGiftConfigParam;
import com.hzs.activity.draw.service.IAcDrawGiftRuleConfigService;
import com.hzs.activity.draw.service.IAcDrawRuleConfigService;
import com.hzs.activity.pick.service.IAcPickUpConfigService;
import com.hzs.activity.recommend.param.AcRecommendParam;
import com.hzs.common.core.constant.CacheConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.service.RedisService;
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.AcGoalMemberConfig;
import com.hzs.common.domain.activity.base.AcPickUpConfig;
import com.hzs.common.domain.activity.draw.AcDrawGiftRuleConfig;
import com.hzs.common.domain.activity.draw.AcDrawRuleConfig;
import com.hzs.common.domain.activity.draw.ext.AcDrawGiftRuleConfigExt;
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.List;

/**
 * 活动赠品配置 服务实现类
 *
 * @author hzs
 * @since 2023-04-21
 */
@Service
public class AcDrawGiftRuleConfigServiceImpl extends ServiceImpl<AcDrawGiftRuleConfigMapper, AcDrawGiftRuleConfig> implements IAcDrawGiftRuleConfigService {

    @Autowired
    private IAcPickUpConfigService pickUpConfigService;
    @Autowired
    private IActivityService iActivityService;
    @Autowired
    private IAcDrawGiftRuleConfigService drawGiftConfigService;
    @Autowired
    private IAcDrawRuleConfigService drawRuleConfigService;
    @Autowired
    private IAcBaseConfigService baseConfigService;
    @Autowired
    IAcApprovalLogService acApprovalLogService;
    @Autowired
    private IAcGoalMemberConfigService goalMemberConfigService;
    @Autowired
    private RedisService redisService;

    @DubboReference
    IApprovalServiceApi approvalServiceApi;

    @Override
    public List<AcDrawGiftRuleConfigExt> queryAcDrawGiftConfig(DrawGiftConfigParam drawGiftConfigParam) {
        return baseMapper.queryAcDrawGiftConfig(drawGiftConfigParam);
    }

    /**
     * 查询活动赠品配置列表
     *
     * @param drawGiftConfigParam
     * @return
     */
    @Override
    public List<AcDrawGiftRuleConfigExt> queryList(DrawGiftConfigParam drawGiftConfigParam) {
        return baseMapper.queryList(drawGiftConfigParam);
    }

    /**
     * 删除抽奖信息详情
     *
     * @param pkId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeDrawGiftConfig(Integer pkId) {
        baseConfigService.removeById(pkId);
        //目标用户群删除
        LambdaQueryWrapper<AcGoalMemberConfig> qe = new LambdaQueryWrapper<>();
        qe.eq(AcGoalMemberConfig::getPkBaseId, pkId);
        goalMemberConfigService.remove(qe);
        // 活动赠品配置
        LambdaQueryWrapper<AcDrawGiftRuleConfig> qw = new LambdaQueryWrapper<>();
        qw.eq(AcDrawGiftRuleConfig::getPkBaseId, pkId);
        drawGiftConfigService.remove(qw);
        // 抽奖赠送次数规则删除
        LambdaQueryWrapper<AcDrawRuleConfig> qr = new LambdaQueryWrapper<>();
        qr.eq(AcDrawRuleConfig::getPkBaseId, pkId);
        drawRuleConfigService.remove(qr);
        redisService.deleteObjectByKey(CacheConstants.DRAW_REWARD_GIFT + pkId);
    }

    /**
     * 修改抽奖信息详情
     *
     * @param activityParam
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDrawGiftConfig(ActivityParam activityParam) {
        //目标用户群删除
        LambdaQueryWrapper<AcGoalMemberConfig> qe = new LambdaQueryWrapper<>();
        qe.eq(AcGoalMemberConfig::getPkBaseId, activityParam.getPkId());
        goalMemberConfigService.remove(qe);
        // 活动赠品配置
        LambdaQueryWrapper<AcDrawGiftRuleConfig> qw = new LambdaQueryWrapper<>();
        qw.eq(AcDrawGiftRuleConfig::getPkBaseId, activityParam.getPkId());
        drawGiftConfigService.remove(qw);
        // 抽奖赠送次数规则删除
        LambdaQueryWrapper<AcDrawRuleConfig> qr = new LambdaQueryWrapper<>();
        qr.eq(AcDrawRuleConfig::getPkBaseId, activityParam.getPkId());
        drawRuleConfigService.remove(qr);
        LambdaQueryWrapper<AcPickUpConfig> qq = new LambdaQueryWrapper<>();
        qq.eq(AcPickUpConfig::getPkBaseId, activityParam.getPkId());
        pickUpConfigService.remove(qq);

        iActivityService.updateRaffleActivity(activityParam);
        redisService.deleteObjectByKey(CacheConstants.DRAW_REWARD_GIFT + activityParam.getPkId());
    }

    /**
     * 抽奖审核
     *
     * @param businessResult
     * @return
     */
    @Override
    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)) {
            AcRecommendParam recommendParam = JSONUtil.toBean(data, AcRecommendParam.class);
            if (controlType.equals(EControlType.SAVE.getValue())) {
                ActivityParam activityParam = recommendParam.getActivityParam();
                activityParam.setPkCountry(recommendParam.getPkCountry());
                activityParam.setPkCreator(recommendParam.getPkMember());
                activityParam.setActType(EActType.LOTTERY_DRAW.getValue());
                iActivityService.saveRaffleActivity(activityParam);
                return null;
            } else if (controlType.equals(EControlType.MODIFY.getValue())) {
                ActivityParam activityParam = recommendParam.getActivityParam();
                activityParam.setActType(EActType.LOTTERY_DRAW.getValue());
                activityParam.setPkCountry(recommendParam.getPkCountry());
                activityParam.setPkCreator(recommendParam.getPkMember());
                drawGiftConfigService.updateDrawGiftConfig(activityParam);
                return null;
            } else if (controlType.equals(EControlType.DELETE.getValue())) {
                drawGiftConfigService.removeDrawGiftConfig(recommendParam.getActivityParam().getPkBaseId().intValue());
            }
        }
        //更新审批状态
        acApprovalLogService.updateApprovalLog(eApprovalBusiness, businessCode, loginUser.getDataCountry(),
                loginUser.getUserId(), EApproveRechargeStatus.AGREE, businessResult.getApproveRemark());
        return null;
    }

    @Override
    public Boolean onLinePetition(AcRecommendParam recommendParam) {
        EApprovalBusiness approvalBusiness = null;
        if (recommendParam.getControlType().equals(EControlType.SAVE.getValue())) {
            approvalBusiness = EApprovalBusiness.LOTTERY_DRAW_ADD;
        } else if (recommendParam.getControlType().equals(EControlType.MODIFY.getValue())) {
            approvalBusiness = EApprovalBusiness.LOTTERY_DRAW_UPDATE;
        } else if (recommendParam.getControlType().equals(EControlType.DELETE.getValue())) {
            approvalBusiness = EApprovalBusiness.LOTTERY_DRAW_REMOVE;
        }

        return submitApproval(recommendParam, approvalBusiness);
    }

    /**
     * 提交审批
     *
     * @param recommendParam 抽奖参数
     */
    public Boolean submitApproval(AcRecommendParam recommendParam, EApprovalBusiness approvalBusiness) {
        //保存审批日志
        AcApprovalLog approvalLog = saveApprovalLog(recommendParam, approvalBusiness);
        ApprovalSubmitDTO approvalSubmitDTO = ApprovalSubmitDTO.builder().eApprovalBusiness(approvalBusiness)
                .businessCode(approvalLog.getBusinessCode())
                .businessData(JSONObject.toJSONString(recommendParam)).fileList(recommendParam.getFileList())
                .signType(ESignType.getEnumByValue(recommendParam.getSignType())).userIdList(recommendParam.getUserIdList())
                .sendIdList(recommendParam.getSendIdList()).remark(recommendParam.getRemark()).build();
        R<String> submit = approvalServiceApi.submit(approvalSubmitDTO, recommendParam.getLoginUser());
        if (!submit.isSuccess()) {
            throw new RuntimeException("抽奖参数提交审批失败！");
        }

        //添加操作日志
        StringBuffer str = new StringBuffer();
        Integer value = null;
        if (recommendParam.getControlType() == EControlType.SAVE.getValue()) {
            str.append(EControlType.SAVE.getLabel());
            value = EApprovalBusiness.LOTTERY_DRAW_ADD.getValue();
        }
        if (recommendParam.getControlType() == EControlType.MODIFY.getValue()) {
            str.append(EControlType.MODIFY.getLabel());
            value = EApprovalBusiness.LOTTERY_DRAW_UPDATE.getValue();
        }
        if (recommendParam.getControlType() == EControlType.DELETE.getValue()) {
            AcBaseConfig baseConfig = BeanUtil.copyProperties(recommendParam.getActivityParam(), AcBaseConfig.class);
            baseConfig.setPkCreator(approvalLog.getPkCreator());
            baseConfig.setPkCountry(recommendParam.getPkCountry());
            baseConfig.setBusinessCode(approvalLog.getBusinessCode());
            iActivityService.removeBaseConfigLog(baseConfig, str, null, EApprovalBusiness.LOTTERY_DRAW_REMOVE.getValue(), false);
        } else {
            ActivityParam activityParam = BeanUtil.copyProperties(recommendParam.getActivityParam(), ActivityParam.class);
            activityParam.setPkCreator(approvalLog.getPkCreator());
            activityParam.setPkCountry(recommendParam.getPkCountry());
            activityParam.setBusinessCode(approvalLog.getBusinessCode());
            iActivityService.createBaseConfigLog(activityParam, str, null, value, false);
        }
        return submit.isSuccess();
    }

    /**
     * 保存活动审批日志信息
     *
     * @param recommendParam   直推赠送参数
     * @param approvalBusiness 审批业务
     * @return boolean
     */
    public AcApprovalLog saveApprovalLog(AcRecommendParam recommendParam, EApprovalBusiness approvalBusiness) {
        Integer controlType = recommendParam.getControlType();
        //查询变更前的数据
        String afterData = JSONUtil.toJsonStr(recommendParam);
        String beforeData = controlType.equals(EControlType.SAVE.getValue()) ? JSONUtil.toJsonStr(recommendParam) : null;
        //业务单号
        String businessCode = CommonUtil.createSerialNumber(EOrderPrefix.ACTIVITY_CODE.getValue());
        AcApprovalLog approvalLog = AcApprovalLog.builder().approvalType(approvalBusiness.getValue())
                .beforeData(beforeData).businessCode(businessCode).controlType(controlType)
                .approvalStatus(EApproveRechargeStatus.WAIT.getValue()).afterData(afterData)
                .build();
        approvalLog.setPkCreator(recommendParam.getPkMember());
        approvalLog.setPkCountry(recommendParam.getPkCountry());

        acApprovalLogService.save(approvalLog);
        return approvalLog;
    }
}
