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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
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.activity.base.param.ActivityParam;
import com.hzs.activity.base.service.IActivityService;
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.people.mapper.AcNewPeopleRuleConfigMapper;
import com.hzs.activity.people.param.AcBaseConfigParam;
import com.hzs.activity.people.service.IAcNewPeopleRuleConfigService;
import com.hzs.activity.people.vo.AcNewPeopleRuleConfigVO;
import com.hzs.activity.wares.service.IAcGiftConfigService;
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.utils.CommonUtil;
import com.hzs.common.core.utils.TransactionUtils;
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.people.AcNewPeopleRuleConfig;
import com.hzs.system.sys.IApprovalServiceApi;
import com.hzs.system.sys.dto.ApprovalBusinessResultDTO;
import com.hzs.system.sys.dto.ApprovalSubmitDTO;
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;

/**
 * <p>
 * 新人礼包规则表 服务实现类
 * </p>
 *
 * @author hzs
 * @since 2023-04-24
 */
@Service
public class AcNewPeopleRuleConfigServiceImpl extends ServiceImpl<AcNewPeopleRuleConfigMapper, AcNewPeopleRuleConfig> implements IAcNewPeopleRuleConfigService {

    @Autowired
    private IAcApprovalLogService iAcApprovalLogService;
    @DubboReference
    private IApprovalServiceApi approvalServiceApi;
    @Autowired
    private IAcBaseConfigService iAcBaseConfigService;
    @Autowired
    private IAcGiftConfigService iAcGiftConfigService;
    @Autowired
    private IAcGoalMemberConfigService iAcGoalMemberConfigService;
    @Autowired
    private IActivityService iActivityService;


    /**
     * @description: 新人礼包发起签呈
     * @author: zhang jing
     * @date: 2023/4/25 11:54
     * @param: [anpVO]
     * @return: boolean
     **/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean petition(AcBaseConfigParam anpParam) {
        //业务单号
        String code = CommonUtil.createSerialNumber(EOrderPrefix.ACTIVITY_CODE.getValue());
        Date date = new Date();
        //添加日志信息
        AcApprovalLog acLog = new AcApprovalLog();
        acLog.setApprovalType(EApprovalBusiness.NEW_PEOPLE.getValue());
        acLog.setAfterData(JSONObject.toJSONString(anpParam));
        acLog.setApprovalStatus(EAgentApprovalStatus.UNAPPROVED.getValue());
        acLog.setBusinessCode(code);
        acLog.setPkCreator(anpParam.getLoginUser().getUserId());
        acLog.setCreationTime(date);
        acLog.setPkCountry(anpParam.getPkCountry());
        acLog.setControlType(anpParam.getControlType());
        iAcApprovalLogService.save(acLog);
        //生成签呈
        ApprovalSubmitDTO approvalSubmitDTO = ApprovalSubmitDTO.builder().eApprovalBusiness(EApprovalBusiness.NEW_PEOPLE)
                .businessCode(code)
                .signType(ESignType.getEnumByValue(anpParam.getSignType()))
                .remark(anpParam.getRemark())
                .userIdList(anpParam.getUserIdList()).build();
        R<String> submit = approvalServiceApi.submit(approvalSubmitDTO, anpParam.getLoginUser());
        if (!submit.isSuccess()) {
            log.error("====" + submit.getData());
            throw new RuntimeException(TransactionUtils.getContent(ConfigMsgConstants.NEW_PEOPLE_PETITION));
        }
        return true;
    }

    /**
     * @description: 查询新人礼包规则
     * @author: zhang jing
     * @date: 2023/4/25 15:40
     * @param: [nplVO]
     * @return: java.util.List<com.hzs.activity.people.vo.AcNewPeopleRuleConfigVO>
     **/
    @Override
    public List<AcNewPeopleRuleConfigVO> queryNplList(AcNewPeopleRuleConfigVO nplVO) {
        return baseMapper.queryNplList(nplVO);
    }

    /**
     * @description: 新人礼包签呈审批
     * @author: zhang jing
     * @date: 2023/4/25 18:04
     * @param: [abrDTO]
     * @return: boolean
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String approval(ApprovalBusinessResultDTO abrDTO) {
        Date date = new Date();
        // 用户ID
        Long userId = abrDTO.getLoginUser().getUserId();
        // 所属国家
        Integer pkCountry = abrDTO.getLoginUser().getDataCountry();
        AcApprovalLog acApprovalLog = iAcApprovalLogService.queryApprovalLog(abrDTO.getEApprovalBusiness(),
                abrDTO.getBusinessCode(), pkCountry);
        UpdateWrapper<AcApprovalLog> up = new UpdateWrapper<>();
        up.eq("BUSINESS_CODE", abrDTO.getBusinessCode());
        up.set("PK_MODIFIED", userId);
        up.set("MODIFIED_TIME", date);
        if (abrDTO.getEApproveStatus().getValue() == EApproveStatus.FINISH.getValue()) {
            AcBaseConfigParam nplData = JSONUtil.toBean(acApprovalLog.getAfterData(), AcBaseConfigParam.class);
            //新增
            if (acApprovalLog.getControlType() == EControlType.SAVE.getValue()) {
                //新增活动主表
                ActivityParam activityParam = nplData.getActivityParam();
                activityParam.setPkCreator(userId);
                activityParam.setPkCountry(pkCountry);
                AcBaseConfig baseConfig = iActivityService.saveBaseConfig(nplData.getActivityParam());
                //目标群体配置列表
                iActivityService.saveGoalMemberConfig(activityParam, baseConfig);
                //活动规则表
                if (CollectionUtil.isNotEmpty(nplData.getAnpList())) {
                    for (AcNewPeopleRuleConfigVO nplc : nplData.getAnpList()) {
                        AcNewPeopleRuleConfig npl = BeanUtil.toBean(nplc, AcNewPeopleRuleConfig.class);
                        npl.setPkBaseId(baseConfig.getPkId());
                        npl.setCreationTime(date);
                        npl.setPkCountry(pkCountry);
                        npl.setPkCreator(userId);
                        baseMapper.insert(npl);
                        if (CollectionUtil.isNotEmpty(nplc.getAgcList())) {
                            for (AcGiftConfig agc : nplc.getAgcList()) {
                                agc.setActType(EActType.NEW_GIFT.getValue());
                                agc.setPkRuleId(npl.getPkId());
                                agc.setCreationTime(date);
                                agc.setPkCountry(pkCountry);
                                agc.setPkCreator(userId);
                                iAcGiftConfigService.save(agc);
                            }
                        }
                    }
                }
            }
            //修改
            if (acApprovalLog.getControlType() == EControlType.MODIFY.getValue()) {
                //修改活动主表
                AcBaseConfig baseConfig = BeanUtil.toBean(nplData.getActivityParam(), AcBaseConfig.class);
                baseConfig.setModifiedTime(date);
                baseConfig.setPkModified(userId);
                iAcBaseConfigService.updateById(baseConfig);
                //修改目标群体配置列表
                if (CollectionUtil.isNotEmpty(nplData.getActivityParam().getGoalMemberConfigList())) {
                    UpdateWrapper<AcGoalMemberConfig> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("PK_BASE_ID", baseConfig.getPkId());
                    updateWrapper.set("DEL_FLAG", EDelFlag.DELETE.getValue());
                    iAcGoalMemberConfigService.update(updateWrapper);
                    //目标群体配置列表
                    for (AcGoalMemberConfig agm : nplData.getActivityParam().getGoalMemberConfigList()) {
                        agm.setPkBaseId(baseConfig.getPkId());
                        agm.setPkCountry(pkCountry);
                        agm.setCreationTime(date);
                        agm.setPkCreator(userId);
                        iAcGoalMemberConfigService.save(agm);
                    }
                }
                if (CollectionUtil.isNotEmpty(nplData.getAnpList())) {
                    QueryWrapper<AcNewPeopleRuleConfig> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("PK_BASE_ID", baseConfig.getPkId());
                    List<AcNewPeopleRuleConfig> arcList = baseMapper.selectList(queryWrapper);
                    //删除赠品
                    if (CollectionUtil.isNotEmpty(arcList)) {
                        for (AcNewPeopleRuleConfig arc : arcList) {
                            UpdateWrapper<AcGiftConfig> updateWrapper = new UpdateWrapper<>();
                            updateWrapper.set("DEL_FLAG", EDelFlag.DELETE.getValue());
                            updateWrapper.eq("PK_RULE_ID", arc.getPkId());
                            iAcGiftConfigService.update(updateWrapper);
                        }
                    }
                    //删除规则
                    UpdateWrapper<AcNewPeopleRuleConfig> updateArc = new UpdateWrapper<>();
                    updateArc.eq("PK_BASE_ID", baseConfig.getPkId());
                    updateArc.set("DEL_FLAG", EDelFlag.DELETE.getValue());
                    baseMapper.update(null, updateArc);
                    for (AcNewPeopleRuleConfigVO nplc : nplData.getAnpList()) {
                        AcNewPeopleRuleConfig npl = BeanUtil.toBean(nplc, AcNewPeopleRuleConfig.class);
                        //修改规则
                        npl.setPkCountry(pkCountry);
                        npl.setCreationTime(date);
                        npl.setPkCreator(userId);
                        npl.setPkBaseId(baseConfig.getPkId());
                        baseMapper.insert(npl);
                        if (CollectionUtil.isNotEmpty(nplc.getAgcList())) {
                            for (AcGiftConfig agc : nplc.getAgcList()) {
                                agc.setPkRuleId(npl.getPkId());
                                agc.setActType(EActType.NEW_GIFT.getValue());
                                agc.setCreationTime(date);
                                agc.setPkCountry(pkCountry);
                                agc.setPkCreator(userId);
                                iAcGiftConfigService.save(agc);
                            }
                        }
                    }
                }
            }
            //删除
            if (acApprovalLog.getControlType() == EControlType.DELETE.getValue()) {
//                AcBaseConfigParam oldData = JSONUtil.toBean(acApprovalLog.getBeforeData(), AcBaseConfigParam.class);
                //删除活动主表
                AcBaseConfig oldAbc = BeanUtil.copyProperties(nplData.getActivityParam(), AcBaseConfig.class);
                UpdateWrapper<AcBaseConfig> updateBase = new UpdateWrapper<>();
                updateBase.set("DEL_FLAG", EDelFlag.DELETE.getValue());
                updateBase.set("MODIFIED_TIME", date);
                updateBase.set("PK_MODIFIED", userId);
                updateBase.eq("PK_ID", oldAbc.getPkId());
                iAcBaseConfigService.update(updateBase);

                //删除目标群体配置列表
                UpdateWrapper<AcGoalMemberConfig> updateWrapperAG = new UpdateWrapper<>();
                updateWrapperAG.eq("PK_BASE_ID", oldAbc.getPkId());
                updateWrapperAG.set("DEL_FLAG", EDelFlag.DELETE.getValue());
                iAcGoalMemberConfigService.update(updateWrapperAG);

                if (CollectionUtil.isNotEmpty(nplData.getAnpList())) {
                    //删除规则
                    UpdateWrapper<AcNewPeopleRuleConfig> updateWrapper = new UpdateWrapper();
                    updateWrapper.set("DEL_FLAG", EDelFlag.DELETE.getValue());
                    updateWrapper.eq("PK_BASE_ID", oldAbc.getPkId());
                    updateWrapper.set("MODIFIED_TIME", date);
                    updateWrapper.set("PK_MODIFIED", userId);
                    baseMapper.update(null, updateWrapper);
                    for (AcNewPeopleRuleConfigVO nplc : nplData.getAnpList()) {
                        if (CollectionUtil.isNotEmpty(nplc.getAgcList())) {
                            UpdateWrapper<AcGiftConfig> upAgc = new UpdateWrapper();
                            upAgc.eq("PK_RULE_ID", nplc.getPkId());
                            upAgc.set("DEL_FLAG", EDelFlag.DELETE.getValue());
                            iAcGiftConfigService.update(upAgc);
                        }
                    }
                }
            }
            //更新日志表
            up.set("APPROVAL_STATUS", EAgentApprovalStatus.APPROVED.getValue());
            iAcApprovalLogService.update(up);
        } else {
            up.set("APPROVAL_STATUS", EAgentApprovalStatus.REFUSE.getValue());
            iAcApprovalLogService.update(up);
        }
        return null;
    }


}
