package cn.gov.customs.wxjy.ibmmq.utils;

import cn.gov.customs.wxjy.ibmmq.model.AddInfo;
import cn.gov.customs.wxjy.ibmmq.model.DxpMsg;
import cn.gov.customs.wxjy.ibmmq.model.ReceiverIds;
import cn.gov.customs.wxjy.ibmmq.model.TransInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

@Slf4j
@Service
public class XmlBuildTool {

    @Value("${msg.sender-id}")
    private String senderId;

    @Value("${msg.receiver-id}")
    private String receiverId;

    /**
     * 生成XML报文
     * @param message 消息
     * @return XML报文
     * @throws JAXBException 抛出JAXB异常
     */
    public String generateXmlMsg(String message) throws JAXBException {
        // 创建JAXB上下文
        JAXBContext jaxbContext = JAXBContext.newInstance(DxpMsg.class);

        // 创建Marshaller
        Marshaller marshaller = jaxbContext.createMarshaller();

        // 设置格式化输出
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        // 设置编码
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");

        // 创建DxpMsg对象并设置属性
        DxpMsg dxpMsg = new DxpMsg();
        dxpMsg.setVer("1.0");

        // 设置TransInfo
        TransInfo transInfo = new TransInfo();
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        transInfo.setCopMsgId(uuid);
        transInfo.setSenderId(senderId);

        // 处理接收者ID
		ReceiverIds receiverIds = new ReceiverIds();
        String[] ids = receiverId.split(",");
        receiverIds.setReceiverId(Arrays.asList(ids));
        transInfo.setReceiverIds(receiverIds);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        transInfo.setCreatTime(sdf.format(new Date()));
        transInfo.setMsgType("Mft9");

        dxpMsg.setTransInfo(transInfo);

        // 设置Data (Base64编码的内容)
        byte[] bytes = message.getBytes();
        Base64.Encoder encoder = Base64.getEncoder();
        String encodeString = encoder.encodeToString(bytes);
        dxpMsg.setData(encodeString);

        // 设置AddInfo
        AddInfo addInfo = new AddInfo();

        addInfo.setFileName("");
        addInfo.setIcCard("");

        dxpMsg.setAddInfo(addInfo);

        // 转换为XML字符串
        StringWriter writer = new StringWriter();
        marshaller.marshal(dxpMsg, writer);
        String xmlString = writer.toString();
//        log.info("XML报文：{}", xmlString);
        return xmlString;
    }

    /**
     * 解析XML报文
     * @param xmlMsg XML报文
     * @return DxpMsg对象
     * @throws JAXBException 抛出JAXB异常
     */
    public DxpMsg parseXmlToDxpMsg(String xmlMsg) throws JAXBException {
        // 创建JAXB上下文
        JAXBContext jaxbContext = JAXBContext.newInstance(DxpMsg.class);
        // 创建Unmarshaller
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        // 解析XML字符串
        return (DxpMsg) unmarshaller.unmarshal(new StringReader(xmlMsg));
    }
}
