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

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
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.adam.dto.vo.AdamUserInfoVo;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.base.SqlMapping;
import com.liquidnet.service.base.constant.MQConst;
import com.liquidnet.service.feign.adam.api.FeignAdamBaseClient;
import com.liquidnet.service.sweet.config.WechatMpConfigure;
import com.liquidnet.service.sweet.entity.SweetAppletUser;
import com.liquidnet.service.sweet.mapper.SweetAppletUserMapper;
import com.liquidnet.service.sweet.utils.QueueUtils;
import com.liquidnet.service.sweet.utils.WechatUsersRedisUtils;
import com.liquidnet.service.sweet.vo.SweetAppletUsersVo;
import com.liquidnet.service.sweet.vo.SweetWechatUsersVo;
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 UserDataServiceImpl {
    @Autowired
    WechatMpConfigure wechatMpConfigure;

    @Autowired
    private WechatUsersRedisUtils redisUtils;
    @Autowired
    private QueueUtils queueUtils;

    @Autowired
    SweetAppletUserMapper sweetAppletUserMapper;

    @Autowired
    private FeignAdamBaseClient feignAdamBaseClient;

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

        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;
                    }
                    SweetWechatUsersVo sweetWechatUsers = redisUtils.getSweetWechatUsers(wxMpUser.getUnionId(), type);
                    if (null == sweetWechatUsers) {
                        SweetWechatUsersVo sweetWechatUsersVo = SweetWechatUsersVo.getNew();
                        sweetWechatUsersVo.setWechatUserId(IDGenerator.nextSnowId());
                        sweetWechatUsersVo.setType(type);
                        sweetWechatUsersVo.setOpenId(wxMpUser.getOpenId());
                        sweetWechatUsersVo.setUnionId(wxMpUser.getUnionId());
                        sweetWechatUsersVo.setNickname(wxMpUser.getNickname());
                        sweetWechatUsersVo.setSexDesc(wxMpUser.getSexDesc());
                        sweetWechatUsersVo.setSex(wxMpUser.getSex());
                        sweetWechatUsersVo.setHeadImgUrl(wxMpUser.getHeadImgUrl());
                        sweetWechatUsersVo.setLanguage(wxMpUser.getLanguage());
                        sweetWechatUsersVo.setCountry(wxMpUser.getCountry());
                        sweetWechatUsersVo.setProvince(wxMpUser.getProvince());
                        sweetWechatUsersVo.setCity(wxMpUser.getCity());
                        sweetWechatUsersVo.setSubscribeTime(DateUtil.ofEpochMilli(wxMpUser.getSubscribeTime()));
                        sweetWechatUsersVo.setSubscribeScene(wxMpUser.getSubscribeScene());

                        LinkedList<String> sqls = CollectionUtil.linkedListString();
                        LinkedList<Object[]> sqlsDataA = CollectionUtil.linkedListObjectArr();
                        sqls.add(SqlMapping.get("sweet_wechat_users.insert"));
                        sqlsDataA.add(new Object[]{
                                sweetWechatUsersVo.getWechatUserId(), type, sweetWechatUsersVo.getOpenId(), sweetWechatUsersVo.getUnionId(), sweetWechatUsersVo.getNickname(),
                                sweetWechatUsersVo.getSexDesc(), sweetWechatUsersVo.getSex(), sweetWechatUsersVo.getHeadImgUrl(), sweetWechatUsersVo.getLanguage(),
                                sweetWechatUsersVo.getCountry(), sweetWechatUsersVo.getProvince(), sweetWechatUsersVo.getCity(),
                                sweetWechatUsersVo.getSubscribeTime(), sweetWechatUsersVo.getSubscribeScene()
                        });
                        queueUtils.sendMsgByRedis(MQConst.SweetQueue.SWEET_WECHAT_USER_INSERT.getKey(),
                                SqlMapping.gets(sqls, sqlsDataA));
                        // 入缓存
                        redisUtils.setSweetWechatUsers(sweetWechatUsersVo);
                    }

                } catch (Exception e) {
                    log.info("forException：openId：[{}]", openId);
                }
            }
            log.info("nextOpenidSuccess：[{}] ", nextOpenid);
        } while (!nextOpenid.isEmpty());
        log.info("同步微信用户完成");
    }

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

        SweetWechatUsersVo sweetWechatUsers = redisUtils.getSweetWechatUsers(wxMpUser.getUnionId(), type);
        if (null == sweetWechatUsers) {
            SweetWechatUsersVo sweetWechatUsersVo = SweetWechatUsersVo.getNew();
            sweetWechatUsersVo.setWechatUserId(IDGenerator.nextSnowId());
            sweetWechatUsersVo.setType(type);
            sweetWechatUsersVo.setOpenId(wxMpUser.getOpenId());
            sweetWechatUsersVo.setUnionId(wxMpUser.getUnionId());
            sweetWechatUsersVo.setNickname(wxMpUser.getNickname());
            sweetWechatUsersVo.setSexDesc(wxMpUser.getSexDesc());
            sweetWechatUsersVo.setSex(wxMpUser.getSex());
            sweetWechatUsersVo.setHeadImgUrl(wxMpUser.getHeadImgUrl());
            sweetWechatUsersVo.setLanguage(wxMpUser.getLanguage());
            sweetWechatUsersVo.setCountry(wxMpUser.getCountry());
            sweetWechatUsersVo.setProvince(wxMpUser.getProvince());
            sweetWechatUsersVo.setCity(wxMpUser.getCity());
            sweetWechatUsersVo.setSubscribeTime(DateUtil.ofEpochMilli(wxMpUser.getSubscribeTime()));
            sweetWechatUsersVo.setSubscribeScene(wxMpUser.getSubscribeScene());

            LinkedList<String> sqls = CollectionUtil.linkedListString();
            LinkedList<Object[]> sqlsDataA = CollectionUtil.linkedListObjectArr();
            sqls.add(SqlMapping.get("sweet_wechat_users.insert"));
            sqlsDataA.add(new Object[]{
                    sweetWechatUsersVo.getWechatUserId(), type, sweetWechatUsersVo.getOpenId(), sweetWechatUsersVo.getUnionId(), sweetWechatUsersVo.getNickname(),
                    sweetWechatUsersVo.getSexDesc(), sweetWechatUsersVo.getSex(), sweetWechatUsersVo.getHeadImgUrl(), sweetWechatUsersVo.getLanguage(),
                    sweetWechatUsersVo.getCountry(), sweetWechatUsersVo.getProvince(), sweetWechatUsersVo.getCity(),
                    sweetWechatUsersVo.getSubscribeTime(), sweetWechatUsersVo.getSubscribeScene()
            });
            queueUtils.sendMsgByRedis(MQConst.SweetQueue.SWEET_WECHAT_USER_INSERT.getKey(),
                    SqlMapping.gets(sqls, sqlsDataA));
            // 入缓存
            redisUtils.setSweetWechatUsers(sweetWechatUsersVo);
        }
    }

    public void appletUser() {
        int size = 1000;
        // 获取总记录数
        Integer count = sweetAppletUserMapper.selectCount(Wrappers.lambdaQuery(SweetAppletUser.class));
        // 总page
        int countPage = (int) Math.ceil(count / size);
        for (int page = 0; page < countPage; page++) {
            List<SweetAppletUser> sweetAppletUsers = sweetAppletUserMapper.selectList(Wrappers.lambdaQuery(SweetAppletUser.class).last("limit " + (page * size) + "," + ((page + 1) * size)));
            for (SweetAppletUser info : sweetAppletUsers) {
                SweetAppletUsersVo oldInfo = redisUtils.getSweetAppletUsers(info.getGetPurePhoneNumber());
                if (null == oldInfo) {
                    ResponseDto<AdamUserInfoVo> userInfoVo = feignAdamBaseClient.registerByMobile(info.getGetPurePhoneNumber());
                    AdamUserInfoVo userInfoVoData = userInfoVo.getData();
                    String userId = userInfoVoData.getUid();

                    LinkedList<String> sqlsA = CollectionUtil.linkedListString();
                    LinkedList<Object[]> sqlsDataA = CollectionUtil.linkedListObjectArr();
                    sqlsA.add(SqlMapping.get("sweet_applet_users.insert"));
                    sqlsDataA.add(new Object[]{
                            info.getUserId(), userId, info.getOpenId(), info.getUnionId(), info.getGetPhoneNumber(), info.getGetPurePhoneNumber(), info.getGetCountryCode(), info.getType()
                    });
                    queueUtils.sendMsgByRedis(MQConst.SweetQueue.SWEET_WECHAT_USER_INSERT.getKey(),
                            SqlMapping.gets(sqlsA, sqlsDataA));

                    SweetAppletUsersVo sweetAppletUsersVo = SweetAppletUsersVo.getNew();
                    sweetAppletUsersVo.setAppletUserId(info.getUserId());
                    sweetAppletUsersVo.setUserId(userId);
                    sweetAppletUsersVo.setOpenId(info.getOpenId());
                    sweetAppletUsersVo.setUnionId(info.getUnionId());
                    sweetAppletUsersVo.setPhoneNumber(info.getGetPhoneNumber());
                    sweetAppletUsersVo.setPurePhoneNumber(info.getGetPurePhoneNumber());
                    sweetAppletUsersVo.setCountryCode(info.getGetCountryCode());
                    sweetAppletUsersVo.setType(info.getType());
                    redisUtils.setSweetAppletUsers(sweetAppletUsersVo);
                }
            }
        }
    }
}
