package com.weaver.seconddev.interfaces.workflow.controller;

import com.alibaba.fastjson.JSONObject;
import com.weaver.common.base.entity.result.WeaResult;
import com.weaver.common.distribution.lock.DistributionLockInterface;
import com.weaver.common.i18n.tool.util.I18nContextUtil;
import com.weaver.custom.configcenter.htsysjcmtConfig;
import com.weaver.ecode.api.rpc.EcodeService;
import com.weaver.emonitor.util.Util;
import com.weaver.framework.rpc.annotation.RpcReference;
import com.weaver.framework.rpc.context.impl.TenantRpcContext;
import com.weaver.openapi.pojo.ApiResult;
import com.weaver.openapi.pojo.auth.params.AccessTokenParam;
import com.weaver.openapi.pojo.auth.params.CodeParam;
import com.weaver.openapi.pojo.auth.res.AccessToken;
import com.weaver.openapi.pojo.auth.res.Code;
import com.weaver.openapi.pojo.message.params.MessageVo;
import com.weaver.openapi.pojo.message.params.vo.MessageEntity;
import com.weaver.openapi.pojo.message.params.vo.MessageReciver;
import com.weaver.openapi.pojo.message.params.vo.MessageSender;
import com.weaver.openapi.service.AuthService;
import com.weaver.openapi.service.MessageService;
import com.weaver.seconddev.interfaces.prop.ConfigProp;
import com.weaver.verupgrade.conn.RecordSet;
import com.weaver.verupgrade.hrm.resource.ResourceComInfo;
import com.weaver.workflow.list.api.rest.publicapi.WflRequestListRest;
import lombok.extern.slf4j.Slf4j;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.commons.lang.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import javax.xml.rpc.ServiceException;
import javax.xml.rpc.encoding.XMLType;
import java.net.URLEncoder;
import java.rmi.RemoteException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@RestController
@RequestMapping({"/papi/secondev/message"})
//@WeaPermission
public class MessageSubscriptionController {

    // api 需要用户会话，e10入口地址访问
    // papi 任何人都可以直接访问 public api，e10入口地址访问
    // sapi 服务内部通信的接口路由前缀 /sapi/secondev，e10入口地址访问不了
    // 二开服务新接口：/api/secondev，/papi/secondev

    @RpcReference(timeout = 10000)
    EcodeService ecodeService;
    @RpcReference(timeout = 2000, group = "workflow")
    WflRequestListRest wflRequestListRest;
    @Autowired
    private DistributionLockInterface distributionLock;
    @Autowired
    private ConfigProp configProp;
    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(MessageSubscriptionController.class);
    @PostMapping("/subscription")
    public WeaResult<String> subscription(@RequestParam Map<String,Object> param, @RequestBody Map<String,Object> params ) throws ServiceException, RemoteException {
        logger.error("MessageSubscriptionController Start "  );
        String jtzhkey = "t6kj9c07jr";
//        String jtzhadmin = configProp.getJtzhadmin();
//        log.error("jtzhkey:"+jtzhkey+" jtzhadmin:"+itzhadmin);

        TenantRpcContext.setTargetTenantKey(jtzhkey);
//        TenantRpcContext.setTargetEmployeeId(jtzhadmin);
        Map<String ,String > map = new HashMap<>();
        RecordSet rs = I18nContextUtil.getBean(RecordSet.class);

        logger.error("params == " + params);
        sendMsg(params);

        logger.error("subscription 推送成功");
        map.put("msg","推送成功");
        return WeaResult.success(map.toString());
    }

    private  void  sendMsg(Map<String,Object> params) throws RemoteException, ServiceException {
        logger.error("sendMsg params " + params);
        String systemId = "SYS006";
        String password = "123456";
        String moudule = "流程待办";
        String messages = "<messages>";
        String content = String.valueOf(params.get("content"));
        String url = String.valueOf(params.get("pcUrl"));
        String mobileurl = String.valueOf(params.get("h5Url"));
//        String pcurl = configProp.getPc_url()+ URLEncoder.encode(url);
//        String msgurl = configProp.getPc_url()+ URLEncoder.encode(mobileurl);
        String pcurl = url;
        String msgurl = mobileurl;
        String m_msgtitle = String.valueOf(params.get("title"));
        String sendid = String.valueOf(params.get("senderId"));

        String receivers = String.valueOf(params.get("receivers")) ;


        logger.error("             receivers:  " + receivers);
        logger.error("             moudule:  " + moudule);
        logger.error("             pcurl:  " + pcurl);
        logger.error("             msgurl:  " + msgurl);
        logger.error("             m_msgtitle:  " + m_msgtitle);
        logger.error("             moudule:  " + moudule);
        logger.error("             sendid:  " + sendid);


        String sendname = "系统管理员";
        String userid = "1";
        ResourceComInfo rc = I18nContextUtil.getBean(ResourceComInfo.class);
        if (sendid != "1") {
            sendname = rc.getLastname(sendid + "");
            userid = rc.getWorkcode(sendid + "");
        }
        String pre = "";
        String msgtt = m_msgtitle;
        if (m_msgtitle.contains("~`~`7")) {
            msgtt = m_msgtitle.substring(m_msgtitle.indexOf("~`~`7") + 6, m_msgtitle.indexOf("`~`8"));
        }
        if ("会议".equals(moudule)) {
            content = content.substring(content.indexOf("~`~`7") + 6, content.indexOf("`~`8")).replaceAll("<br/>", " ");
            msgtt = "您有一个会议即将开始，会议名称：" + msgtt + " " + content;
        }
        if ("通知公告".equals(moudule)) {
            content = content.substring(content.indexOf("~`~`7") + 6, content.indexOf("`~`8")).replaceAll("<br/>", " ");
            msgtt = "您有新的待阅文档：" + msgtt;
        }
        String refurl;
        if ("流程待办".equals(moudule)) {
            refurl = m_msgtitle;
            if (refurl.contains("~`~`7")) {
                refurl = refurl.substring(refurl.indexOf("~`~`7") + 6, refurl.indexOf("`~`8"));
                msgtt = refurl + "：" + msgtt;
            }
        }
        logger.error("             content:  " + content);
        logger.error("             msgtt:  " + msgtt);

        refurl = msgurl;
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String msgtime = df.format(new Date());
        String target = "2";
        String extdata = "";
//            Set<String> useridset = msg.getRecivers();





        // 去除字符串两端的方括号
        String trimmed = receivers.substring(1, receivers.length() - 1);
        // 使用逗号和空格作为分隔符将字符串拆分成多个子字符串
        String[] strArray = trimmed.split(", ");
//        List<String> useridset = Collections.singletonList(String.valueOf(params.get("receivers")));
        List<String> list = new ArrayList<>();
        // 遍历数组，将每个元素添加到 ArrayList 中
        for (String num : strArray) {
            if(StringUtils.isNotEmpty(num)){
                list.add(num);
            }
        }



        Object[] arr = list.toArray();
        for (int i = 0; i < arr.length; i += 100) {
            StringBuilder sb = new StringBuilder();
            for (int j = i; j < i + 100 && j < arr.length; ++j) {
                sb.append(rc.getWorkcode(arr[j] + "") + ",");
            }
            String user = sb.toString().substring(0, sb.length() - 1);

            logger.error("             user:  " + user);
            String msgid = "MsgSYS006" + userid + (new Date()).getTime();
            messages = messages + "<message>";
            messages = messages + "<MSG_ID>" + msgid + "</MSG_ID><PRE_MSG_ID>" + pre + "</PRE_MSG_ID><USER_ID>" + user + "</USER_ID><MSG_TITLE>" + msgtt + "</MSG_TITLE><MSG_CONTENT>" + msgtt + "</MSG_CONTENT><SENDER_NAME>" + sendname + "</SENDER_NAME><REF_URL>" + refurl + "</REF_URL><MSG_TIME>" + msgtime + "</MSG_TIME><TARGET>" + target + "</TARGET><EXT_DATA>" + extdata + "</EXT_DATA>";
            messages = messages + "</message>";
            if (!"流程待办".equals(moudule)) {
                String pctarget = "1";
                pre = msgid;
                msgid = "MsgPCSYS006" + userid + (new Date()).getTime();
                messages = messages + "<message>";
                messages = messages + "<MSG_ID>" + msgid + "</MSG_ID><PRE_MSG_ID>" + pre + "</PRE_MSG_ID><USER_ID>" + user + "</USER_ID><MSG_TITLE>" + msgtt + "</MSG_TITLE><MSG_CONTENT>" + msgtt + "</MSG_CONTENT><SENDER_NAME>" + sendname + "</SENDER_NAME><REF_URL>" + pcurl + "</REF_URL><MSG_TIME>" + msgtime + "</MSG_TIME><TARGET>" + pctarget + "</TARGET><EXT_DATA>" + extdata + "</EXT_DATA>";
                messages = messages + "</message>";
            }
        }
        messages = messages + "</messages>";


        String typeNamespace = "http://message.ht_portal_webservice.com";
//        String endpoint = "https://sappop.htgd.com.cn:50001/XISOAPAdapter/MessageServlet?senderParty=&senderService=BS_HTU_POP&receiverParty=&receiverService=&interface=SI_HTPortalMessage_OUT&interfaceNamespace=http%3A%2F%2Fhengtong.com%2FHTU%2FHTPortalMessage";
        String endpoint = "http://sappod.hengtong.com:50000/XISOAPAdapter/MessageServlet?senderParty=&senderService=BS_HTU&receiverParty=&receiverService=&interface=SI_HTPortalMessage_OUT&interfaceNamespace=http%3A%2F%2Fhengtong.com%2FHTU%2FHTPortalMessage";
        Service service = new Service();
        Call call = (Call) service.createCall();
        call.setTimeout(300000);
        call.setTargetEndpointAddress(endpoint);
        call.setOperationName(new QName(typeNamespace, "message"));
        call.addParameter(new QName(typeNamespace, "systemId"), XMLType.XSD_STRING, ParameterMode.IN);
        call.addParameter(new QName(typeNamespace, "password"), XMLType.XSD_STRING, ParameterMode.IN);
        call.addParameter(new QName(typeNamespace, "moudule"), XMLType.XSD_STRING, ParameterMode.IN);
        call.addParameter(new QName(typeNamespace, "messages"), XMLType.XSD_STRING, ParameterMode.IN);
        call.setReturnClass(String.class);
        call.setReturnQName(new QName(typeNamespace, "messageResponse"));
        call.setUseSOAPAction(true);
        call.setSOAPActionURI("http://sap.com/xi/WebService/soap1.1");
        Hashtable<String, String> headers = (Hashtable) call.getProperty("HTTP-Request-Headers");
        if (headers == null) {
            headers = new Hashtable();
            call.setProperty("HTTP-Request-Headers", headers);
        }
        headers.put("Authorization", configProp.getUrl_password());

        logger.error("             Url_password():  " + configProp.getUrl_password());
        logger.error("             systemId:  " + systemId);
        logger.error("             password:  " + password);
        logger.error("             moudule:  " + moudule);
        logger.error("             messages:  " + messages);

        Object[] val = new Object[] { systemId, password, moudule, messages };
        String obj = (String) call.invoke(val);

        logger.error("             obj:  " + String.valueOf(obj));
        logger.error(String.valueOf("----onMessage--<\n"));
    }

}
