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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hzs.activity.base.service.IAcApprovalLogService;
import com.hzs.activity.pick.mapper.AcPickMapper;
import com.hzs.activity.pick.param.AcPickQueryParam;
import com.hzs.activity.pick.param.AcPickSaveDetailParam;
import com.hzs.activity.pick.param.AcPickSaveParam;
import com.hzs.activity.pick.service.IAcPickLogService;
import com.hzs.activity.pick.service.IAcPickMemberLogService;
import com.hzs.activity.pick.service.IAcPickService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.activity.pick.vo.ApiPickListVO;
import com.hzs.common.core.constant.SystemFieldConstants;
import com.hzs.common.core.constant.msg.ActivityMsgConstants;
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.domain.activity.base.AcApprovalLog;
import com.hzs.common.domain.activity.pick.AcPick;
import com.hzs.common.domain.activity.pick.AcPickLog;
import com.hzs.common.domain.activity.pick.AcPickMemberLog;
import com.hzs.common.domain.activity.pick.ext.AcPickExt;
import com.hzs.common.domain.member.base.CuMember;
import com.hzs.common.core.utils.TransactionUtils;
import com.hzs.member.base.IMemberServiceApi;
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.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 提货基础表 服务实现类
 */
@Service
public class AcPickServiceImpl extends ServiceImpl<AcPickMapper, AcPick> implements IAcPickService {

    @Autowired
    private IAcApprovalLogService iAcApprovalLogService;
    @Autowired
    private IAcPickLogService iAcPickLogService;
    @Autowired
    private IAcPickMemberLogService iAcPickMemberLogService;

    @DubboReference
    IApprovalServiceApi iApprovalServiceApi;
    @DubboReference
    IMemberServiceApi iMemberServiceApi;

    @Override
    public boolean addPickByActivity(Long pkMember, Integer pickType, Long pkBaseConfig, Long pkDataId,
                                     Integer usableQuantity, String pickCover, Date receiveTime, Integer pkPostage,
                                     Long pkCreator, Integer pkCountry, Long pkBaseId) {
        if (baseMapper.addQuantityByActivity(pickType, pkBaseConfig, pkDataId, pkMember, usableQuantity, pkPostage, receiveTime, pkCreator) == 0) {
            AcPick acPick = new AcPick();
            acPick.setPkMember(pkMember);
            acPick.setPickType(pickType);
            if (null != pkBaseConfig) {
                acPick.setPkBaseConfig(pkBaseConfig);
            }
            acPick.setPkDataId(pkDataId);
            acPick.setUsableQuantity(usableQuantity);
            acPick.setPickCover(pickCover);
            if (null != receiveTime) {
                acPick.setReceiveTime(receiveTime);
            }
            if (null != pkPostage) {
                // 处理邮费模板
                acPick.setIsFreeMail(EYesNo.NO.getIntValue());
                acPick.setPkPostage(pkPostage);
            } else {
                acPick.setIsFreeMail(EYesNo.YES.getIntValue());
            }
            acPick.setPkCreator(pkCreator);
            acPick.setPkCountry(pkCountry);
            if (null != pkBaseId) {
                acPick.setPkBaseId(pkBaseId);
            }
            return baseMapper.insert(acPick) > 0;
        }
        return true;
    }

    @Override
    public boolean updatePickUse(Integer pickType, Long pkBaseConfig, Long pkDataId, Long pkMember, Integer quantity, Long pkModified) {
        return baseMapper.updatePickUse(pickType, pkBaseConfig, pkDataId, pkMember, quantity, pkModified) > 0;
    }

    @Override
    public List<AcPickExt> queryList(AcPickQueryParam param, Integer pkCountry) {
        return baseMapper.queryList(param, pkCountry);
    }

    @Override
    public AcPickExt queryDetail(Long pkId, Integer pkCountry) {
        return baseMapper.queryDetail(pkId, pkCountry);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String pickSubmit(AcPickSaveParam param, LoginUser loginUser) {
        // 会员ID
        Long userId = loginUser.getUserId();
        // 所属国家
        Integer pkCountry = loginUser.getDataCountry();

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

        // 批量保存日志
        List<AcApprovalLog> approvalLogList = new ArrayList<>();

        for (AcPickSaveDetailParam acPickSaveDetailParam : param.getDetailList()) {
            // 活动审批日志
            AcApprovalLog acApprovalLog = new AcApprovalLog();
            acApprovalLog.setApprovalType(EApprovalBusiness.PICK_ADD.getValue());
            acApprovalLog.setBusinessCode(businessCode);
            acApprovalLog.setPkCreator(userId);
            acApprovalLog.setPkCountry(pkCountry);
            acApprovalLog.setAfterData(JSONUtil.toJsonStr(acPickSaveDetailParam));
            if (null != acPickSaveDetailParam.getPkId()) {
                acApprovalLog.setPkBusiness(acPickSaveDetailParam.getPkId());
            }
            approvalLogList.add(acApprovalLog);
        }

        if (iAcApprovalLogService.saveBatch(approvalLogList)) {
            // 保存审批日志成功，提交签呈

            // 提交签呈处理
            R<String> resultR = iApprovalServiceApi.submitOrder(
                    ApprovalSubmitDTO.builder()
                            .eApprovalBusiness(EApprovalBusiness.PICK_ADD)
                            .businessCode(businessCode)
                            .signType(ESignType.getEnumByValue(param.getSignType()))
                            .userIdList(param.getUserIdList())
                            .sendIdList(param.getSendIdList())
                            .remark(param.getRemark())
                            .fileList(param.getFileList())
                            .build(),
                    loginUser,
                    null
            );
            if (resultR.isSuccess()) {
                return null;
            }
            throw new BaseException(TransactionUtils.getContent(CommonMsgConstants.OPERATION_FAILED) + ": " + resultR.getMsg());
        }
        return TransactionUtils.getContent(CommonMsgConstants.OPERATION_FAILED);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String pickApprovalAgree(ApprovalBusinessResultDTO resultDTO) {
        // 用户ID
        Long userId = resultDTO.getLoginUser().getUserId();
        // 所属国家
        Integer pkCountry = resultDTO.getLoginUser().getDataCountry();

        List<AcApprovalLog> approvalLogList = iAcApprovalLogService.queryApprovalLogList(resultDTO.getEApprovalBusiness(), resultDTO.getBusinessCode(), pkCountry);
        // 一批审批可能有多个
        AcApprovalLog approvalLog = approvalLogList.get(0);
        if (null == approvalLog) {
            log.error("提货充值同意处理失败: 签呈不存在!");
            return TransactionUtils.getContent(ActivityMsgConstants.PICK_NOT_EXIST);
        }
        if (EAgentApprovalStatus.UNAPPROVED.getValue() != approvalLog.getApprovalStatus()) {
            log.error("提货充值同意处理失败: 签呈已处理");
            return TransactionUtils.getContent(ActivityMsgConstants.PICK_PROCESSED);
        }

        // 新増提货列表
        List<AcPick> createList = new ArrayList<>();
        // 修改提货列表
        List<AcPick> updateList = new ArrayList<>();

        for (AcApprovalLog acApprovalLog : approvalLogList) {
            // 存在业务ID，则为修改
            AcPickSaveDetailParam detailParam = JSONUtil.toBean(acApprovalLog.getAfterData(), AcPickSaveDetailParam.class);
            // 当前会员
            CuMember cuMember = iMemberServiceApi.getMember(detailParam.getMemberCode()).getData();
            // 提货ID
            Long pickId = null;
            if (null == detailParam.getPkId()) {
                QueryWrapper<AcPick> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("PICK_TYPE", EPickType.PICK_PRODUCT.getValue());
                queryWrapper.eq("PK_BASE_CONFIG", 0);
                queryWrapper.eq("PK_DATA_ID", detailParam.getPkProduct());
                queryWrapper.eq("SPECS_NAME_ID", detailParam.getSpecsNameId());
                queryWrapper.eq("PK_MEMBER", cuMember.getPkId());
                AcPick acPick = this.getOne(queryWrapper);
                if (null != acPick) {
                    pickId = acPick.getPkId();
                }
            } else {
                pickId = detailParam.getPkId();
            }

            AcPick acPick = new AcPick();
            if (null == pickId) {
                // 新增提货数据
                acPick.setPkMember(cuMember.getPkId());
                acPick.setPickType(EPickType.PICK_PRODUCT.getValue());
                acPick.setPkDataId(detailParam.getPkProduct().longValue());
                acPick.setSpecsName(detailParam.getSpecsName());
                acPick.setSpecsNameId(detailParam.getSpecsNameId());
                acPick.setUsableQuantity(detailParam.getQuantity());
                acPick.setBaseQuantity(detailParam.getBaseQuantity());
                acPick.setReceiveTime(detailParam.getReceiveTime());
                acPick.setIsFreeMail(detailParam.getIsFreeMail());
                acPick.setPkPostage(detailParam.getPkPostage());
                acPick.setPkCreator(userId);
                acPick.setPkCountry(pkCountry);
                createList.add(acPick);
            } else {
                // 修改提货数据
                acPick.setPkId(pickId);
                acPick.setUsableQuantity(detailParam.getQuantity());
                acPick.setBaseQuantity(detailParam.getBaseQuantity());
                acPick.setReceiveTime(detailParam.getReceiveTime());
                acPick.setIsFreeMail(detailParam.getIsFreeMail());
                acPick.setPkPostage(detailParam.getPkPostage());
                acPick.setPkModified(userId);
                acPick.setModifiedTime(new Date());
                updateList.add(acPick);
            }
        }

        if (iAcApprovalLogService.updateApprovalLog(resultDTO.getEApprovalBusiness(), resultDTO.getBusinessCode(), pkCountry, userId, EApproveRechargeStatus.AGREE, resultDTO.getApproveRemark())) {
            // 更新修改记录

            // 提货操作日志
            List<AcPickLog> logList = new ArrayList<>();

            // 插入提货数据
            if (CollectionUtil.isNotEmpty(createList)) {
                for (AcPick acPick : createList) {
                    this.baseMapper.insert(acPick);

                    AcPickLog acPickLog = new AcPickLog();
                    acPickLog.setPkPick(acPick.getPkId());
                    acPickLog.setQuantity(acPick.getUsableQuantity());
                    acPickLog.setPkUser(userId);
                    acPickLog.setPkCountry(pkCountry);
                    logList.add(acPickLog);
                }
            }
            // 更新提货数据
            if (CollectionUtil.isNotEmpty(updateList)) {
                for (AcPick acPick : updateList) {
                    this.baseMapper.updatePickByPkId(acPick);

                    AcPickLog acPickLog = new AcPickLog();
                    acPickLog.setPkPick(acPick.getPkId());
                    acPickLog.setQuantity(acPick.getUsableQuantity());
                    acPickLog.setPkUser(userId);
                    acPickLog.setPkCountry(pkCountry);
                    logList.add(acPickLog);
                }
            }
            // 插入提货操作日志
            iAcPickLogService.insertBatch(logList);

            return null;
        }
        log.error("提货充值同意处理失败: 更新数据失败");
        return TransactionUtils.getContent(DocumentMsgConstants.DOCUMENT_ORDER_ERROR);
    }

    @Override
    public String pickApprovalReject(ApprovalBusinessResultDTO resultDTO) {
        // 用户ID
        Long userId = resultDTO.getLoginUser().getUserId();
        // 所属国家
        Integer pkCountry = resultDTO.getLoginUser().getDataCountry();

        List<AcApprovalLog> approvalLogList = iAcApprovalLogService.queryApprovalLogList(resultDTO.getEApprovalBusiness(), resultDTO.getBusinessCode(), pkCountry);
        // 一批审批可能有多个
        AcApprovalLog approvalLog = approvalLogList.get(0);
        if (null == approvalLog) {
            log.error("提货充值驳回处理失败: 签呈不存在!");
            return TransactionUtils.getContent(ActivityMsgConstants.PICK_NOT_EXIST);
        }
        if (EAgentApprovalStatus.UNAPPROVED.getValue() != approvalLog.getApprovalStatus()) {
            log.error("提货充值驳回处理失败: 签呈已处理");
            return TransactionUtils.getContent(ActivityMsgConstants.PICK_PROCESSED);
        }

        if (iAcApprovalLogService.updateApprovalLog(resultDTO.getEApprovalBusiness(), resultDTO.getBusinessCode(), pkCountry, userId, EApproveRechargeStatus.REJECT, resultDTO.getApproveRemark())) {
            return null;
        }
        log.error("提货充值驳回处理失败: 更新数据失败");
        return TransactionUtils.getContent(DocumentMsgConstants.DOCUMENT_ORDER_ERROR);
    }

    @Override
    public List<ApiPickListVO> pickList(Long pkMember, Integer pkCountry) {
        return baseMapper.pickList(pkMember, pkCountry);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean callbackPickOrder(Long pkMember, String orderCode) {
        QueryWrapper<AcPickMemberLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PK_MEMBER", pkMember);
        queryWrapper.eq("PICK_ORDER", orderCode);
        queryWrapper.eq(SystemFieldConstants.DEL_FLAG, EDelFlag.DELETE.getValue());
        AcPickMemberLog acPickMemberLog = iAcPickMemberLogService.getOne(queryWrapper);

        AcPick acPick = this.getById(acPickMemberLog.getPkPick());

        if (this.updatePickUse(acPick.getPickType(), acPick.getPkBaseConfig(), acPick.getPkDataId(),
                acPick.getPkMember(), acPickMemberLog.getPickQuantity(), acPick.getPkMember())) {
            // 更新使用数量成功
            UpdateWrapper<AcPickMemberLog> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq(SystemFieldConstants.PK_ID, acPickMemberLog.getPkId());
            updateWrapper.set(SystemFieldConstants.DEL_FLAG, EDelFlag.UN_DELETE.getValue());
            // 更新提货日志状态
            iAcPickMemberLogService.update(updateWrapper);

            return true;
        }
        return false;
    }

}
