package com.weaver.seconddev.chapanda.feishu.esb;

import com.weaver.common.base.entity.result.WeaResult;
import com.weaver.esb.api.rpc.EsbServerlessRpcRemoteInterface;
import com.weaver.seconddev.chapanda.feishu.util.Esb2FeishuOpenIdUtil;
import com.weaver.seconddev.chapanda.feishu.util.Esb2FeishuSendMessageUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;

@Service("Esb2FeishuSendMessageCardAction")
public class Esb2FeishuSendMessageCardAction implements EsbServerlessRpcRemoteInterface {
    private final static Logger log = LoggerFactory.getLogger(Esb2FeishuSendMessageCardAction.class);

    @Autowired
    Esb2FeishuSendMessageUtil esb2FeishuSendMessageUtil;

    @Autowired
    Esb2FeishuOpenIdUtil esb2FeishuOpenIdUtil;

    @Override
    public WeaResult<Map<String, Object>> execute(Map<String, Object> params) {

//        String feishuHost = "https://open.feishu.cn";
//        String tokenUrl = "/open-apis/auth/v3/tenant_access_token/internal";
//        String feishuUrl = "/open-apis/im/v1/messages?receive_id_type=open_id";
//        String app_id = "cli_a8d0ee6b667dd00e";
//        String app_secret = "UjShC4eY7vCgHsQvFWZZleVdCqSEWGD0";
//        String template_id = "AAqIMF4quXR02" ;
//        String template_version_name = "1.0.1";
//        String receiveId = "ou_8ff7816cfa8cda57643cac2a06fbdc7e";

        String templateId = (String) params.get("templateId");
        String templateVersionName = (String) params.get("templateVersionName");
        String receiveId = (String) params.get("receiveId");
        log.error("templateId:{}",templateId);
        log.error("templateVersionName:{}",templateVersionName);
        log.error("receiveId:{}",receiveId);

        if(StringUtils.isBlank(templateId)){
            return WeaResult.fail(500,"templateId is null");
        }

        if(StringUtils.isBlank(templateVersionName)){
            return WeaResult.fail(500,"templateVersionName is null");
        }

        if(StringUtils.isBlank(receiveId)){
            return WeaResult.fail(500,"1. is null");
        }

        String openId = esb2FeishuOpenIdUtil.queryFeishuOpenId(receiveId);
        if(StringUtils.isBlank(openId)){
            return WeaResult.fail(500,"openId is null");
        }

        Map<String, Object> dataMap = esb2FeishuSendMessageUtil.senCardMessage(templateId,templateVersionName,openId,params);
        String chat_id = (String) dataMap.get("chat_id");
        String message_id = (String) dataMap.get("message_id");

        Map<String, Object> actionMap = new HashMap<String, Object>();
        actionMap.put("code",200);
        actionMap.put("msg","成功");
        actionMap.put("chat_id",chat_id);
        actionMap.put("message_id",message_id);
        return WeaResult.success(actionMap);
    }

}
