package com.playlet.web.service.app.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.playlet.common.utils.StringUtils;
import com.playlet.common.utils.http.HttpUtils;
import com.playlet.system.domain.PlayletPublicUser;
import com.playlet.system.service.IPlayletPublicUserService;
import com.playlet.web.service.WxService;
import com.playlet.web.service.app.PlayletPublicUserAppService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class PlayletPublicUserAppServiceImpl implements PlayletPublicUserAppService {

    private final IPlayletPublicUserService iPlayletPublicUserService;

    private final WxService wxService;

    @Override
    public PlayletPublicUser addPublicUser(PlayletPublicUser publicUser) {
        iPlayletPublicUserService.insertPlayletPublicUser(publicUser);
        return publicUser;
    }

    @Override
    public PlayletPublicUser findByUnionIdAndPublicId(PlayletPublicUser publicUser) {
        List<PlayletPublicUser> list =iPlayletPublicUserService.lambdaQuery()
                .eq(PlayletPublicUser::getPublicId, publicUser.getPublicId())
                .eq(PlayletPublicUser::getUnionId, publicUser.getUnionId())
                .list();
        if(CollectionUtils.isNotEmpty(list)){
            // 判断用户是否关注公众号
            if(StringUtils.isNotEmpty(list.get(0).getOpenId())){
                String accessToken = wxService.getAccessToken();
                String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken + "&openid=" + list.get(0).getOpenId() + "&lang=zh_CN";
                log.info("调用微信获取用户信息,入参url:{}", url);
                String result = HttpUtils.sendGet(url);
                log.info("调用微信获取用户信息,响应内容:{}", result);
                // 是否关注公众号
                String watchPublic = JSONObject.parseObject(result).getString("subscribe");
                if(!watchPublic.equals(list.get(0).getWatchPublic())){
                    list.get(0).setWatchPublic(watchPublic);
                    // 将状态更新到表中
                    iPlayletPublicUserService.updateById(list.get(0));
                }
            }
            return list.get(0);
        }
        return null;
    }

}
