package com.hzs.activity.pick.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.hzs.activity.base.param.ActivityParam;
import com.hzs.activity.base.service.IAcApprovalLogService;
import com.hzs.activity.base.service.IAcBaseConfigService;
import com.hzs.activity.base.service.IActivityService;
import com.hzs.activity.pick.mapper.AcRetailPickProductConfigMapper;
import com.hzs.activity.pick.service.IAcRetailPickProductConfigService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.activity.pick.vo.AcRetailPickProductConfigVO;
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.pick.AcRetailPickProductConfig;
import com.hzs.common.domain.activity.pick.ext.AcRetailPickProductConfigExt;
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.Date;
import java.util.List;

/**
 * 提货赠送活动商品配置 服务实现类
 *
 * @author hzs
 * @since 2025-01-13
 */
@Service
public class AcRetailPickProductConfigServiceImpl extends ServiceImpl<AcRetailPickProductConfigMapper, AcRetailPickProductConfig> implements IAcRetailPickProductConfigService {

    @Autowired
    private IActivityService iActivityService;
    @DubboReference
    IApprovalServiceApi approvalServiceApi;
    @Autowired
    private IAcApprovalLogService acApprovalLogService;
    @Autowired
    private IAcBaseConfigService baseConfigService;

    /**
     * @description: 会员提货赠送活动发起签呈
     * @author: zhang jing
     * @date: 2024/11/29 9:42
     * @param: [rppcVo]
     * @return: java.lang.Boolean
     **/
    @Override
    public Boolean onLinePetition(AcRetailPickProductConfigVO rppcVo) {
        EApprovalBusiness approvalBusiness = null;
        if (rppcVo.getControlType() == EControlType.SAVE.getValue()) {
            approvalBusiness = EApprovalBusiness.RETAIL_PICK_PRODUCT_ADD;
        } else if (rppcVo.getControlType() == EControlType.MODIFY.getValue()) {
            approvalBusiness = EApprovalBusiness.RETAIL_PICK_PRODUCT_UPDATE;
        } else if (rppcVo.getControlType() == EControlType.DELETE.getValue()) {
            approvalBusiness = EApprovalBusiness.RETAIL_PICK_PRODUCT_REMOVE;
        }
        Boolean b = submitApproval(rppcVo, approvalBusiness);
        ActivityParam activityParam = rppcVo.getActivityParam();
        activityParam.setPkCountry(SecurityUtils.getPkCountry());
        activityParam.setPkCreator(SecurityUtils.getUserId());
        activityParam.setActType(EActType.PICK_GIFT.getValue());
        //日志
        iActivityService.createBaseConfigLog(activityParam, new StringBuffer(), null, approvalBusiness.getValue(), false);
        return b;
    }

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

    /**
     * @description: 保存审批日志
     * @author: zhang jing
     * @date: 2024/11/29 9:44
     * @param: [rppcVo, approvalBusiness]
     * @return: com.hzs.common.domain.activity.base.AcApprovalLog
     **/
    public AcApprovalLog saveApprovalLog(AcRetailPickProductConfigVO rppcVo, EApprovalBusiness approvalBusiness) {
        Integer controlType = rppcVo.getControlType();
        String afterData = JSONUtil.toJsonStr(rppcVo);
        String beforeData = controlType.equals(EControlType.SAVE.getValue()) ? JSONUtil.toJsonStr(rppcVo) : null;
        //业务单号
        String businessCode = CommonUtil.createSerialNumber(EOrderPrefix.ACTIVITY_CODE.getValue());
        rppcVo.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(rppcVo.getLoginUser().getUserId());
        approvalLog.setPkCountry(rppcVo.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)) {
            AcRetailPickProductConfigVO rppcVo = JSONUtil.toBean(data, AcRetailPickProductConfigVO.class);
            if (controlType.equals(EControlType.SAVE.getValue())) {
                ActivityParam activityParam = rppcVo.getActivityParam();
                activityParam.setPkCountry(loginUser.getDataCountry());
                activityParam.setPkCreator(loginUser.getUserId());
                activityParam.setActType(EActType.PICK_GIFT.getValue());
                activityParam.setSystemType(rppcVo.getSystemType());
                rppcVo.setActivityParam(activityParam);
                Long pkBaseId = saveGift(rppcVo);
                //日志
                iActivityService.createBaseConfigLog(activityParam, new StringBuffer(), pkBaseId, EApprovalBusiness.RETAIL_PICK_PRODUCT_ADD.getValue(), true);
                return null;
            } else if (controlType.equals(EControlType.MODIFY.getValue())) {
                ActivityParam activityParam = rppcVo.getActivityParam();
                activityParam.setPkCountry(loginUser.getDataCountry());
                activityParam.setPkCreator(loginUser.getUserId());
                activityParam.setActType(EActType.PICK_GIFT.getValue());
                activityParam.setSystemType(rppcVo.getSystemType());
                rppcVo.setActivityParam(activityParam);
                updateGift(rppcVo);
                iActivityService.createBaseConfigLog(activityParam, new StringBuffer(), activityParam.getPkBaseId(), EApprovalBusiness.RETAIL_PICK_PRODUCT_UPDATE.getValue(), true);
                return null;
            } else if (controlType.equals(EControlType.DELETE.getValue())) {
                ActivityParam activityParam = rppcVo.getActivityParam();
                Long pkBaseId = activityParam.getPkId();
                AcBaseConfig baseConfig = baseConfigService.getById(pkBaseId);
                removeActivity(pkBaseId.intValue());
                iActivityService.removeBaseConfigLog(baseConfig, new StringBuffer(), activityParam.getPkId(), EApprovalBusiness.RETAIL_PICK_PRODUCT_REMOVE.getValue(), true);
            }
        }
        return null;
    }

    /**
     * 新增提货赠送规格
     *
     * @param mcrVo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long saveGift(AcRetailPickProductConfigVO mcrVo) {
        // 增加基础配置
        AcBaseConfig baseConfig = iActivityService.saveBaseConfig(mcrVo.getActivityParam());
        // 提货赠送规格配置
        saveConsumeRuleConfigService(mcrVo, baseConfig);
        return baseConfig.getPkId();
    }

    /**
     * @description:修改会员提货赠送活动规则
     * @author: zhang jing
     * @date: 2024/12/2 16:17
     * @param: [mcrVo]
     * @return: void
     **/
    @Override
    public void updateGift(AcRetailPickProductConfigVO mcrVo) {
        Long pkId = mcrVo.getActivityParam().getPkId();
        // 查询基础信息，修改活动主表
        AcBaseConfig baseConfig = BeanUtil.copyProperties(mcrVo.getActivityParam(), AcBaseConfig.class);
        baseConfigService.updateById(baseConfig);
        //删除提货赠送活动规则表
        LambdaQueryWrapper<AcRetailPickProductConfig> delmcr = new LambdaQueryWrapper<>();
        delmcr.eq(AcRetailPickProductConfig::getPkBaseId, pkId);
        baseMapper.delete(delmcr);
        //新增提货赠送规则
        saveConsumeRuleConfigService(mcrVo, baseConfig);
    }

    /**
     * @description: 新增提货赠送活动规则和活动赠品
     * @author: zhang jing
     * @date: 2024/12/2 16:43
     * @param: [mcrVo, baseConfig]
     * @return: void
     **/
    public void saveConsumeRuleConfigService(AcRetailPickProductConfigVO mcrVo, AcBaseConfig baseConfig) {
        List<AcRetailPickProductConfigExt> mcrList = mcrVo.getRppcList();
        for (AcRetailPickProductConfigExt mcr : mcrList) {
            /**
             * 新增提货赠送规则配置
             */
            Date date = new Date();
            mcr.setWaresQuantity(mcrVo.getWaresQuantity());
            mcr.setGiftQuantity(mcrVo.getGiftQuantity());
            mcr.setPkBaseId(baseConfig.getPkId());
            mcr.setCreationTime(date);
            mcr.setPkCreator(mcrVo.getLoginUser().getUserId());
            mcr.setPkCountry(mcrVo.getLoginUser().getDataCountry());
            baseMapper.insert(mcr);
        }
    }

    /**
     * @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<AcRetailPickProductConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AcRetailPickProductConfig::getPkBaseId, pkId);
        baseMapper.delete(queryWrapper);
    }

}
