package com.liquidnet.service.sweet.service.impl;

import com.liquidnet.commons.lang.util.CollectionUtil;
import com.liquidnet.commons.lang.util.DateUtil;
import com.liquidnet.commons.lang.util.IDGenerator;
import com.liquidnet.service.base.SqlMapping;
import com.liquidnet.service.base.constant.MQConst;
import com.liquidnet.service.sweet.config.WechatMpConfigure;
import com.liquidnet.service.sweet.entity.SweetWechatUser;
import com.liquidnet.service.sweet.utils.QueueUtils;
import com.liquidnet.service.sweet.utils.RedisDataUtils;
import lombok.extern.slf4j.Slf4j;
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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;

@Slf4j
@Service
public class SweetWechatMpService {
    @Autowired
    WechatMpConfigure wechatMpConfigure;

    @Autowired
    private RedisDataUtils redisDataUtils;
    @Autowired
    private QueueUtils queueUtils;

    public void userInfo() throws WxErrorException {
        WxMpService wxMpService = wechatMpConfigure.getWxMpService();

        String nextOpenid = "";
        do {
            WxMpUserList wxMpUserList = wxMpService.getUserService().userList(nextOpenid);
            int count = wxMpUserList.getCount();
            long total = wxMpUserList.getTotal();
            List<String> openids = wxMpUserList.getOpenids();
            nextOpenid = wxMpUserList.getNextOpenid();
            log.info("count：[{}] ", count);
            log.info("total：[{}] ", total);
//            log.info("openids：[{}] ", openids);
            log.info("nextOpenid：[{}] ", nextOpenid);

            for (String openId : openids) {
                try {
                    WxMpUser wxMpUser = wxMpService.getUserService().userInfo(openId);
                    if (!wxMpUser.getSubscribe()) {
                        log.info("getSubscribeFalse：openId：[{}]", openId);
                        continue;
                    }
                    SweetWechatUser userInfo = redisDataUtils.getSweetWechatUser(wxMpUser.getUnionId());
                    if (null == userInfo) {
                        SweetWechatUser sweetWechatUser = SweetWechatUser.getNew();
                        sweetWechatUser.setOpenId(wxMpUser.getOpenId());
                        sweetWechatUser.setUnionId(wxMpUser.getUnionId());
                        sweetWechatUser.setNickname(wxMpUser.getNickname());
                        sweetWechatUser.setSexDesc(wxMpUser.getSexDesc());
                        sweetWechatUser.setSex(wxMpUser.getSex());
                        sweetWechatUser.setHeadImgUrl(wxMpUser.getHeadImgUrl());
                        sweetWechatUser.setLanguage(wxMpUser.getLanguage());
                        sweetWechatUser.setCountry(wxMpUser.getCountry());
                        sweetWechatUser.setProvince(wxMpUser.getProvince());
                        sweetWechatUser.setCity(wxMpUser.getCity());
                        sweetWechatUser.setSubscribeTime(DateUtil.ofEpochMilli(wxMpUser.getSubscribeTime()));
                        sweetWechatUser.setSubscribeScene(wxMpUser.getSubscribeScene());
                        sweetWechatUser.setUserId(IDGenerator.nextSnowId());
                        LinkedList<String> sqls = CollectionUtil.linkedListString();
                        LinkedList<Object[]> sqlsDataA = CollectionUtil.linkedListObjectArr();
                        sqls.add(SqlMapping.get("sweet_user.insert"));
                        sqlsDataA.add(new Object[]{
                                sweetWechatUser.getUserId(), sweetWechatUser.getOpenId(), sweetWechatUser.getUnionId(), sweetWechatUser.getNickname(),
                                sweetWechatUser.getSexDesc(), sweetWechatUser.getSex(), sweetWechatUser.getHeadImgUrl(), sweetWechatUser.getLanguage(),
                                sweetWechatUser.getCountry(), sweetWechatUser.getProvince(), sweetWechatUser.getCity(),
                                sweetWechatUser.getSubscribeTime(), sweetWechatUser.getSubscribeScene()
                        });
                        queueUtils.sendMsgByRedis(MQConst.SweetQueue.SWEET_USER_INSERT_DRAW.getKey(),
                                SqlMapping.gets(sqls, sqlsDataA));
                        // 入缓存
                        redisDataUtils.setSweetWechatUser(sweetWechatUser);
                    }
                } catch (Exception e) {
                    log.info("forException：openId：[{}]", openId);
                }
            }
            log.info("nextOpenidSuccess：[{}] ", nextOpenid);
        } while (!nextOpenid.isEmpty());
        log.info("同步微信用户完成");
    }

    public void getUser(String openId) throws WxErrorException {
        WxMpService wxMpService = wechatMpConfigure.getWxMpService();
        WxMpUser wxMpUser = wxMpService.getUserService().userInfo(openId);
        log.info("openId：[{}],wxMpUsers：[{}]", openId, wxMpUser);

        SweetWechatUser userInfo = redisDataUtils.getSweetWechatUser(wxMpUser.getUnionId());
        if (null == userInfo) {
            SweetWechatUser sweetWechatUser = SweetWechatUser.getNew();
            sweetWechatUser.setOpenId(wxMpUser.getOpenId());
            sweetWechatUser.setUnionId(wxMpUser.getUnionId());
            sweetWechatUser.setNickname(wxMpUser.getNickname());
            sweetWechatUser.setSexDesc(wxMpUser.getSexDesc());
            sweetWechatUser.setSex(wxMpUser.getSex());
            sweetWechatUser.setHeadImgUrl(wxMpUser.getHeadImgUrl());
            sweetWechatUser.setLanguage(wxMpUser.getLanguage());
            sweetWechatUser.setCountry(wxMpUser.getCountry());
            sweetWechatUser.setProvince(wxMpUser.getProvince());
            sweetWechatUser.setCity(wxMpUser.getCity());
            sweetWechatUser.setSubscribeTime(DateUtil.ofEpochMilli(wxMpUser.getSubscribeTime()));
            sweetWechatUser.setSubscribeScene(wxMpUser.getSubscribeScene());
            sweetWechatUser.setUserId(IDGenerator.nextSnowId());
            LinkedList<String> sqls = CollectionUtil.linkedListString();
            LinkedList<Object[]> sqlsDataA = CollectionUtil.linkedListObjectArr();
            sqls.add(SqlMapping.get("sweet_user.insert"));
            sqlsDataA.add(new Object[]{
                    sweetWechatUser.getUserId(), sweetWechatUser.getOpenId(), sweetWechatUser.getUnionId(), sweetWechatUser.getNickname(),
                    sweetWechatUser.getSexDesc(), sweetWechatUser.getSex(), sweetWechatUser.getHeadImgUrl(), sweetWechatUser.getLanguage(),
                    sweetWechatUser.getCountry(), sweetWechatUser.getProvince(), sweetWechatUser.getCity(),
                    sweetWechatUser.getSubscribeTime(), sweetWechatUser.getSubscribeScene()
            });
            queueUtils.sendMsgByRedis(MQConst.SweetQueue.SWEET_USER_INSERT_DRAW.getKey(),
                    SqlMapping.gets(sqls, sqlsDataA));
            // 入缓存
            redisDataUtils.setSweetWechatUser(sweetWechatUser);
        }
    }
}
