package com.ygtx.common.utils.ice;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ygtx.common.config.IcePendingTaskProperties;
import com.ygtx.common.core.domain.ice.IcePendingTaskRequest;
import com.ygtx.common.core.domain.ice.IcePendingTaskResponse;
import com.ygtx.common.core.domain.ice.IcePendingTaskStatusRequest;
import com.ygtx.common.utils.StringUtils;
import com.ygtx.common.utils.http.IceSsoHttpUtil;
import org.apache.xmlbeans.impl.soap.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * ICE待办任务Web Service工具类
 *
 * @author ygt
 */
@Component
public class IcePendingTaskWebServiceUtil
{
    private static final Logger log = LoggerFactory.getLogger(IcePendingTaskWebServiceUtil.class);

    @Autowired
    private IcePendingTaskProperties icePendingTaskProperties;

    @Autowired
    private IceSsoHttpUtil iceSsoHttpUtil;

    /**
     * 推送待办消息
     *
     * @param request 待办消息请求对象
     * @return 响应结果
     */
    public IcePendingTaskResponse sendPendingTask(IcePendingTaskRequest request)
    {
        try
        {
            // 验证必要参数
            if (request == null)
            {
                throw new IllegalArgumentException("请求参数不能为空");
            }

            if (StringUtils.isEmpty(request.getPlatformId()))
            {
                request.setPlatformId(icePendingTaskProperties.getPlatformId());
            }

            if (StringUtils.isEmpty(request.getSystemId()))
            {
                request.setSystemId(icePendingTaskProperties.getSystemId());
            }

            if (StringUtils.isEmpty(request.getTitle()))
            {
                throw new IllegalArgumentException("标题不能为空");
            }

            if (StringUtils.isEmpty(request.getCode()))
            {
                throw new IllegalArgumentException("用户工号不能为空");
            }

            if (request.getType() == null)
            {
                request.setType(2); // 默认为2
            }

            if (StringUtils.isEmpty(request.getUrl()))
            {
                throw new IllegalArgumentException("跳转URL不能为空");
            }

            // 创建SOAP客户端并调用服务
            String wsdlUrl = icePendingTaskProperties.getWsdlUrl();
            if (StringUtils.isEmpty(wsdlUrl))
            {
                throw new RuntimeException("未配置ICE待办任务WSDL接口地址");
            }

            // 使用SOAP调用Web Service
            return callSendOpenMessageDataNew(wsdlUrl, request);
        }
        catch (Exception e)
        {
            log.error("推送ICE待办消息失败", e);
            IcePendingTaskResponse response = new IcePendingTaskResponse();
            response.setRet(-1);
            response.setMsg(e.getMessage());
            response.setSuccess(false);
            return response;
        }
    }

    /**
     * 更新待办任务状态
     *
     * @param request 状态变更请求对象
     * @return 响应结果
     */
    public IcePendingTaskResponse updatePendingTaskStatus(IcePendingTaskStatusRequest request)
    {
        try
        {
            // 验证必要参数
            if (request == null)
            {
                throw new IllegalArgumentException("请求参数不能为空");
            }

            if (StringUtils.isEmpty(request.getTaskId()))
            {
                throw new IllegalArgumentException("任务ID不能为空");
            }

            if (StringUtils.isEmpty(request.getIsCompleted()))
            {
                throw new IllegalArgumentException("完成状态不能为空");
            }

            if (StringUtils.isEmpty(request.getSystemId()))
            {
                request.setSystemId(icePendingTaskProperties.getSystemId());
            }

            String wsdlUrl = icePendingTaskProperties.getWsdlUrl();
            if (StringUtils.isEmpty(wsdlUrl))
            {
                throw new RuntimeException("未配置ICE待办任务WSDL接口地址");
            }

            // 使用SOAP调用Web Service
            return callUpdateMessageData(wsdlUrl, request);
        }
        catch (Exception e)
        {
            log.error("更新ICE待办任务状态失败", e);
            IcePendingTaskResponse response = new IcePendingTaskResponse();
            response.setRet(-1);
            response.setMsg(e.getMessage());
            response.setSuccess(false);
            return response;
        }
    }

    /**
     * 调用send_open_message_data_new方法
     *
     * @param wsdlUrl WSDL地址
     * @param request 请求参数
     * @return 响应结果
     */
    private IcePendingTaskResponse callSendOpenMessageDataNew(String wsdlUrl, IcePendingTaskRequest request) throws Exception
    {
        // 创建SOAP消息
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = messageFactory.createMessage();

        SOAPPart soapPart = soapMessage.getSOAPPart();

        // SOAP Envelope
        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.addNamespaceDeclaration("web", "http://webservice.soa.b2b.huawei.com");

        // SOAP Body
        SOAPBody soapBody = envelope.getBody();
        SOAPElement soapBodyElem = soapBody.addChildElement("send_open_message_data_new", "web");

        // 添加参数
        addParameter(soapBodyElem, "platform_id", request.getPlatformId());
        addParameter(soapBodyElem, "title", request.getTitle());
        addParameter(soapBodyElem, "sumary", request.getSumary());
        addParameter(soapBodyElem, "content", request.getContent());
        addParameter(soapBodyElem, "code", request.getCode());
        addParameter(soapBodyElem, "type", String.valueOf(request.getType()));
        addParameter(soapBodyElem, "url", request.getUrl());
        addParameter(soapBodyElem, "task_id", request.getTaskId());
        addParameter(soapBodyElem, "is_completed", request.getIsCompleted());
        addParameter(soapBodyElem, "system_id", request.getSystemId());

        soapMessage.saveChanges();

        // 发送SOAP请求
        SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
        SOAPConnection soapConnection = soapConnectionFactory.createConnection();

        SOAPMessage soapResponse = soapConnection.call(soapMessage, wsdlUrl);

        // 解析响应
        IcePendingTaskResponse response = parseSoapResponse(soapResponse);
        soapConnection.close();

        return response;
    }

    /**
     * 调用update_message_data方法
     *
     * @param wsdlUrl WSDL地址
     * @param request 请求参数
     * @return 响应结果
     */
    private IcePendingTaskResponse callUpdateMessageData(String wsdlUrl, IcePendingTaskStatusRequest request) throws Exception
    {
        // 创建SOAP消息
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = messageFactory.createMessage();

        SOAPPart soapPart = soapMessage.getSOAPPart();

        // SOAP Envelope
        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.addNamespaceDeclaration("web", "http://webservice.soa.b2b.huawei.com");

        // SOAP Body
        SOAPBody soapBody = envelope.getBody();
        SOAPElement soapBodyElem = soapBody.addChildElement("update_message_data", "web");

        // 添加参数
        addParameter(soapBodyElem, "task_id", request.getTaskId());
        addParameter(soapBodyElem, "is_completed", request.getIsCompleted());
        addParameter(soapBodyElem, "system_id", request.getSystemId());

        soapMessage.saveChanges();

        // 发送SOAP请求
        SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
        SOAPConnection soapConnection = soapConnectionFactory.createConnection();

        SOAPMessage soapResponse = soapConnection.call(soapMessage, wsdlUrl);

        // 解析响应
        IcePendingTaskResponse response = parseSoapResponse(soapResponse);
        soapConnection.close();

        return response;
    }

    /**
     * 添加参数到SOAP元素
     *
     * @param parent 父元素
     * @param name 参数名
     * @param value 参数值
     * @throws SOAPException
     */
    private void addParameter(SOAPElement parent, String name, String value) throws SOAPException
    {
        if (value != null)
        {
            SOAPElement param = parent.addChildElement(name);
            param.addTextNode(value);
        }
        else
        {
            SOAPElement param = parent.addChildElement(name);
            param.addTextNode("");
        }
    }

    /**
     * 解析SOAP响应
     *
     * @param soapResponse SOAP响应消息
     * @return 解析后的响应对象
     * @throws Exception
     */
    private IcePendingTaskResponse parseSoapResponse(SOAPMessage soapResponse) throws Exception
    {
        SOAPBody body = soapResponse.getSOAPBody();
        String responseStr = body.getTextContent();

        // 尝试解析JSON响应
        try
        {
            JSONObject jsonObject = JSON.parseObject(responseStr);
            IcePendingTaskResponse response = new IcePendingTaskResponse();
            response.setRet(jsonObject.getInteger("ret"));
            response.setMsg(jsonObject.getString("msg"));
            response.setData(jsonObject.getString("data"));
            response.setTime(jsonObject.getString("time"));
            response.setSuccess(jsonObject.getInteger("ret") != null && jsonObject.getInteger("ret") == 0);
            return response;
        }
        catch (Exception e)
        {
            log.warn("无法解析JSON响应，尝试其他解析方式", e);
            // 如果不是JSON格式，创建一个通用响应
            IcePendingTaskResponse response = new IcePendingTaskResponse();
            response.setRet(0);
            response.setMsg("success");
            response.setData(responseStr);
            response.setSuccess(true);
            return response;
        }
    }
}