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.entity.SweetAppletUsers;
import com.liquidnet.service.sweet.entity.SweetWechatUsers;
import com.liquidnet.service.sweet.mapper.SweetAppletUserMapper;
import com.liquidnet.service.sweet.mapper.SweetAppletUsersMapper;
import com.liquidnet.service.sweet.mapper.SweetWechatUsersMapper;
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;

    @Autowired
    private SweetAppletUsersMapper appletUsersMapper;

    @Autowired
    SweetWechatUsersMapper sweetWechatUsersMapper;

    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.getSweetWechatUsersOfOpenId(wxMpUser.getOpenId(), 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));

                        /*SweetWechatUsers sweetWechatUsers1 = new SweetWechatUsers();
                        sweetWechatUsers1.setWechatUserId(sweetWechatUsersVo.getWechatUserId());
                        sweetWechatUsers1.setType(type);
                        sweetWechatUsers1.setOpenId(sweetWechatUsersVo.getOpenId());
                        sweetWechatUsers1.setUnionId(sweetWechatUsersVo.getUnionId());
                        sweetWechatUsers1.setNickname(sweetWechatUsersVo.getNickname());
                        sweetWechatUsers1.setSexDesc(sweetWechatUsersVo.getSexDesc());
                        sweetWechatUsers1.setSex(sweetWechatUsersVo.getSex());
                        sweetWechatUsers1.setHeadImgUrl(sweetWechatUsersVo.getHeadImgUrl());
                        sweetWechatUsers1.setLanguage(sweetWechatUsersVo.getLanguage());
                        sweetWechatUsers1.setCountry(sweetWechatUsersVo.getCountry());
                        sweetWechatUsers1.setProvince(sweetWechatUsersVo.getProvince());
                        sweetWechatUsers1.setCity(sweetWechatUsersVo.getCity());
                        sweetWechatUsers1.setSubscribeTime(sweetWechatUsersVo.getSubscribeTime());
                        sweetWechatUsers1.setSubscribeScene(sweetWechatUsersVo.getSubscribeScene());
                        sweetWechatUsersMapper.insert(sweetWechatUsers1);*/

                        // 入缓存
                        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.getSweetWechatUsersOfOpenId(wxMpUser.getOpenId(), 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));

            /*SweetWechatUsers sweetWechatUsers1 = new SweetWechatUsers();
            sweetWechatUsers1.setWechatUserId(sweetWechatUsersVo.getWechatUserId());
            sweetWechatUsers1.setType(type);
            sweetWechatUsers1.setOpenId(sweetWechatUsersVo.getOpenId());
            sweetWechatUsers1.setUnionId(sweetWechatUsersVo.getUnionId());
            sweetWechatUsers1.setNickname(sweetWechatUsersVo.getNickname());
            sweetWechatUsers1.setSexDesc(sweetWechatUsersVo.getSexDesc());
            sweetWechatUsers1.setSex(sweetWechatUsersVo.getSex());
            sweetWechatUsers1.setHeadImgUrl(sweetWechatUsersVo.getHeadImgUrl());
            sweetWechatUsers1.setLanguage(sweetWechatUsersVo.getLanguage());
            sweetWechatUsers1.setCountry(sweetWechatUsersVo.getCountry());
            sweetWechatUsers1.setProvince(sweetWechatUsersVo.getProvince());
            sweetWechatUsers1.setCity(sweetWechatUsersVo.getCity());
            sweetWechatUsers1.setSubscribeTime(sweetWechatUsersVo.getSubscribeTime());
            sweetWechatUsers1.setSubscribeScene(sweetWechatUsersVo.getSubscribeScene());
            sweetWechatUsersMapper.insert(sweetWechatUsers1);*/

            // 入缓存
            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);
        countPage = countPage + 1;
        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.getSweetAppletUsersOfPhone(info.getGetPurePhoneNumber());
                if (null == oldInfo) {
                    try {
                        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));

                        /*SweetAppletUsers sweetAppletUsers1 = new SweetAppletUsers();
                        sweetAppletUsers1.setAppletUserId(info.getUserId());
                        sweetAppletUsers1.setUserId(userId);
                        sweetAppletUsers1.setOpenId(info.getOpenId());
                        sweetAppletUsers1.setUnionId(info.getUnionId());
                        sweetAppletUsers1.setPhoneNumber(info.getGetPhoneNumber());
                        sweetAppletUsers1.setPurePhoneNumber(info.getGetPurePhoneNumber());
                        sweetAppletUsers1.setCountryCode(info.getGetCountryCode());
                        sweetAppletUsers1.setType(info.getType());
                        appletUsersMapper.insert(sweetAppletUsers1);*/

                        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);
                    } catch (Exception e) {
                        log.error("feignAdamBaseClientException phone:{}, e:{}", info.getGetPurePhoneNumber(), e);
                    }
                }
            }
        }
    }

}
