package co.yixiang.yshop.module.mp.service.handler.cp;

import co.yixiang.yshop.framework.common.util.json.JsonUtils;
import co.yixiang.yshop.module.mp.framework.cp.builder.TextBuilder;
import co.yixiang.yshop.module.mp.framework.cp.config.WxCpConfiguration;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.cp.api.WxCpKfService;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.kf.*;
import me.chanjar.weixin.cp.bean.kf.msg.WxCpKfTextMsg;
import me.chanjar.weixin.cp.bean.message.WxCpXmlMessage;
import me.chanjar.weixin.cp.bean.message.WxCpXmlOutMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

import static co.yixiang.yshop.module.mp.enums.CpKfServiceStateEnum.*;

/**
 * @author pepis
 * @apiNote 用户进入会话事件 消息处理器
 **/
@Component
public class EnterSessionHandler extends AbstractHandler {
    @Resource
    private RedisTemplate redisTemplate;

    public static final String MSG_CURSOR = "kf_msg_cursor";

    @Override
    public WxCpXmlOutMessage handle(WxCpXmlMessage wxMessage, Map<String, Object> context, WxCpService wxCpService, WxSessionManager sessionManager) throws WxErrorException {
        Map<String, Object> allFieldsMap = wxMessage.getAllFieldsMap();
        String token = (String) allFieldsMap.get("Token");
        String openKfId = (String) allFieldsMap.get("OpenKfId");
        WxCpKfService kfService = WxCpConfiguration.getCpService().getKfService();
        logger.info("\nEnterSessionHandler接收到请求消息，内容：{}", JsonUtils.toJsonString(wxMessage));
        String nextCursor = (String) redisTemplate.opsForValue().get(MSG_CURSOR);
        boolean hasMore = true;
        while (hasMore) {
            WxCpKfMsgListResp kfMsgListResp = kfService.syncMsg(nextCursor, token, null, null, openKfId);
            logger.info("\nEnterSessionHandler同步消息，内容：{}", JsonUtils.toJsonString(kfMsgListResp));

            String welcomeCode = wxMessage.getWelcomeCode();

            for (WxCpKfMsgListResp.WxCpKfMsgItem msgItem : kfMsgListResp.getMsgList()) {

                String externalUserId = msgItem.getExternalUserId();
                try {
                    WxCpKfServiceStateResp stateResp = kfService.getServiceState(openKfId, externalUserId);
                    logger.info("stateResp {} {} {} {}", openKfId, externalUserId, welcomeCode, stateResp.getServiceState());
                    if (stateResp.getServiceState().equals(UNTREATED.getValue()) || stateResp.getServiceState().equals(INTELLIGENT.getValue())) {
                        if (StringUtils.isNotBlank(welcomeCode)) {
                            //发送只能客服欢迎语
                            WxCpKfMsgSendRequest sendRequest = new WxCpKfMsgSendRequest();
                            sendRequest.setCode(welcomeCode);
                            sendRequest.setMsgType(WxConsts.XmlMsgType.TEXT);
                            WxCpKfTextMsg msg = new WxCpKfTextMsg();
                            msg.setContent("欢迎咨询,正在为您安排客服人员,请稍候!");
                            sendRequest.setText(msg);
                            WxCpKfMsgSendResp sendResp = kfService.sendMsgOnEvent(sendRequest);
                            logger.info("sendResp errcode {}, errmsg {}", sendResp.getErrcode(), sendResp.getErrmsg());
                        }
                        WxCpKfServiceStateTransResp transResp = kfService.transServiceState(openKfId, externalUserId, IN_THE_LINE.getValue(), null);
                        logger.info("transResp {}", transResp);
                    }
                } catch (Exception e) {
                    logger.error("transServiceState fail {}", e.getMessage(), e);
                }
                Integer msgHasMore = kfMsgListResp.getHasMore();
                hasMore = msgHasMore != null && msgHasMore == 1;
                nextCursor = kfMsgListResp.getNextCursor();
            }
            redisTemplate.opsForValue().set(MSG_CURSOR, nextCursor);
        }
        return new TextBuilder().build(JsonUtils.toJsonString(wxMessage), wxMessage, wxCpService);
    }
}
