package com.kym.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kym.common.utils.CommUtil;
import com.kym.common.utils.IDGenerator;
import com.kym.entity.MpRelation;
import com.kym.entity.User;
import com.kym.mapper.MpRelationMapper;
import com.kym.service.MpRelationService;
import com.kym.service.UserService;
import com.kym.service.mybatisplus.MyBaseServiceImpl;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.chanjar.weixin.mp.bean.result.WxMpUserList;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 微信公众号用户关联表 服务实现类
 * </p>
 *
 * @author skyline
 * @since 2024-07-31
 */
@Service
public class MpRelationServiceImpl extends MyBaseServiceImpl<MpRelationMapper, MpRelation> implements MpRelationService {

    private static final String lang = "zh_CN";
    private final UserService userService;
    private final WxMpService wxMpService;


    public MpRelationServiceImpl(UserService userService, WxMpService wxMpService) {
        this.userService = userService;
        this.wxMpService = wxMpService;
    }

    /**
     * 批量处理（全量）公众号用户关联小程序用户
     *
     * @throws WxErrorException
     */
    @Override
    @Transactional
    public void batchBindMpUser() throws WxErrorException {
        String nextOpenid = null;
        for (; ; ) {
            // 获取公众号所有关注者列表
            WxMpUserList wxUserList = wxMpService.getUserService().userList(nextOpenid);
            var openids = wxUserList.getOpenids();
            if (CommUtil.isEmptyOrNull(openids)) {
                break;
            }

            // 通过unionid获取公众号openid
            var mpRelationList = new ArrayList<MpRelation>();
            List<WxMpUser> mpUserList = wxMpService.getUserService().userInfoList(openids);
            mpUserList.forEach(mpUser -> {
                MpRelation mpRelation = new MpRelation()
                        .setMpOpenid(mpUser.getOpenId())
                        .setUnionid(mpUser.getUnionId())
                        .setSubscribe(mpUser.getSubscribe())
                        .setSubscribeScene(mpUser.getSubscribeScene());
                mpRelationList.add(mpRelation);
            });

            // 批量replace
            replaceBatch(mpRelationList);

            var mpRelations = mpRelationList.stream().filter(mpRelation -> CommUtil.isNotEmptyAndNull(mpRelation.getUnionid())).toList();
            var userList = userService.lambdaQuery().in(User::getUnionid, mpRelations.stream().map(MpRelation::getUnionid).toList()).list();
            userList.forEach(user -> mpRelations.stream().filter(mpRelation -> mpRelation.getUnionid().equals(user.getUnionid())).forEach(mpRelation -> {
                mpRelation.setOpenid(user.getOpenid());
                mpRelation.setUserId(user.getId());
            }));
            updateBatchByQueryWrapper(mpRelations, mpRelation ->
                    new QueryWrapper<MpRelation>().eq("unionid", mpRelation.getUnionid()));

            // 检查是否有下一页
            if (CommUtil.isEmptyOrNull(wxUserList.getNextOpenid())) {
                break;
            }
            nextOpenid = wxUserList.getNextOpenid();
        }
        // 同步关注状态到 t_user（兜底事件丢失场景）
        var allRelations = lambdaQuery().isNotNull(MpRelation::getUserId).list();
        if (!CommUtil.isEmptyOrNull(allRelations)) {
            var subscribedIds = allRelations.stream()
                    .filter(MpRelation::getSubscribe)
                    .map(MpRelation::getUserId).toList();
            if (!subscribedIds.isEmpty()) {
                userService.lambdaUpdate().set(User::getFollowOfficialAccount, 1)
                        .in(User::getId, subscribedIds).update();
            }
            var unsubscribedIds = allRelations.stream()
                    .filter(r -> !r.getSubscribe())
                    .map(MpRelation::getUserId).toList();
            if (!unsubscribedIds.isEmpty()) {
                userService.lambdaUpdate().set(User::getFollowOfficialAccount, 2)
                        .in(User::getId, unsubscribedIds).update();
            }
        }
    }

    /**
     * 绑定公众号用户
     *
     * @param mpOpenid
     */
    public void bindMpUser(String mpOpenid) {
        try {
            WxMpUser mpUser = wxMpService.getUserService().userInfo(mpOpenid, lang);

            // 查询已存在的记录，避免重复插入
            MpRelation mpRelation = lambdaQuery().eq(MpRelation::getMpOpenid, mpOpenid).one();
            if (mpRelation == null) {
                mpRelation = new MpRelation();
                mpRelation.setId(IDGenerator.INS().nextId());
            }
            mpRelation
                    .setMpOpenid(mpUser.getOpenId())
                    .setUnionid(mpUser.getUnionId())
                    .setSubscribe(mpUser.getSubscribe())
                    .setSubscribeScene(mpUser.getSubscribeScene());

            var user = userService.getOne(new QueryWrapper<User>().eq("unionid", mpRelation.getUnionid()));
            if (user != null) {
                mpRelation.setOpenid(user.getOpenid());
                mpRelation.setUserId(user.getId());
            }
            saveOrUpdate(mpRelation);
            // 同步关注状态到 t_user
            if (user != null) {
                userService.lambdaUpdate()
                        .set(User::getFollowOfficialAccount, 1)
                        .eq(User::getId, user.getId())
                        .update();
            }
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 取消关注公众号
     *
     * @param mpOpenid 公众号openid
     */
    public void unbindMpUser(String mpOpenid) {
        var mpRelation = lambdaQuery().eq(MpRelation::getMpOpenid, mpOpenid).one();
        if (mpRelation != null) {
            lambdaUpdate().set(MpRelation::getSubscribe, false)
                    .eq(MpRelation::getMpOpenid, mpOpenid).update();
            if (mpRelation.getUserId() != null) {
                userService.lambdaUpdate()
                        .set(User::getFollowOfficialAccount, 2)
                        .eq(User::getId, mpRelation.getUserId())
                        .update();
            }
        }
    }

}
