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

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.GiftConfigParam;
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.consume.mapper.AcConsumeRuleConfigMapper;
import com.hzs.activity.consume.service.IAcConsumeRuleConfigService;
import com.hzs.activity.consume.service.IAcConsumeShieldConfigService;
import com.hzs.activity.recommend.param.AcRecommendParam;
import com.hzs.activity.wares.service.IAcGiftConfigService;
import com.hzs.activity.wares.service.IAcWaresRuleConfigService;
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.consume.AcConsumeRuleConfig;
import com.hzs.common.domain.activity.consume.AcConsumeShieldConfig;
import com.hzs.common.domain.activity.consume.ext.AcConsumeRuleConfigExt;
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.List;

/**
 * 消费买赠规则配置表 服务实现类
 *
 * @author hzs
 * @since 2023-04-20
 */
@Service
public class AcConsumeRuleConfigServiceImpl extends ServiceImpl<AcConsumeRuleConfigMapper, AcConsumeRuleConfig> implements IAcConsumeRuleConfigService {

    @Autowired
    private IActivityService iActivityService;
    @Autowired
    private IAcApprovalLogService acApprovalLogService;
    @Autowired
    private IAcWaresRuleConfigService waresRuleConfigService;
    @Autowired
    private IAcConsumeShieldConfigService consumeShieldConfigService;
    @Autowired
    private IAcGiftConfigService waresGiftConfigService;
    @Autowired
    private IAcBaseConfigService baseConfigService;
    @Autowired
    private IAcGoalMemberConfigService goalMemberConfigService;

    @DubboReference
    IApprovalServiceApi approvalServiceApi;

    @Override
    public List<AcConsumeRuleConfigExt> queryConsumeGiftConfigByCondition(GiftConfigParam giftConfigParam) {
        return baseMapper.queryConsumeGiftConfigByCondition(giftConfigParam);
    }

    /**
     * 删除
     *
     * @param pkId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeActivity(Integer pkId) {
        baseConfigService.removeById(pkId);
        LambdaQueryWrapper<AcGoalMemberConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AcGoalMemberConfig::getPkBaseId, pkId);
        goalMemberConfigService.remove(queryWrapper);
        LambdaQueryWrapper<AcWaresRuleConfig> qw = new LambdaQueryWrapper<>();
        qw.eq(AcWaresRuleConfig::getPkBaseId, pkId);
        List<AcWaresRuleConfig> list = waresRuleConfigService.list(qw);
        for (AcWaresRuleConfig acWaresRuleConfig : list) {
            LambdaQueryWrapper<AcGiftConfig> qe = new LambdaQueryWrapper<>();
            qe.eq(AcGiftConfig::getPkRuleId, acWaresRuleConfig.getPkId());
            waresGiftConfigService.remove(qe);
        }
        LambdaQueryWrapper<AcWaresRuleConfig> qf = new LambdaQueryWrapper<>();
        qf.eq(AcWaresRuleConfig::getPkBaseId, pkId);
        waresRuleConfigService.remove(qf);
        LambdaQueryWrapper<AcConsumeShieldConfig> qr = new LambdaQueryWrapper<>();
        qr.eq(AcConsumeShieldConfig::getPkBaseId, pkId);
        consumeShieldConfigService.remove(qr);
    }

    /**
     * 消费赠送审批
     *
     * @param recommendParam
     */
    @Override
    public Boolean onLinePetition(AcRecommendParam recommendParam) {
        EApprovalBusiness approvalBusiness = null;
        if (recommendParam.getControlType() == EControlType.SAVE.getValue()) {
            approvalBusiness = EApprovalBusiness.CONSUME_GIFT_ADD;
        } else if (recommendParam.getControlType() == EControlType.MODIFY.getValue()) {
            approvalBusiness = EApprovalBusiness.CONSUME_GIFT_UPDATE;
        } else if (recommendParam.getControlType() == EControlType.DELETE.getValue()) {
            approvalBusiness = EApprovalBusiness.CONSUME_GIFT_REMOVE;
        }
        Boolean b = submitApproval(recommendParam, approvalBusiness);
        ActivityParam activityParam = recommendParam.getActivityParam();
        activityParam.setPkCountry(SecurityUtils.getPkCountry());
        activityParam.setPkCreator(SecurityUtils.getUserId());
        activityParam.setActType(EActType.CONSUMPTION_GIFT.getValue());

        //日志
        iActivityService.createBaseConfigLog(activityParam, new StringBuffer(), null, approvalBusiness.getValue(), false);
        return b;
    }

    /**
     * 消费赠送审批/修改/删除
     *
     * @param businessResult
     */
    @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(loginUser.getDataCountry());
                activityParam.setPkCreator(loginUser.getUserId());
                activityParam.setActType(EActType.CONSUMPTION_GIFT.getValue());
                iActivityService.saveConsumptionGift(activityParam);
                //日志
                //   IActivityService.createBaseConfigLog(activityParam, new StringBuffer(), pkBaseId, EApprovalBusiness.CONSUME_GIFT_ADD.getValue(), true);
                return null;
            } else if (controlType.equals(EControlType.MODIFY.getValue())) {
                ActivityParam activityParam = recommendParam.getActivityParam();
                activityParam.setPkCountry(loginUser.getDataCountry());
                activityParam.setPkCreator(loginUser.getUserId());
                activityParam.setActType(EActType.CONSUMPTION_GIFT.getValue());
                iActivityService.updateConsumptionGift(activityParam);
                //     IActivityService.createBaseConfigLog(activityParam, new StringBuffer(), activityParam.getPkBaseId(), EApprovalBusiness.CONSUME_GIFT_UPDATE.getValue(), true);
                return null;
            } else if (controlType.equals(EControlType.DELETE.getValue())) {
                ActivityParam activityParam = recommendParam.getActivityParam();
                Long pkBaseId = activityParam.getPkBaseId();
                AcBaseConfig baseConfig = baseConfigService.getById(pkBaseId);
                this.removeActivity(pkBaseId.intValue());
                //   IActivityService.removeBaseConfigLog(baseConfig, new StringBuffer(), activityParam.getPkBaseId(), EApprovalBusiness.CONSUME_GIFT_REMOVE.getValue(), true);
            }
        }
        return null;
    }

    /**
     * 提交审批
     *
     * @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.getActivityParam()))
                .signType(ESignType.getEnumByValue(recommendParam.getSignType())).userIdList(recommendParam.getUserIdList())
                .sendIdList(recommendParam.getSendIdList()).remark(recommendParam.getRemark()).fileList(recommendParam.getFileList())
                .build();
        R<String> submit = approvalServiceApi.submit(approvalSubmitDTO, recommendParam.getLoginUser());
        if (!submit.isSuccess()) {
            throw new RuntimeException("旅游活动参数提交审批失败！");
        }
        return submit.isSuccess();
    }

    /**
     * 保存活动审批日志信息
     *
     * @param recommendParam   直推赠送参数
     * @param approvalBusiness 审批业务
     * @return boolean
     */
    public AcApprovalLog saveApprovalLog(AcRecommendParam recommendParam, EApprovalBusiness approvalBusiness) {
        Integer controlType = recommendParam.getControlType();
        //查询变更前的数据
/*        String afterData = !controlType.equals(EControlType.SAVE.getValue()) ?
                JSONUtil.toJsonStr(showDetailInfo(recommendParam.getPkBaseId(), recommendParam.getPkCountry())) :
                JSONUtil.toJsonStr(recommendParam);*/
        String afterData = JSONUtil.toJsonStr(recommendParam);
        String beforeData = controlType.equals(EControlType.SAVE.getValue()) ? JSONUtil.toJsonStr(recommendParam) : null;
        //业务单号
        String businessCode = CommonUtil.createSerialNumber(EOrderPrefix.ACTIVITY_CODE.getValue());
        recommendParam.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(recommendParam.getPkMember());
        approvalLog.setPkCountry(recommendParam.getPkCountry());

        acApprovalLogService.save(approvalLog);
        return approvalLog;
    }


}
