package com.seer.teach.mp.api;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.seer.teach.mp.api.resp.WxOAuth2AccessTokenDTO;
import com.seer.teach.mp.convert.WxOAuth2AccessTokenConvert;
import com.seer.teach.mp.entity.MpDealerApplicationsEntity;
import com.seer.teach.mp.factory.MpServiceFactory;
import com.seer.teach.mp.service.IMpDealerApplicationsService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
public class WechatOfficialAccountApiImpl implements WechatOfficialAccountApi{

    @Autowired
    private MpServiceFactory mpServiceFactory;

    @Autowired
    private IMpDealerApplicationsService mpDealerApplicationsService;

    @Override
    public WxOAuth2AccessTokenDTO getUserWxOAuth2AccessToken(String appId, String code) {
        WxMpService mpService = mpServiceFactory.getMpService(appId);
        try {
            WxOAuth2AccessToken wxOAuth2AccessToken = mpService.getOAuth2Service().getAccessToken(code);
            String openId = wxOAuth2AccessToken.getOpenId();
            log.info("获取用户OpenId：{}",openId);
            return WxOAuth2AccessTokenConvert.INSTANCE.wxOAuth2AccessToken2DTO(wxOAuth2AccessToken);
        } catch (WxErrorException e) {
            log.error("获取用户openId失败",e);
            return null;
        }

    }

    @Override
    public void initMpAccountCache() {
        mpServiceFactory.init();
    }

    @Override
    public Integer getDealerApplicationsApplyStatusByUserId(Integer userId) {
        MpDealerApplicationsEntity dealerApplicationsEntity = mpDealerApplicationsService.getOne(new LambdaQueryWrapper<>(MpDealerApplicationsEntity.class)
                .eq(MpDealerApplicationsEntity::getApplicantUserId, userId));
        if (dealerApplicationsEntity != null) {
            return dealerApplicationsEntity.getStatus();
        }
        return null;
    }
}