package cn.axzo.msg.center.notices.client.controller;

import cn.axzo.msg.center.api.request.AliMessageCallbackRequestDto;
import cn.axzo.msg.center.api.response.AliCallbackResponseDto;
import cn.axzo.msg.center.notices.common.enums.MessageChannelEnum;
import cn.axzo.msg.center.notices.common.lang.LoggerTemplate;
import cn.axzo.msg.center.notices.common.utils.KeyUtils;
import cn.axzo.msg.center.notices.integration.client.DingDingClient;
import cn.axzo.msg.center.notices.manager.api.dto.request.ChuangLanSmsReportRequestDto;
import cn.axzo.msg.center.notices.manager.api.dto.response.ChuangLanCallbackResponseDto;
import cn.axzo.msg.center.notices.service.api.MessageCallbackService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;


/**
 *  @author: szg
 *  @Date: 2021/5/28 15:49
 *  @Description: 消息回调处理
 */
@Slf4j
@RestController
@RequestMapping(value = "/webApi")
public class MessageCallbackController {

    @Resource(name = "messageCallbackService")
    private MessageCallbackService messageCallbackService;

    @Resource(name = "dingDingClient")
    private DingDingClient dingDingClient;

    @Resource(name = "loggerTemplate")
    private LoggerTemplate loggerTemplate;


    /**
     * 阿里云回调
     * @param request
     * @return
     */
    @PostMapping(value = "/ali/status/callback")
    public AliCallbackResponseDto aliCallbackHandle(
        @RequestBody List<AliMessageCallbackRequestDto> request) {
        log.info("MessageCallbackController#aliCallbackHandle request param is {}",
            JSON.toJSONString(request));
        return messageCallbackService.aliCallbackHandle(request);
    }


    /**
     * 创蓝回调
     * @param request
     * @return
     */
    @GetMapping(value = "/chuangLan/status/callback")
    public ChuangLanCallbackResponseDto chuangLanCallbackHandle(ChuangLanSmsReportRequestDto request){
        log.info("MessageCallbackController#chuangLanCallbackHandle request param is {}", JSON.toJSONString(request));

        if(StringUtils.isBlank(request.getMsgid()) ||
            StringUtils.isBlank(request.getMobile()) ||
            StringUtils.isBlank(request.getUid())) {
            dingDingClient.notifyChannelCallback(MessageChannelEnum.CHUANG_LAN.getCode(),
                JSON.toJSONString(request), "msgId and mobile and uid must not be null");
            log.info("MessageCallbackController#chuangLanCallbackHandle request param format is error");
            return ChuangLanCallbackResponseDto.success();
        }

        String traceId = KeyUtils.getKey(request.getMsgid(), request.getMobile());
        return loggerTemplate.execute(()-> messageCallbackService.chuangLanCallbackHandle(request),traceId);
    }

}
