package com.kym.service.miniapp.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.miniapp.MpRelation;
import com.kym.entity.miniapp.User;
import com.kym.mapper.miniapp.MpRelationMapper;
import com.kym.service.miniapp.MpRelationService;
import com.kym.service.miniapp.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);
            if (CommUtil.isEmptyOrNull(wxUserList.getNextOpenid())) {
                return;
            } else {
                nextOpenid = wxUserList.getNextOpenid();
            }
            // 通过unionid获取公众号openid
            var mpRelationList = new ArrayList<MpRelation>();
            List<WxMpUser> mpUserList = wxMpService.getUserService().userInfoList(wxUserList.getOpenids());
            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()));
        }
    }

    /**
     * 绑定公众号用户
     *
     * @param mpOpenid
     */
    public void bindMpUser(String mpOpenid) {
        try {
            WxMpUser mpUser = wxMpService.getUserService().userInfo(mpOpenid, lang);
            MpRelation 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());
                updateById(mpRelation);
            }
            replace(mpRelation);
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
    }

}
