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


import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
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.other.mapper.AcOtherPriceConfigMapper;
import com.hzs.activity.other.param.OtherPriceConfigQueryParam;
import com.hzs.activity.other.service.IAcOtherPriceConfigService;
import com.hzs.common.core.constant.msg.CommonMsgConstants;
import com.hzs.common.core.constant.msg.DocumentMsgConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.exception.base.BaseException;
import com.hzs.common.core.utils.CommonUtil;
import com.hzs.common.core.utils.DateUtils;
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.other.AcOtherPriceConfig;
import com.hzs.common.domain.activity.other.ext.AcOtherPriceConfigExt;
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;

import java.util.ArrayList;

/**
 * 活动： 车奖/旅游奖活动配置表 服务实现类
 *
 * @author hzs
 * @since 2024-01-17
 */
@Service
public class AcOtherPriceConfigServiceImpl extends ServiceImpl<AcOtherPriceConfigMapper, AcOtherPriceConfig> implements IAcOtherPriceConfigService {
    @Autowired
    private IActivityService activityService;
    @DubboReference
    private IApprovalServiceApi iApprovalServiceApi;
    @Autowired
    private IAcBaseConfigService baseConfigService;
    @Autowired
    private IAcApprovalLogService acApprovalLogService;
    @Autowired
    private IAcOtherPriceConfigService otherPriceConfigService;
    /**
     * 提交车奖/旅游奖 活动配置
     * @param param
     * @param loginUser
     * @return
     */

    @Override
    public String otherPriceConfigSubmit(OtherPriceConfigQueryParam param, LoginUser loginUser) {
        // 会员ID
        Long userId = SecurityUtils.getUserId();
        // 所属国家
        Integer pkCountry = SecurityUtils.getPkCountry();
        if (loginUser == null){
            loginUser = new LoginUser();
            loginUser.setUserId(userId);
            loginUser.setDataCountry(pkCountry);
        }

        // 业务编号
        String businessCode = CommonUtil.createSerialNumber(EOrderPrefix.ACTIVITY_CODE);

        // 批量保存日志
        Integer approvalType = null;
        EApprovalBusiness approvalBusiness = null;
        List<AcApprovalLog> approvalLogList = new ArrayList<>();
        if (param.getActivityParam().getActType().equals(EActType.TOURISM.getValue())){
            approvalType = EApprovalBusiness.TOURISM_AWARD.getValue();
            approvalBusiness = EApprovalBusiness.TOURISM_AWARD;
        }else if (param.getActivityParam().getActType().equals(EActType.CAR.getValue())){
            approvalType = EApprovalBusiness.CAR_AWARD.getValue();
            approvalBusiness = EApprovalBusiness.CAR_AWARD;
        }
        // 活动审批日志
        AcApprovalLog acApprovalLog = new AcApprovalLog();
        acApprovalLog.setApprovalType(approvalType);
        acApprovalLog.setBusinessCode(businessCode);
        acApprovalLog.setPkCreator(userId);
        acApprovalLog.setPkCountry(pkCountry);
        acApprovalLog.setAfterData(JSONUtil.toJsonStr(param));
        if (null != param.getActivityParam().getPkId()) {
            acApprovalLog.setPkBusiness(param.getActivityParam().getPkId());
        }
        approvalLogList.add(acApprovalLog);

        if (acApprovalLogService.saveBatch(approvalLogList)) {
            // 保存审批日志成功，提交签呈
            // 提交签呈处理
            R<String> resultR = iApprovalServiceApi.submitOrder(
                    ApprovalSubmitDTO.builder()
                            .eApprovalBusiness(approvalBusiness)
                            .businessCode(businessCode)
                            .businessData(JSONUtil.toJsonStr(param))
                            .signType(ESignType.getEnumByValue(param.getSignType()))
                            .userIdList(param.getUserIdList())
                            .sendIdList(param.getSendIdList())
                            .remark(param.getRemark())
                            .fileList(param.getFileList())
                            .build(),
                    loginUser,
                    null
            );
            if (resultR.isSuccess()) {
                return TransactionUtils.getContent(CommonMsgConstants.OPERATION_SUCCESS);
            }
            throw new BaseException(TransactionUtils.getContent(CommonMsgConstants.OPERATION_FAILED) + ": " + resultR.getMsg());
        }
        return TransactionUtils.getContent(CommonMsgConstants.OPERATION_FAILED);
    }

    @Override
    public List<AcOtherPriceConfigExt> queryList(List<Integer> actTypeList, String nowDate, Integer pkCountry) {
        return baseMapper.queryList(actTypeList, nowDate, pkCountry);
    }

    /**
     * 车奖/旅游奖 添加修改
     * @param businessResult
     */

    @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 "审批数据不存在！";
        }
        String data = approvalLog.getAfterData();
        OtherPriceConfigQueryParam otherPriceConfigQueryParam = JSONUtil.toBean(data, OtherPriceConfigQueryParam.class);
        if (otherPriceConfigQueryParam.getControlType().equals(EControlType.SAVE.getValue())
                || otherPriceConfigQueryParam.getControlType().equals(EControlType.MODIFY.getValue())){
            saveAll(otherPriceConfigQueryParam,loginUser.getDataCountry());
        }else if (otherPriceConfigQueryParam.getControlType().equals(EControlType.DELETE.getValue())){
            deleteOther(otherPriceConfigQueryParam,loginUser.getDataCountry());
        }

        acApprovalLogService.updateApprovalLog(businessResult.getEApprovalBusiness(), businessResult.getBusinessCode(), loginUser.getDataCountry(), loginUser.getUserId(), EApproveRechargeStatus.AGREE, businessResult.getApproveRemark());
        log.error("车奖/旅游奖同意处理失败: 更新数据失败");
        return TransactionUtils.getContent(DocumentMsgConstants.DOCUMENT_ORDER_ERROR);
    }

    @Override
    public String ApprovalReject(ApprovalBusinessResultDTO approvalBusinessResultDTO) {
        EApprovalBusiness eApprovalBusiness = approvalBusinessResultDTO.getEApprovalBusiness();
        String businessCode = approvalBusinessResultDTO.getBusinessCode();
        LoginUser loginUser = approvalBusinessResultDTO.getLoginUser();
        AcApprovalLog approvalLog = acApprovalLogService.queryApprovalLog(eApprovalBusiness, businessCode, loginUser.getDataCountry());
        if (null == approvalLog) {
            return "审批数据不存在！";
        }
        //更新审批状态
        acApprovalLogService.updateApprovalLog(eApprovalBusiness, businessCode, loginUser.getDataCountry(),
                loginUser.getUserId(), EApproveRechargeStatus.REJECT, approvalBusinessResultDTO.getApproveRemark());
        return null;
    }

    /**
     * 删除规则
     * @param otherPriceConfigQueryParam
     * @param pkCountry
     */
    private void deleteOther(OtherPriceConfigQueryParam otherPriceConfigQueryParam, Integer pkCountry) {
        Long pkBaseId = otherPriceConfigQueryParam.getActivityParam().getPkId();

        baseConfigService.removeById(pkBaseId);
        QueryWrapper<AcOtherPriceConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PK_BASE_ID",pkBaseId);
        otherPriceConfigService.remove(queryWrapper);
    }

    /**
     * 新增/修改
     * @param otherPriceConfigQueryParam
     * @param pkCountry
     */
    private void saveAll(OtherPriceConfigQueryParam otherPriceConfigQueryParam, Integer pkCountry) {
        ActivityParam activityParam = otherPriceConfigQueryParam.getActivityParam();
        Long pkUser = SecurityUtils.getUserId();
        // 新增列表
        List<AcOtherPriceConfig> saveList = new ArrayList<>();
        // 修改列表
        List<AcOtherPriceConfig> updateList = new ArrayList<>();
        for (AcOtherPriceConfig otherPriceConfig : otherPriceConfigQueryParam.getOtherPriceConfigList()) {
            if (otherPriceConfig.getPkId() == null){
                otherPriceConfig.setCreationTime(DateUtils.currentDateTime());
                otherPriceConfig.setPkCreator(pkUser);
                otherPriceConfig.setType(otherPriceConfigQueryParam.getActivityParam().getActType());
                otherPriceConfig.setPkCountry(pkCountry);
                saveList.add(otherPriceConfig);
            }else {
                otherPriceConfig.setModifiedTime(DateUtils.currentDateTime());
                otherPriceConfig.setPkModified(pkUser);
                otherPriceConfig.setType(otherPriceConfigQueryParam.getActivityParam().getActType());
                updateList.add(otherPriceConfig);
            }
        }
        AcBaseConfig baseConfig = null;
        if (activityParam.getPkId() != null){
            // 修改基础配置
            baseConfig = activityService.updateBaseConfig(activityParam);
        }else {
            // 增加基础配置
            activityParam.setPkCountry(pkCountry);
            activityParam.setPkCreator(SecurityUtils.getUserId());
            activityParam.setActType(otherPriceConfigQueryParam.getActivityParam().getActType());
            activityParam.setCreationTime(DateUtils.currentDateTime());
            baseConfig = activityService.saveBaseConfig(activityParam);
        }
        saveList.addAll(updateList);
        if (saveList != null && saveList.size() > 0){
            deleteByPkCountryAll(pkCountry,null,baseConfig.getPkId());
            for (AcOtherPriceConfig otherPriceConfig : saveList) {
                otherPriceConfig.setPkBaseId(baseConfig.getPkId());
            }
            saveBatch(saveList);
    //        saveBatch(updateList);
        }
    }
    /**
     * 删除所有规则
     * @param pkCountry
     */
    private void deleteByPkCountryAll(Integer pkCountry,List<Long> notIdlList,Long pkBaseId) {
        baseMapper.deleteByPkCountryAll(pkCountry,notIdlList,pkBaseId);
    }
}
