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

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
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.TransactionUtils;
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.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.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 真实奖衔控制 服务实现类
 * </p>
 *
 * @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;

    /**
     * @description: 查询奖衔控制列表
     * @author: zhang jing
     * @date: 2023/4/8 11:40
     * @param: [controlVO]
     * @return: java.util.List<com.hzs.member.base.vo.CuAwardsControlVO>
     **/
    @Override
    public List<CuAwardsControlVO> queryAwardsControlList(CuAwardsControlVO controlVO) {
        return baseMapper.queryAwardsControlList(controlVO);
    }

    /**
     * @description: 添加真实奖衔控制-发起签呈
     * @author: zhang jing
     * @date: 2023/4/8 16:06
     * @param: [controlVO]
     * @return: boolean
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean savePetition(CuAwardsControlVO controlVO) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        //业务单号
        String code = CommonUtil.createSerialNumber(EOrderPrefix.HANDLE_BUSINESS.getValue());
        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);
        }
        //生成签呈
        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())
                .build();
        R<String> submit = approvalServiceApi.submit(approvalSubmitDTO, loginUser);
        if (!submit.isSuccess()) {
            log.error("====" + submit.getData());
            throw new RuntimeException(TransactionUtils.getContent(ConfigMsgConstants.AWARDS_CONTROL_SAVE_PETITION));
        }
        return true;
    }

    /**
     * @description: 修改真实奖衔控制-发起签呈
     * @author: zhang jing
     * @date: 2023/4/8 16:12
     * @param: [controlVO]
     * @return: boolean
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean upPetition(CuAwardsControlVO controlVO) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        //业务单号
        String code = CommonUtil.createSerialNumber(EOrderPrefix.SELF_SERVICE.getValue());
        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);
        }
        //生成签呈
        ApprovalSubmitDTO approvalSubmitDTO = ApprovalSubmitDTO.builder().eApprovalBusiness(EApprovalBusiness.AWARDS_CONTROL_MODIFY)
                .businessCode(code)
                .signType(ESignType.getEnumByValue(controlVO.getSignType()))
                .remark(controlVO.getRemark()).pkMemberList(controlVO.getPkMemberList()).userIdList(controlVO.getUserIdList()).build();
        R<String> submit = approvalServiceApi.submit(approvalSubmitDTO, loginUser);
        if (!submit.isSuccess()) {
            log.error("====" + submit.getData());
            throw new RuntimeException(TransactionUtils.getContent(ConfigMsgConstants.AWARDS_CONTROL_MODIFY_PETITION));
        }
        return true;
    }

    /**
     * @description: 删除真实奖衔控制-发起签呈
     * @author: zhang jing
     * @date: 2023/4/8 16:12
     * @param: [controlVO]
     * @return: boolean
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delPetition(CuAwardsControlVO controlVO) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        //业务单号
        String code = CommonUtil.createSerialNumber(EOrderPrefix.SELF_SERVICE.getValue());
        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);
        }
        //生成签呈
        ApprovalSubmitDTO approvalSubmitDTO = ApprovalSubmitDTO.builder().eApprovalBusiness(EApprovalBusiness.AWARDS_CONTROL_DELETE)
                .businessCode(code)
                .signType(ESignType.getEnumByValue(controlVO.getSignType()))
                .remark(controlVO.getRemark()).pkMemberList(controlVO.getPkMemberList()).userIdList(controlVO.getUserIdList()).build();
        R<String> submit = approvalServiceApi.submit(approvalSubmitDTO, loginUser);
        if (!submit.isSuccess()) {
            log.error("====" + submit.getData());
            throw new RuntimeException(TransactionUtils.getContent(ConfigMsgConstants.AWARDS_CONTROL_DELETE_PETITION));
        }
        return true;
    }

    @Override
    public List<CuAwardsControl> queryAllCuAwardsControl() {
        QueryWrapper<CuAwardsControl> queryWrapper = new QueryWrapper<>();
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * @description: 真实奖衔控制 免签 全免
     * @author: zhang jing
     * @date: 2023/7/17 19:15
     * @param: [controlVO]
     * @return: com.hzs.member.base.vo.CuAwardsControlVO
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CuAwardsControlVO affirm(CuAwardsControlVO controlVO) {
        //业务单号
        String code = CommonUtil.createSerialNumber(EOrderPrefix.HANDLE_BUSINESS.getValue());
        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));

            CuAwardsControl control = BeanUtil.copyProperties(ccl, CuAwardsControl.class);
            if (controlVO.getApprovalBusiness() == EApprovalBusiness.AWARDS_CONTROL_SAVE.getValue()) {
                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()) {
                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()) {
                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 (controlVO.getProcessType() == EProcessType.AVOIDSIGNING.getValue()) {
                BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
                businessCommissionDTO.setPkCountry(controlVO.getPkCountry());
                businessCommissionDTO.setMemberAmountDTOList(controlVO.getMemberAmountDTOList());
                businessCommissionDTO.setTradeType(EApprovalBusiness.CHANGE_MEMBER_CODE.getValue());
                Boolean b = cuMemberTradeService.businessCommissionSubmit(businessCommissionDTO);
                if (!b) {
                    throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_UPDATE_CODE_MONEY));
                }
            }
            memberServiceLogService.save(memberLog);
        }
        return controlVO;
    }
}
