package com.docus.server.message.service;

import com.docus.core.util.Func;
import com.docus.infrastructure.redis.service.IdService;
import com.docus.infrastructure.web.api.ResultCode;
import com.docus.server.message.config.MessageForwardConfig;
import com.docus.server.message.dto.Message;
import com.docus.server.message.dto.MessageResponse;
import com.docus.server.message.entity.UnifyMessage;
import com.docus.server.message.enums.DataFormatEnum;
import com.docus.server.message.mapper.UnifyMessageMapper;
import com.docus.server.message.result.MessageInfo;
import com.docus.server.message.result.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;

import java.io.FileInputStream;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author WYBDEV
 */
@Service
@Slf4j
public class UnifyMessageServiceImpl implements UnifyMessageService {
    private UnifyMessageMapper unifyMessageMapper;
    private IdService idService;
    private MessageCarrier messageCarrier;

    @Autowired
    public void setUnifyMessageMapper(UnifyMessageMapper unifyMessageMapper) {
        this.unifyMessageMapper = unifyMessageMapper;
    }

    @Autowired
    public void setIdService(IdService idService) {
        this.idService = idService;
    }

    @Autowired
    public void setMessageCarrier(MessageCarrier messageCarrier) {
        this.messageCarrier = messageCarrier;
    }

    @Override
    public String pushInformation(String method, String message) {
        String uuid = Func.randomUUID();
        log.info("[{}] 收到消息，方法：{}，消息为：{}", uuid, method, message);
        MessageForwardConfig.MessageForward messageForward = MessageForwardConfig.wsMessageForward(method);
        if (messageForward == null || Func.isEmpty(messageForward.getUrls())) {
            log.info("[{}] 返回消息：方法匹配错误！", uuid);
            return "方法匹配错误！";
        }
        DataFormatEnum dataFormatEnum = DataFormatEnum.fromValue(messageForward.getMessageDataType());
        if (dataFormatEnum == null) {
            log.info("[{}] 返回消息：格式匹配错误！", uuid);
            return "格式匹配错误！";
        }
        UnifyMessage unifyMessage = saveMessage(method, message);
        try {
            List<MessageResponse> responseLis = messageCarrier.send(new Message(method, message), messageForward);
            String returnMessage = verifyMessageResponseAndGetReturnMessage(responseLis);
            log.info("[{}] 返回消息：{}", uuid, returnMessage);
            return returnMessage;
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            messageFailed(unifyMessage);
            MessageInfo messageInfo = new MessageInfo(dataFormatEnum, message);
            String returnMessage = ResultUtil.dynamicParameterReplace(messageInfo, messageForward.getErrorResult());
            log.info("[{}] 返回消息：{}", uuid, returnMessage);
            return returnMessage;
        }
    }

    private void messageFailed(UnifyMessage unifyMessage) {
        UnifyMessage updateMessage = new UnifyMessage();
        updateMessage.setId(unifyMessage.getId());
        updateMessage.setState(0);
        unifyMessageMapper.updateById(updateMessage);
    }

    private String verifyMessageResponseAndGetReturnMessage(List<MessageResponse> responseLis) {
        for (MessageResponse response : responseLis) {
            if (response.getRetry() == 1) {
                throw new RuntimeException("需要重试！");
            }
        }
        responseLis = responseLis.stream().filter(item -> Func.isNotEmpty(item.getRespCode())).collect(Collectors.toList());
        if (Func.isEmpty(responseLis)) {
            throw new RuntimeException("未收到成功和失败的返回结果！");
        }
        for (MessageResponse response : responseLis) {
            if (ResultCode.FAILED.getCode().equals(response.getRespCode())) {
                return response.getRespMessage();
            }
        }
        return responseLis.get(0).getRespMessage();
    }

    public static void main(String[] args) throws Exception {


            String path="F:\\xiamen-jiashi\\pdf\\interface.pdf";

            BASE64Encoder encoder = new BASE64Encoder();

            FileInputStream inputStream2 = new FileInputStream(path);
            System.out.println(inputStream2.available());
            byte[] bytes2 = new byte[inputStream2.available()];
            inputStream2.read(bytes2, 0, inputStream2.available());
            inputStream2.close();
            String base642 = encoder.encode(bytes2);

            System.out.println(base642);


    }
    private UnifyMessage saveMessage(String method, String message) {
        UnifyMessage unifyMessage = new UnifyMessage();
        unifyMessage.setId(idService.getDateSeq());
        unifyMessage.setMessage(message);
        unifyMessage.setMethod(method);
        unifyMessage.setState(1);
        unifyMessage.setCreateTime(new Date());
        unifyMessageMapper.insert(unifyMessage);
        return unifyMessage;
    }


}
