package com.hzs.activity.wares.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.param.GiftConfigParam;
import com.hzs.activity.base.service.IAcApprovalLogService;
import com.hzs.activity.base.service.IActivityService;
import com.hzs.activity.base.service.IAcBaseConfigService;
import com.hzs.activity.base.service.IAcGoalMemberConfigService;
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.wares.AcWaresRuleConfig;
import com.hzs.activity.wares.mapper.AcWaresRuleConfigMapper;
import com.hzs.activity.wares.service.IAcWaresRuleConfigService;
import com.hzs.common.domain.activity.wares.ext.AcWaresRuleConfigExt;
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 java.util.List;

/**
 * 商品买赠规则配置表 服务实现类
 *
 * @author hzs
 * @since 2023-04-20
 */
@Service
public class AcWaresRuleConfigServiceImpl extends ServiceImpl<AcWaresRuleConfigMapper, AcWaresRuleConfig> implements IAcWaresRuleConfigService {

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

    @DubboReference
    IApprovalServiceApi approvalServiceApi;

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

    /**
     * 删除
     *
     * @param pkId
     * @return
     */
    @Override
    public void removeWaresRuleConfig(Long pkId) {
        baseConfigService.removeById(pkId);
        // 删除商品买赠规格
        removeWaresGiftConfig(pkId);
        LambdaQueryWrapper<AcWaresRuleConfig> qr = new LambdaQueryWrapper<>();
        qr.eq(AcWaresRuleConfig::getPkBaseId, pkId);
        waresRuleConfigService.remove(qr);
        LambdaQueryWrapper<AcGoalMemberConfig> qt = new LambdaQueryWrapper<>();
        qt.eq(AcGoalMemberConfig::getPkBaseId, pkId);
        goalMemberConfigService.remove(qt);
    }

    /**
     * 商品买赠规则配置表
     *
     * @param baseConfigId
     */
    @Override
    public void removeWaresGiftConfig(Long baseConfigId) {
        LambdaQueryWrapper<AcWaresRuleConfig> qe = new LambdaQueryWrapper<>();
        qe.eq(AcWaresRuleConfig::getPkBaseId, baseConfigId);
        List<AcWaresRuleConfig> waresRuleConfigList = waresRuleConfigService.list(qe);
        for (AcWaresRuleConfig acWaresRuleConfig : waresRuleConfigList) {
            LambdaQueryWrapper<AcGiftConfig> qw = new LambdaQueryWrapper<>();
            qw.eq(AcGiftConfig::getPkRuleId, acWaresRuleConfig.getPkId());
            waresGiftConfigService.remove(qw);
        }
    }

    /**
     * 商品赠送审批
     *
     * @param recommendParam
     */
    @Override
    public Boolean onLinePetition(AcRecommendParam recommendParam) {
        EApprovalBusiness approvalBusiness = null;
        if (recommendParam.getControlType() == EControlType.SAVE.getValue()) {
            approvalBusiness = EApprovalBusiness.PRODUCT_GIFT_ADD;
        } else if (recommendParam.getControlType() == EControlType.MODIFY.getValue()) {
            approvalBusiness = EApprovalBusiness.PRODUCT_GIFT_UPDATE;
        } else if (recommendParam.getControlType() == EControlType.DELETE.getValue()) {
            approvalBusiness = EApprovalBusiness.PRODUCT_GIFT_REMOVE;
        }
        Boolean b = submitApproval(recommendParam, approvalBusiness);
        //日志
        ActivityParam activityParam = recommendParam.getActivityParam();
        activityParam.setPkCountry(SecurityUtils.getPkCountry());
        activityParam.setPkCreator(SecurityUtils.getUserId());
        activityParam.setActType(EActType.PRODUCT_GIFT.getValue());
        activityParam.setBusinessCode(recommendParam.getActivityParam().getBusinessCode());
        iActivityService.createBaseConfigLog(activityParam, new StringBuffer(), null, approvalBusiness.getValue(), false);
        return b;
    }

    /**
     * 商品赠送审核规则
     *
     * @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(loginUser.getDataCountry());
                activityParam.setPkCreator(loginUser.getUserId());
                activityParam.setActType(EActType.PRODUCT_GIFT.getValue());
                iActivityService.saveActivity(activityParam);
                return null;
            } else if (controlType.equals(EControlType.MODIFY.getValue())) {
                ActivityParam activityParam = recommendParam.getActivityParam();
                activityParam.setPkCountry(loginUser.getDataCountry());
                activityParam.setPkCreator(loginUser.getUserId());
                activityParam.setActType(EActType.PRODUCT_GIFT.getValue());
                waresRuleConfigService.updateWaresRuleConfig(activityParam);
                return null;
            } else if (controlType.equals(EControlType.DELETE.getValue())) {
                ActivityParam activityParam = recommendParam.getActivityParam();
                Long pkBaseId = activityParam.getPkBaseId();
                waresRuleConfigService.removeWaresRuleConfig(pkBaseId);
            }
        }
        return null;
    }

    /**
     * 商品赠送审核规则
     *
     * @param businessResult
     * @return
     */
    @Override
    public String approvalReject(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 "审批数据不存在！";
        }
        //更新审批状态
        acApprovalLogService.updateApprovalLog(eApprovalBusiness, businessCode, loginUser.getDataCountry(),
                loginUser.getUserId(), EApproveRechargeStatus.REJECT, businessResult.getApproveRemark());
        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 = 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;
    }

    /**
     * 修改信息
     *
     * @param activityParam
     */
    @Override
    public void updateWaresRuleConfig(ActivityParam activityParam) {
        Long pkId = activityParam.getPkId();
        // 查询基础信息
        AcBaseConfig baseConfig = BeanUtil.copyProperties(activityParam, AcBaseConfig.class);
        baseConfig.setPkId(activityParam.getPkId());
        baseConfigService.updateById(baseConfig);

        removeWaresGiftConfig(activityParam.getPkId());
        LambdaQueryWrapper<AcWaresRuleConfig> qr = new LambdaQueryWrapper<>();
        qr.eq(AcWaresRuleConfig::getPkBaseId, pkId);
        waresRuleConfigService.remove(qr);
        LambdaQueryWrapper<AcGoalMemberConfig> qt = new LambdaQueryWrapper<>();
        qt.eq(AcGoalMemberConfig::getPkBaseId, pkId);
        goalMemberConfigService.remove(qt);
        // 商品买赠配置
        iActivityService.saveWaresRuleConfig(activityParam, baseConfig);
        //目标用户配置
        iActivityService.saveGoalMemberConfig(activityParam, baseConfig);
    }
}
