package com.sckw.payment.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.sckw.payment.job.AsyncPool;
import com.sckw.payment.model.JumpUrlConfig;
import com.sckw.payment.model.KwpLedgerLogisticsTrack;
import com.sckw.payment.model.KwpLedgerTradeTrack;
import com.sckw.payment.model.constant.JumpEnum;
import com.sckw.stream.enums.MessageEnum;
import com.sckw.stream.model.SckwMessage;
import com.sckw.stream.model.UserInfo;
import com.sckw.system.api.RemoteSystemService;
import com.sckw.system.api.model.dto.res.EntCacheResDto;
import com.sckw.system.api.model.dto.res.UserCacheResDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Map;
import java.util.Objects;

/**
 * @author xucaiqin
 * @date 2023-09-06 20:20:45
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class MessageSender {
    private final StreamBridge streamBridge;
    private final JumpUrlConfig jumpUrlConfig;
    @DubboReference(version = "1.0.0", group = "design", check = false)
    private RemoteSystemService remoteSystemService;
    private final KwpLedgerTradeTrackService tradeTrackService;
    private final KwpLedgerLogisticsTrackService logisticsTrackService;

    /**
     * 变更人 当前操作用户，LoginUserHolder.getUserId()
     * 系统管理员，queryEntCacheById contactsId
     * 推送创建人
     *
     * @param map
     * @param user        用户id为创建人id，企业id为创建人所在企业
     * @param messageEnum
     */
    public void sendCreate(Long createBy, Map<String, Object> map, UserInfo user, MessageEnum messageEnum) {
        AsyncPool.addTask(() -> {
            SckwMessage sckwMessage = new SckwMessage(messageEnum).setMsgUrls(jumpUrlConfig.getMapUrl(JumpEnum.getByEnum(messageEnum))).setParams(map).setUserInfos(Collections.singletonList(user)).setCreateBy(createBy);
            log.info("推送创建人：{}", JSONObject.toJSONString(sckwMessage));
            streamBridge.send("sckw-message", JSON.toJSONString(sckwMessage));
        });
    }

    /**
     * 推送系统管理员
     *
     * @param map
     * @param entId       对账单关联的企业id
     * @param messageEnum 消息枚举
     */
    public void sendManager(Long createBy, Map<String, Object> map, Long entId, MessageEnum messageEnum) {
        AsyncPool.addTask(() -> {
            EntCacheResDto entCacheResDto = remoteSystemService.queryEntCacheById(entId);
            if (Objects.nonNull(entCacheResDto)) {
                SckwMessage sckwMessage = new SckwMessage(messageEnum).setMsgUrls(jumpUrlConfig.getMapUrl(JumpEnum.getByEnum(messageEnum))).setParams(map).setUserInfos(Collections.singletonList(new UserInfo(entCacheResDto.getContactsId(), entCacheResDto.getId()))).setCreateBy(createBy);
                log.info("推送系统管理员：{}", JSONObject.toJSONString(sckwMessage));
                streamBridge.send("sckw-message", JSON.toJSONString(sckwMessage));
            }
        });

    }

    /**
     * 推送销售变更人
     *
     * @param createBy
     * @param map
     * @param ledgerId    对账单id
     * @param messageEnum
     */
    private void sendSellChanger(Long createBy, Map<String, Object> map, Long ledgerId, MessageEnum messageEnum) {
        AsyncPool.addTask(() -> {
            KwpLedgerTradeTrack kwpLedgerTradeTrack = tradeTrackService.queryLedgered(ledgerId);
            if (Objects.nonNull(kwpLedgerTradeTrack)) {
                UserCacheResDto userCacheResDto = remoteSystemService.queryUserCacheById(kwpLedgerTradeTrack.getCreateBy());
                EntCacheResDto entCacheResDto = Objects.nonNull(userCacheResDto) ? (Objects.nonNull(userCacheResDto.getEntInfo()) ? userCacheResDto.getEntInfo() : new EntCacheResDto()) : new EntCacheResDto();
                SckwMessage sckwMessage = new SckwMessage(messageEnum).setMsgUrls(jumpUrlConfig.getMapUrl(JumpEnum.getByEnum(messageEnum))).setParams(map).setUserInfos(Collections.singletonList(new UserInfo(kwpLedgerTradeTrack.getCreateBy(), entCacheResDto.getId()))).setCreateBy(createBy);
                log.info("推送变更人：{}", JSONObject.toJSONString(sckwMessage));
                streamBridge.send("sckw-message", JSON.toJSONString(sckwMessage));
            }
        });
    }

    /**
     * 推送采购变更人
     *
     * @param createBy
     * @param map
     * @param ledgerId
     * @param messageEnum
     */
    private void sendPurchaseChanger(Long createBy, Map<String, Object> map, Long ledgerId, MessageEnum messageEnum) {
        AsyncPool.addTask(() -> {
            KwpLedgerLogisticsTrack kwpLedgerLogisticsTrack = logisticsTrackService.queryLedgered(ledgerId);
            if (Objects.nonNull(kwpLedgerLogisticsTrack)) {
                UserCacheResDto userCacheResDto = remoteSystemService.queryUserCacheById(kwpLedgerLogisticsTrack.getCreateBy());
                EntCacheResDto entCacheResDto = Objects.nonNull(userCacheResDto) ? (Objects.nonNull(userCacheResDto.getEntInfo()) ? userCacheResDto.getEntInfo() : new EntCacheResDto()) : new EntCacheResDto();
                SckwMessage sckwMessage = new SckwMessage(messageEnum)
                        .setMsgUrls(jumpUrlConfig.getMapUrl(JumpEnum.getByEnum(messageEnum)))
                        .setParams(map).setUserInfos(Collections.singletonList(new UserInfo(kwpLedgerLogisticsTrack.getCreateBy(), entCacheResDto.getId()))).setCreateBy(createBy);
                log.info("推送变更人：{}", JSONObject.toJSONString(sckwMessage));
                streamBridge.send("sckw-message", JSON.toJSONString(sckwMessage));
            }
        });
    }

    /**
     * 推送系统管理员和推送销售变更人
     *
     * @param createBy
     * @param map
     * @param ledgerId    对账单id
     * @param entId       需要推送的对账单关联的企业
     * @param messageEnum
     */
    public void sendSellBoth(Long createBy, Map<String, Object> map, Long ledgerId, Long entId, MessageEnum messageEnum) {
        AsyncPool.addTask(() -> {
            sendManager(createBy, map, entId, messageEnum);
            sendSellChanger(createBy, map, ledgerId, messageEnum);
        });
    }

    /**
     * 推送系统管理员和推送采购变更人
     *
     * @param createBy
     * @param map
     * @param ledgerId    对账单id
     * @param entId       需要推送的对账单关联的企业
     * @param messageEnum
     */
    public void sendPurchaseBoth(Long createBy, Map<String, Object> map, Long ledgerId, Long entId, MessageEnum messageEnum) {
        AsyncPool.addTask(() -> {
            sendManager(createBy, map, entId, messageEnum);
            sendPurchaseChanger(createBy, map, ledgerId, messageEnum);
        });
    }
}
