package cn.axzo.msg.center.im.channel.handler;

import cn.axzo.msg.center.api.enums.ReceiveTypeEnum;
import cn.axzo.msg.center.api.request.MsgBody4Guest;
import cn.axzo.msg.center.common.exception.ServiceException;
import cn.axzo.msg.center.common.model.ProfileIdRepair;
import cn.axzo.msg.center.common.utils.PlaceholderResolver;
import cn.axzo.msg.center.domain.enums.NativeTypeEnum;
import cn.axzo.msg.center.im.channel.IMChannelHandler;
import cn.axzo.msg.center.im.domain.dto.IMSendMessageDTO;
import cn.axzo.msg.center.im.domain.enums.IMChannelEnum;
import cn.axzo.msg.center.im.domain.param.IMSendSingleMessageParam;
import cn.axzo.msg.center.inside.notices.service.IYouMengMessageService;
import cn.axzo.msg.center.service.dto.ButtonRouterDTO;
import cn.axzo.msg.center.service.dto.PersonDTO;
import cn.axzo.msg.center.service.enums.IdentityTypeEnum;
import cn.azxo.framework.common.utils.StringUtils;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Optional;

/**
 * @description
 *   友盟即时通信渠道
 *
 * @author cold_blade
 * @date 2023/9/27
 * @version 1.0
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class YouMengHandler implements IMChannelHandler {

    private final IYouMengMessageService youMengMessageService;

    @Override
    public void sendSingleMessage(IMSendSingleMessageParam param) {
        youMengMessageService.sendPushMessage(convert(param));
    }

    @Override
    public IMChannelEnum channel() {
        return IMChannelEnum.YOU_MENG;
    }

    private MsgBody4Guest convert(IMSendSingleMessageParam param) {
        MsgBody4Guest imMessage = new MsgBody4Guest();
        imMessage.setTy(0);
        imMessage.setF("0");
        imMessage.setNickName(param.getMessage().getGroupName());
        imMessage.setAppClient(param.getAppClientType().getCode());
        String toId = buildToId(param.getReceiver(), param.getMessage().getBizCode());
        imMessage.setT(toId);
        imMessage.setM(param.getMessage().getMsgContent());

        JSONObject jsonObject = buildMessageExt2(param.getMessage());
        imMessage.setM2(jsonObject.toJSONString());
        imMessage.setM3(String.valueOf(param.getReceiver().getId()));
        return imMessage;
    }

    private String buildToId(PersonDTO person, String bizCode) {
        Long identityId = person.getIdentity().getId();
        switch (toReceiveType(person.getIdentity().getType())) {
            case CM_LEADER:
                return ReceiveTypeEnum.CM_LEADER.getMessage() + ProfileIdRepair.workerLeaderNewId2Old(identityId);
            case CM_WORKER:
                return ReceiveTypeEnum.CM_WORKER.getMessage() + ProfileIdRepair.workerNewId2OldId(identityId);
            case CMP_USER:
                return ReceiveTypeEnum.CMP_USER.getMessage() + ProfileIdRepair.entUserNew2OldId(identityId);
            case NOT_IDENTITY:
                return ReceiveTypeEnum.NOT_IDENTITY.getMessage() + person.getId();
            case NORMAL:
                return ReceiveTypeEnum.NORMAL.getMessage() + person.getId();
            default:
                log.error("消息推送用户类型错误 bizId:[{}]", bizCode);
                throw new ServiceException("消息推送失败");
        }
    }

    private JSONObject buildMessageExt2(IMSendMessageDTO message) {
        final JSONObject extra = new JSONObject();
        Collection<ButtonRouterDTO> messageRouters = message.getRouters();
        if (messageRouters.isEmpty()) {
            extra.put("ar", "");
            extra.put("ir", "");
        } else {
            // 业务上不会跳转微信小程序
            messageRouters.forEach(item -> {
                PlaceholderResolver pr = PlaceholderResolver.getDefaultResolver();
                String url = pr.resolveByMap(item.getUrl(), message.getRouteParam());
                extra.put("rt", NativeTypeEnum.getByCode(item.getTerminalType().getCode()).getMessage());
                switch (item.getTerminalType()) {
                    case IOS:
                        extra.put("ir", url);
                        break;
                    case ANDROID:
                        extra.put("ar", url);
                        break;
                    case WEB_VIEW:
                    case MINI_PROGRAM:
                        // 小程序
                        extra.put("ar", url);
                        extra.put("ir", url);
                        break;
                    default:
                }
            });
        }
        extra.put("msgId", message.getMsgId());
        extra.put("p", message.getRouteParam());
        extra.put("t", message.getMsgTitle());
        extra.put("extra", message.getExtInfo().toJSONString());
        // 临时处理发送类型，如果消息type为1时，需要前端清空teamId,并且重新拉取数据
        Integer exType = message.getExtInfo().getInteger("type");
        extra.put("type", exType);
        if (StringUtils.isNotBlank(message.getAudioFileName())) {
            extra.put("audio", message.getAudioFileName());
        }
        return extra;
    }

    private ReceiveTypeEnum toReceiveType(IdentityTypeEnum identityType) {
        return Optional.ofNullable(ReceiveTypeEnum.valueOf(identityType.getCode()))
                .orElse(ReceiveTypeEnum.NOT_IDENTITY);
    }
}
