package com.prolog.rdc.tms.service.message.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.prolog.framework.core.exception.BizException;
import com.prolog.rdc.tms.model.dto.message.ChannelMessageDTO;
import com.prolog.rdc.tms.model.dto.message.QwMsgDTO;
import com.prolog.rdc.tms.service.message.MessageChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 企微消息
 * @author hongbo.pan
 * @date 2022/11/17
 */
@Slf4j
@Service
public class QwChannel implements MessageChannel {

    @Override
    public void send(ChannelMessageDTO channelMessageDTO) {
        log.info("topic={},channelMessageDTO={}", "QwChannel", JSON.toJSONString(channelMessageDTO));
        QwMsgDTO textMsg = new QwMsgDTO();
        textMsg.setMsgtype("text");
        QwMsgDTO.QwText text = new QwMsgDTO.QwText();
        text.setContent(channelMessageDTO.getMessageConfigDTO().getContent());
        // 手机号@人
//        if (CollectionUtil.isNotEmpty(channelMessageDTO.getChannelMessageUserDTOList())) {
//            List<String> mobileList = channelMessageDTO.getChannelMessageUserDTOList().stream().map(ChannelMessageUserDTO::getPhone)
//                    .filter(StrUtil::isNotBlank).distinct().collect(Collectors.toList());
//            if (CollectionUtil.isNotEmpty(mobileList)) {
//                text.setMentioned_mobile_list(mobileList);
//            }
//        }
        textMsg.setText(text);
        String body = JSON.toJSONString(textMsg);
        log.info("topic={},title={},body={}", "QwChannel", "sendQw", body);
        HttpResponse response = null;
        try {
            response = HttpUtil.createPost(channelMessageDTO.getMessageConfigDTO().getQwWebhook())
                    .contentType(ContentType.JSON.getValue()).timeout(60 * 1000).body(body).execute();
            log.info("topic={},title={},response={}", "QwChannel", "sendQw", JSON.toJSONString(response));
        } catch (Exception e) {
            log.error("topic={},title={}", "QwChannel", "sendQw", e);
            throw e;
        }
        if (ObjectUtil.isNull(response) || HttpStatus.HTTP_OK != response.getStatus()) {
            throw new BizException("发送企微返回异常,状态码=" + response.getStatus() + ",response=" + JSON.toJSONString(response));
        }
    }
}
