package org.dromara.elevator.wechat.ma.handler;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaKefuMessage;
import cn.binarywang.wx.miniapp.bean.WxMaMessage;
import cn.binarywang.wx.miniapp.message.WxMaXmlOutMessage;
import cn.hutool.http.HttpUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.wechat.ma.handler.BaseCustomerHandler;
import org.dromara.elevator.constant.AreaClientEnum;
import org.dromara.elevator.domain.message.AuthBody;
import org.dromara.elevator.domain.message.AuthToken;
import org.dromara.elevator.domain.vo.EElevatorInfoVo;
import org.dromara.elevator.service.IEElevatorInfoService;
import org.dromara.elevator.service.message.AuthTokenService;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Objects;

/**
 * 微信小程序客服消息
 *
 * @author ym
 * @version 1.0.0
 * @date 2024-11-13 15:23
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class CustomerHandler extends BaseCustomerHandler {


    private final AuthTokenService authTokenService;

    private final IEElevatorInfoService elevatorInfoService;

    private static final String MSG_TYPE = "monitor";

    @Override
    public WxMaXmlOutMessage handle(WxMaMessage wxMessage, Map<String, Object> context,
                                    WxMaService service, WxSessionManager sessionManager) {
        String pagePath = wxMessage.getPagePath();
        Map<String, String> paramMap = HttpUtil.decodeParamMap(pagePath, StandardCharsets.UTF_8);
        String elevatorNum = paramMap.get("elevatorNum");
        String msgType = paramMap.get("msgType");

        if (!StringUtils.equals(msgType, MSG_TYPE) || StringUtils.isBlank(elevatorNum)) {
            return null;
        }
        EElevatorInfoVo elevatorInfo = elevatorInfoService.selectByElevatorNum(elevatorNum);
        if (Objects.isNull(elevatorInfo) || Objects.isNull(elevatorInfo.getEleId())
            || StringUtils.isBlank(elevatorInfo.getAreaCode())) {
            return null;
        }
        AreaClientEnum areaClient = AreaClientEnum.getAreaClient(elevatorInfo.getAreaCode());
        if (Objects.isNull(areaClient)) {
            return null;
        }

        AuthBody authBody = new AuthBody();
        authBody.setClientId(areaClient.getClineId());
        authBody.setClientSecret(areaClient.getClientSecret());
        authBody.setRequestUrl(areaClient.getRequestTokenUrl());
        AuthToken tokenInfo = authTokenService.getToken(authBody);
        try {
            service.getMsgService().sendKefuMsg(WxMaKefuMessage.newLinkBuilder()
                .title(elevatorInfo.getElevatorName() + "电梯监控")
                .url(String.format(areaClient.getMonitorUrl(), tokenInfo.getObj().getAccessToken(), elevatorInfo.getEleId()))
                .thumbUrl("http://111.172.230.93:9000/elevator/2024/11/13/c9b72b9fa57e4bc5b49af5b19ed45628.png")
                .toUser(wxMessage.getFromUser()).build());
        } catch (WxErrorException e) {
            log.error("小程序监控客服消息异常: {}, {}", elevatorNum, wxMessage, e);
        }
        return null;
    }
}
