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

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.common.wechat.mp.handler.BaseSubscribeHandler;
import org.dromara.elevator.domain.EElevatorWechatUser;
import org.dromara.elevator.domain.bo.EElevatorWechatUserBo;
import org.dromara.elevator.domain.vo.EElevatorWechatUserVo;
import org.dromara.elevator.service.IEElevatorWechatUserService;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 关注事件处理
 *
 * @author ym
 * @version 1.0.0
 * @date 2024-10-18 10:26
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class SubscribeHandler extends BaseSubscribeHandler {

    private final IEElevatorWechatUserService elevatorWechatUserService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) {
        log.info("微信公众号关注:{},{}", wxMessage, JsonUtils.toJsonString(context));
        try {
            WxMpUser wxMpUser = wxMpService.getUserService().userInfo(wxMessage.getOpenId());
            // 关注事件处理
            EElevatorWechatUserBo bo = new EElevatorWechatUserBo();
            EElevatorWechatUser wechatUser = elevatorWechatUserService.queryByUnionId(wxMpUser.getUnionId());
            bo.setUnionId(wxMpUser.getUnionId());
            bo.setMpOpenId(wxMpUser.getOpenId());
            if (Objects.isNull(bo.getCreateBy())) {
                bo.setCreateDept(1L);
                bo.setCreateBy(1L);
            }
            if (Objects.nonNull(wechatUser)) {
                // 校验已存在用户id 使用账号是否已有关注绑定
                if (Objects.nonNull(wechatUser.getUserId()) && checkExistWechatUserSubscribe(wechatUser, wxMpUser)) {
                    return null;
                }
                bo.setId(wechatUser.getId());
                bo.setMaOpenId(wechatUser.getMaOpenId());
                bo.setUserId(wechatUser.getUserId());
            }
            elevatorWechatUserService.saveOrUpdate(bo);
        } catch (WxErrorException e) {
            log.error("wxMp获取微信用户信息异常:{}", wxMessage, e);
        }

        return null;
    }

    /**
     * 校验已存在的登录过的微信用户
     *
     * @param wechatUser 微信公众用户
     * @param wxMpUser   公众号用户信息
     */
    private Boolean checkExistWechatUserSubscribe(EElevatorWechatUser wechatUser, WxMpUser wxMpUser) {
        // 存在同一账号多人使用情况
        // 根据用户id查询 unionId不同的账号是否优先关注公众号
        EElevatorWechatUserBo existQueryBo = new EElevatorWechatUserBo();
        existQueryBo.setUserId(wechatUser.getUserId());
        List<EElevatorWechatUserVo> wechatUserList = elevatorWechatUserService.queryList(existQueryBo);

        Optional<EElevatorWechatUserVo> wechatUserVoOptional = wechatUserList.stream()
            .filter(item -> !StringUtils.equals(item.getUnionId(), wxMpUser.getUnionId())
                && StringUtils.isNotBlank(item.getMpOpenId())
                && StringUtils.isNotBlank(item.getMaOpenId()))
            .findFirst();
        // true 存在使用过小程序并已有绑定的 外层业务直接跳过
        return wechatUserVoOptional.isPresent();
    }

}
