package com.hzs.member.base.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.common.core.constant.RabbitMqConstants;
import com.hzs.common.core.constant.msg.ConfigMsgConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.exception.ServiceException;
import com.hzs.common.core.utils.CommonUtil;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.domain.member.base.CuAwardsControl;
import com.hzs.common.domain.member.detail.CuMemberServiceLog;
import com.hzs.common.security.service.UserTokenService;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.member.account.dto.BusinessCommissionDTO;
import com.hzs.member.account.service.ICuMemberTradeService;
import com.hzs.member.base.mapper.CuAwardsControlMapper;
import com.hzs.member.base.service.ICuAwardsControlService;
import com.hzs.member.base.vo.CuAwardsControlVO;
import com.hzs.member.detail.service.ICuMemberServiceLogService;
import com.hzs.system.sys.IApprovalServiceApi;
import com.hzs.system.sys.dto.ApprovalSubmitDTO;
import com.hzs.system.sys.dto.BusinessLogDTO;
import com.hzs.system.sys.dto.LoginUser;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 真实奖衔控制 服务实现类
 *
 * @author hzs
 * @since 2023-04-07
 */
@Service
public class CuAwardsControlServiceImpl extends ServiceImpl<CuAwardsControlMapper, CuAwardsControl> implements ICuAwardsControlService {

    @Autowired
    private UserTokenService userTokenService;
    @Autowired
    private ICuMemberServiceLogService memberServiceLogService;
    @DubboReference
    IApprovalServiceApi approvalServiceApi;
    @Autowired
    private ICuMemberTradeService cuMemberTradeService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public List<CuAwardsControlVO> queryAwardsControlList(CuAwardsControlVO controlVO) {
        return baseMapper.queryAwardsControlList(controlVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean savePetition(CuAwardsControlVO controlVO) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        //业务单号
        String code = CommonUtil.createSerialNumber(EOrderPrefix.SELF_SERVICE.getValue());
        // 封装修改会员编号业务日志
        List<BusinessLogDTO> dtoList = new ArrayList<>();
        Date date = new Date();
        Long userID = SecurityUtils.getUserId();
        LoginUser loginUser = userTokenService.getLoginUser();
        for (CuAwardsControlVO ca : controlVO.getUpdateParentParamList()) {
            //审核通过 修改审核状态,累加修改次数
            CuMemberServiceLog memberLog = new CuMemberServiceLog();
            memberLog.setPkMember(ca.getPkMember());
            memberLog.setPkCreator(userID);
            memberLog.setCreationTime(date);
            memberLog.setPkCountry(pkCountry);
            memberLog.setApproveStatus(EApproveStatus.ALREADY_SUBMIT.getValue());
            memberLog.setBusinessNo(code);
            memberLog.setEditType(EApprovalBusiness.AWARDS_CONTROL_SAVE.getValue());
            memberLog.setEditTypePay(EApprovalBusiness.AWARDS_CONTROL_SAVE.getValue());
            memberLog.setNewValue(JSONObject.toJSONString(ca));
            memberLog.setApproveNumber(ca.getChangeNumber());
            memberLog.setSingleAmount(new BigDecimal(0));
            memberServiceLogService.save(memberLog);
            String content = EApprovalBusiness.AWARDS_CONTROL_SAVE.getLabel();
            if (StringUtils.isNotEmpty(ca.getRealAwardsKeyVal())) {
                content = content + " 真实奖衔： " + ca.getRealAwardsKeyVal();
            }
            if (StringUtils.isNotEmpty(ca.getMentoringAwardKeyVal())) {
                content = content + " 辅导奖衔： " + ca.getMentoringAwardKeyVal();
            }
            if (StringUtils.isNotEmpty(ca.getDividendAwardKeyVal())) {
                content = content + " 分红奖衔： " + ca.getDividendAwardKeyVal();
            }
            if (StringUtils.isNotEmpty(ca.getExtremeAwardsKeyVal())) {
                content = content + " 级差奖衔： " + ca.getExtremeAwardsKeyVal();
            }
            if (StringUtils.isNotEmpty(ca.getReplyExamAwardKeyVal())) {
                content = content + " 复购考核奖衔： " + ca.getReplyExamAwardKeyVal();
            }
            if (StringUtils.isNotEmpty(ca.getDivvyExamAwardsKeyVal())) {
                content = content + " 分红考核奖衔： " + ca.getDivvyExamAwardsKeyVal();
            }
            //组装日志数据
            BusinessLogDTO businessLog = BusinessLogDTO.builder()
                    .businessType(EApprovalBusiness.AWARDS_CONTROL_SAVE.getValue())
                    .businessCode(code)
                    .pkMember(ca.getPkMember())
                    .content(content)
                    .pkCreator(userID)
                    .pkCountry(pkCountry)
                    .freeSignFlag(false).build();
            dtoList.add(businessLog);
        }
        //生成签呈
        ApprovalSubmitDTO approvalSubmitDTO = ApprovalSubmitDTO.builder().eApprovalBusiness(EApprovalBusiness.AWARDS_CONTROL_SAVE)
                .businessCode(code)
                .signType(ESignType.getEnumByValue(controlVO.getSignType()))
                .remark(controlVO.getRemark())
                .pkMemberList(controlVO.getPkMemberList())
                .userIdList(controlVO.getUserIdList())
                .sendIdList(controlVO.getSendIdList())
                .fileList(controlVO.getFileList())
                .build();
        R<String> submit = approvalServiceApi.submit(approvalSubmitDTO, loginUser);
        if (!submit.isSuccess()) {
            log.error("====" + submit.getData());
            throw new RuntimeException(ConfigMsgConstants.AWARDS_CONTROL_SAVE_PETITION);
        }
        //扣钱
        if (controlVO.getProcessType() == EProcessType.DOUBLEPAY.getValue()) {
            BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
            businessCommissionDTO.setPkCountry(pkCountry);
            businessCommissionDTO.setPkAccount(controlVO.getPkAccount());
            businessCommissionDTO.setMemberAmountDTOList(controlVO.getMemberAmountDTOList());
            businessCommissionDTO.setTradeType(EApprovalBusiness.AWARDS_CONTROL_SAVE.getValue());
            Boolean b = cuMemberTradeService.businessCommissionSubmit(businessCommissionDTO);
            if (!b) {
                throw new ServiceException(ConfigMsgConstants.AWARDS_CONTROL_SAVE_PETITION);
            }
        }
        //发送MQ到操作日志
        rabbitTemplate.convertAndSend(RabbitMqConstants.BUSINESS_LOG_EXCHANGE, RabbitMqConstants.BUSINESS_LOG_KEY,
                dtoList);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean upPetition(CuAwardsControlVO controlVO) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        //业务单号
        String code = CommonUtil.createSerialNumber(EOrderPrefix.SELF_SERVICE.getValue());
        // 封装修改会员编号业务日志
        List<BusinessLogDTO> dtoList = new ArrayList<>();
        Date date = new Date();
        Long userID = SecurityUtils.getUserId();
        LoginUser loginUser = userTokenService.getLoginUser();
        for (CuAwardsControlVO ca : controlVO.getUpdateParentParamList()) {
            //审核通过 修改审核状态,累加修改次数
            CuMemberServiceLog memberLog = new CuMemberServiceLog();
            memberLog.setPkMember(ca.getPkMember());
            memberLog.setPkCreator(userID);
            memberLog.setCreationTime(date);
            memberLog.setPkCountry(pkCountry);
            memberLog.setApproveStatus(EApproveStatus.ALREADY_SUBMIT.getValue());
            memberLog.setBusinessNo(code);
            memberLog.setEditType(EApprovalBusiness.AWARDS_CONTROL_MODIFY.getValue());
            memberLog.setEditTypePay(EApprovalBusiness.AWARDS_CONTROL_MODIFY.getValue());
            memberLog.setNewValue(JSONObject.toJSONString(ca));
            memberLog.setApproveNumber(ca.getChangeNumber());
            memberLog.setSingleAmount(new BigDecimal(0));
            memberServiceLogService.save(memberLog);
            String content = EApprovalBusiness.AWARDS_CONTROL_SAVE.getLabel();
            if (StringUtils.isNotEmpty(ca.getRealAwardsKeyVal())) {
                content = content + " 真实奖衔： " + ca.getRealAwardsKeyVal();
            }
            if (StringUtils.isNotEmpty(ca.getMentoringAwardKeyVal())) {
                content = content + " 辅导奖衔： " + ca.getMentoringAwardKeyVal();
            }
            if (StringUtils.isNotEmpty(ca.getDividendAwardKeyVal())) {
                content = content + " 分红奖衔： " + ca.getDividendAwardKeyVal();
            }
            if (StringUtils.isNotEmpty(ca.getExtremeAwardsKeyVal())) {
                content = content + " 级差奖衔： " + ca.getExtremeAwardsKeyVal();
            }
            if (StringUtils.isNotEmpty(ca.getReplyExamAwardKeyVal())) {
                content = content + " 复购考核奖衔： " + ca.getReplyExamAwardKeyVal();
            }
            if (StringUtils.isNotEmpty(ca.getDivvyExamAwardsKeyVal())) {
                content = content + " 分红考核奖衔： " + ca.getDivvyExamAwardsKeyVal();
            }
            //组装日志数据
            BusinessLogDTO businessLog = BusinessLogDTO.builder()
                    .businessType(EApprovalBusiness.AWARDS_CONTROL_MODIFY.getValue())
                    .businessCode(code)
                    .pkMember(ca.getPkMember())
                    .content(content)
                    .pkCreator(userID)
                    .pkCountry(pkCountry)
                    .freeSignFlag(false).build();
            dtoList.add(businessLog);
        }
        //生成签呈
        ApprovalSubmitDTO approvalSubmitDTO = ApprovalSubmitDTO.builder().eApprovalBusiness(EApprovalBusiness.AWARDS_CONTROL_MODIFY)
                .businessCode(code)
                .signType(ESignType.getEnumByValue(controlVO.getSignType()))
                .remark(controlVO.getRemark())
                .pkMemberList(controlVO.getPkMemberList())
                .sendIdList(controlVO.getSendIdList())
                .fileList(controlVO.getFileList())
                .userIdList(controlVO.getUserIdList()).build();
        R<String> submit = approvalServiceApi.submit(approvalSubmitDTO, loginUser);
        if (!submit.isSuccess()) {
            log.error("====" + submit.getData());
            throw new RuntimeException(ConfigMsgConstants.AWARDS_CONTROL_MODIFY_PETITION);
        }
        //扣钱
        if (controlVO.getProcessType() == EProcessType.DOUBLEPAY.getValue()) {
            BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
            businessCommissionDTO.setPkCountry(controlVO.getPkCountry());
            businessCommissionDTO.setPkAccount(controlVO.getPkAccount());
            businessCommissionDTO.setMemberAmountDTOList(controlVO.getMemberAmountDTOList());
            businessCommissionDTO.setTradeType(EApprovalBusiness.AWARDS_CONTROL_MODIFY.getValue());
            Boolean b = cuMemberTradeService.businessCommissionSubmit(businessCommissionDTO);
            if (!b) {
                throw new ServiceException(ConfigMsgConstants.AWARDS_CONTROL_MODIFY_PETITION);
            }
        }

        //发送MQ到操作日志
        rabbitTemplate.convertAndSend(RabbitMqConstants.BUSINESS_LOG_EXCHANGE, RabbitMqConstants.BUSINESS_LOG_KEY,
                dtoList);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delPetition(CuAwardsControlVO controlVO) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        //业务单号
        String code = CommonUtil.createSerialNumber(EOrderPrefix.SELF_SERVICE.getValue());
        // 封装修改会员编号业务日志
        List<BusinessLogDTO> dtoList = new ArrayList<>();
        Date date = new Date();
        Long userID = SecurityUtils.getUserId();
        LoginUser loginUser = userTokenService.getLoginUser();
        for (CuAwardsControlVO ca : controlVO.getUpdateParentParamList()) {
            //审核通过 修改审核状态,累加修改次数
            CuMemberServiceLog memberLog = new CuMemberServiceLog();
            memberLog.setPkMember(ca.getPkMember());
            memberLog.setPkCreator(userID);
            memberLog.setCreationTime(date);
            memberLog.setPkCountry(pkCountry);
            memberLog.setApproveStatus(EApproveStatus.ALREADY_SUBMIT.getValue());
            memberLog.setBusinessNo(code);
            memberLog.setEditType(EApprovalBusiness.AWARDS_CONTROL_DELETE.getValue());
            memberLog.setEditTypePay(EApprovalBusiness.AWARDS_CONTROL_DELETE.getValue());
            memberLog.setNewValue(JSONObject.toJSONString(ca));
            memberLog.setApproveNumber(ca.getChangeNumber());
            memberLog.setSingleAmount(new BigDecimal(0));
            memberServiceLogService.save(memberLog);
            String content = EApprovalBusiness.AWARDS_CONTROL_SAVE.getLabel();
            if (StringUtils.isNotEmpty(ca.getRealAwardsKeyVal())) {
                content = content + " 真实奖衔： " + ca.getRealAwardsKeyVal();
            }
            if (StringUtils.isNotEmpty(ca.getMentoringAwardKeyVal())) {
                content = content + " 辅导奖衔： " + ca.getMentoringAwardKeyVal();
            }
            if (StringUtils.isNotEmpty(ca.getDividendAwardKeyVal())) {
                content = content + " 分红奖衔： " + ca.getDividendAwardKeyVal();
            }
            if (StringUtils.isNotEmpty(ca.getExtremeAwardsKeyVal())) {
                content = content + " 级差奖衔： " + ca.getExtremeAwardsKeyVal();
            }
            if (StringUtils.isNotEmpty(ca.getReplyExamAwardKeyVal())) {
                content = content + " 复购考核奖衔： " + ca.getReplyExamAwardKeyVal();
            }
            if (StringUtils.isNotEmpty(ca.getDivvyExamAwardsKeyVal())) {
                content = content + " 分红考核奖衔： " + ca.getDivvyExamAwardsKeyVal();
            }
            //组装日志数据
            BusinessLogDTO businessLog = BusinessLogDTO.builder()
                    .businessType(EApprovalBusiness.AWARDS_CONTROL_DELETE.getValue())
                    .businessCode(code)
                    .pkMember(ca.getPkMember())
                    .content(content)
                    .pkCreator(userID)
                    .pkCountry(pkCountry)
                    .freeSignFlag(false).build();
            dtoList.add(businessLog);
        }
        //生成签呈
        ApprovalSubmitDTO approvalSubmitDTO = ApprovalSubmitDTO.builder().eApprovalBusiness(EApprovalBusiness.AWARDS_CONTROL_DELETE)
                .businessCode(code)
                .signType(ESignType.getEnumByValue(controlVO.getSignType()))
                .remark(controlVO.getRemark())
                .pkMemberList(controlVO.getPkMemberList())
                .sendIdList(controlVO.getSendIdList())
                .fileList(controlVO.getFileList())
                .userIdList(controlVO.getUserIdList()).build();
        R<String> submit = approvalServiceApi.submit(approvalSubmitDTO, loginUser);
        if (!submit.isSuccess()) {
            log.error("====" + submit.getData());
            throw new RuntimeException(ConfigMsgConstants.AWARDS_CONTROL_DELETE_PETITION);
        }
        //扣钱
        if (controlVO.getProcessType() == EProcessType.DOUBLEPAY.getValue()) {
            BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
            businessCommissionDTO.setPkCountry(controlVO.getPkCountry());
            businessCommissionDTO.setPkAccount(controlVO.getPkAccount());
            businessCommissionDTO.setMemberAmountDTOList(controlVO.getMemberAmountDTOList());
            businessCommissionDTO.setTradeType(EApprovalBusiness.AWARDS_CONTROL_DELETE.getValue());
            Boolean b = cuMemberTradeService.businessCommissionSubmit(businessCommissionDTO);
            if (!b) {
                throw new ServiceException(ConfigMsgConstants.AWARDS_CONTROL_DELETE_PETITION);
            }
        }

        //发送MQ到操作日志
        rabbitTemplate.convertAndSend(RabbitMqConstants.BUSINESS_LOG_EXCHANGE, RabbitMqConstants.BUSINESS_LOG_KEY,
                dtoList);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CuAwardsControlVO affirm(CuAwardsControlVO controlVO) {
        //业务单号
        String code = CommonUtil.createSerialNumber(EOrderPrefix.HANDLE_BUSINESS.getValue());
        // 封装修改会员编号业务日志
        List<BusinessLogDTO> dtoList = new ArrayList<>();
        for (CuAwardsControlVO ccl : controlVO.getUpdateParentParamList()) {
            // 修改审核状态,累加修改次数
            CuMemberServiceLog memberLog = new CuMemberServiceLog();
            memberLog.setPkMember(ccl.getPkMember());
            memberLog.setPkCreator(controlVO.getPkCreator());
            memberLog.setCreationTime(controlVO.getCreationTime());
            memberLog.setPkCountry(controlVO.getPkCountry());
            memberLog.setApproveStatus(EApproveStatus.FINISH.getValue());
            memberLog.setBusinessNo(code);
            memberLog.setNewValue(JSONObject.toJSONString(ccl));
            memberLog.setApproveNumber(ccl.getChangeNumber());
            memberLog.setSingleAmount(new BigDecimal(0));
            String content = "";
            CuAwardsControl control = BeanUtil.copyProperties(ccl, CuAwardsControl.class);
            if (controlVO.getApprovalBusiness() == EApprovalBusiness.AWARDS_CONTROL_SAVE.getValue()) {
                content = EApprovalBusiness.AWARDS_CONTROL_SAVE.getLabel();
                memberLog.setEditType(EApprovalBusiness.AWARDS_CONTROL_SAVE.getValue());
                memberLog.setEditTypePay(EApprovalBusiness.AWARDS_CONTROL_SAVE.getValue());
                //新增真实奖衔控制
                control.setPkMember(ccl.getPkMember());
                control.setPkCountry(controlVO.getPkCountry());
                control.setPkCreator(controlVO.getPkCreator());
                control.setCreationTime(controlVO.getCreationTime());
                baseMapper.insert(control);
            }
            if (controlVO.getApprovalBusiness() == EApprovalBusiness.AWARDS_CONTROL_MODIFY.getValue()) {
                content = EApprovalBusiness.AWARDS_CONTROL_MODIFY.getLabel();
                memberLog.setEditType(EApprovalBusiness.AWARDS_CONTROL_MODIFY.getValue());
                memberLog.setEditTypePay(EApprovalBusiness.AWARDS_CONTROL_MODIFY.getValue());
                //修改真实奖衔控制
                control.setPkMember(ccl.getPkMember());
                control.setPkCountry(controlVO.getPkCountry());
                control.setPkCreator(controlVO.getPkCreator());
                control.setCreationTime(controlVO.getCreationTime());
                baseMapper.updateById(control);
            }
            if (controlVO.getApprovalBusiness() == EApprovalBusiness.AWARDS_CONTROL_DELETE.getValue()) {
                content = EApprovalBusiness.AWARDS_CONTROL_DELETE.getLabel();
                memberLog.setEditType(EApprovalBusiness.AWARDS_CONTROL_DELETE.getValue());
                memberLog.setEditTypePay(EApprovalBusiness.AWARDS_CONTROL_DELETE.getValue());
                //删除真实奖衔控制
                UpdateWrapper<CuAwardsControl> updateWrapper = new UpdateWrapper<>();
                updateWrapper.set("DEL_FLAG", EDelFlag.DELETE.getValue());
                updateWrapper.set("CREATION_TIME", controlVO.getCreationTime());
                updateWrapper.set("PK_CREATOR", controlVO.getPkCreator());
                updateWrapper.eq("PK_ID", control.getPkId());
                baseMapper.update(null, updateWrapper);
            }
            if (StringUtils.isNotEmpty(ccl.getRealAwardsKeyVal())) {
                content = content + " 真实奖衔： " + ccl.getRealAwardsKeyVal();
            }
            if (StringUtils.isNotEmpty(ccl.getMentoringAwardKeyVal())) {
                content = content + " 辅导奖衔： " + ccl.getMentoringAwardKeyVal();
            }
            if (StringUtils.isNotEmpty(ccl.getDividendAwardKeyVal())) {
                content = content + " 分红奖衔： " + ccl.getDividendAwardKeyVal();
            }
            if (StringUtils.isNotEmpty(ccl.getExtremeAwardsKeyVal())) {
                content = content + " 级差奖衔： " + ccl.getExtremeAwardsKeyVal();
            }
            if (StringUtils.isNotEmpty(ccl.getReplyExamAwardKeyVal())) {
                content = content + " 复购考核奖衔： " + ccl.getReplyExamAwardKeyVal();
            }
            if (StringUtils.isNotEmpty(ccl.getDivvyExamAwardsKeyVal())) {
                content = content + " 分红考核奖衔： " + ccl.getDivvyExamAwardsKeyVal();
            }
            //扣钱
            if (controlVO.getProcessType() == EProcessType.AVOIDSIGNING.getValue()) {
                BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
                businessCommissionDTO.setPkCountry(controlVO.getPkCountry());
                businessCommissionDTO.setPkAccount(ccl.getPkAccount());
                businessCommissionDTO.setMemberAmountDTOList(controlVO.getMemberAmountDTOList());
                businessCommissionDTO.setTradeType(controlVO.getApprovalBusiness());
                Boolean b = cuMemberTradeService.businessCommissionSubmit(businessCommissionDTO);
                if (!b) {
                    if (controlVO.getApprovalBusiness() == EApprovalBusiness.AWARDS_CONTROL_SAVE.getValue()) {
                        throw new ServiceException(ConfigMsgConstants.AWARDS_CONTROL_SAVE_PETITION);
                    }
                    if (controlVO.getApprovalBusiness() == EApprovalBusiness.AWARDS_CONTROL_MODIFY.getValue()) {
                        throw new ServiceException(ConfigMsgConstants.AWARDS_CONTROL_MODIFY_PETITION);
                    }
                    if (controlVO.getApprovalBusiness() == EApprovalBusiness.AWARDS_CONTROL_DELETE.getValue()) {
                        throw new ServiceException(ConfigMsgConstants.AWARDS_CONTROL_DELETE_PETITION);
                    }
                }
            }
            memberServiceLogService.save(memberLog);
            //组装日志数据
            BusinessLogDTO businessLog = BusinessLogDTO.builder()
                    .businessType(controlVO.getApprovalBusiness())
                    .businessCode(code)
                    .pkMember(ccl.getPkMember())
                    .content(content)
                    .pkCreator(controlVO.getPkCreator())
                    .pkCountry(controlVO.getPkCountry())
                    .freeSignFlag(true).build();
            dtoList.add(businessLog);
        }
        if (CollectionUtil.isNotEmpty(dtoList)) {
            //发送MQ到操作日志
            rabbitTemplate.convertAndSend(RabbitMqConstants.BUSINESS_LOG_EXCHANGE, RabbitMqConstants.BUSINESS_LOG_KEY,
                    dtoList);
        }
        return controlVO;
    }
}
