package com.cyksj.service.wechat.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.common.util.SpringCtxUtils;
import com.cyksj.mapper.WxAppMapper;
import com.cyksj.model.dto.MiniProgramSession;
import com.cyksj.model.entity.WxApp;
import com.cyksj.service.wechat.MiniProgramOps;
import com.cyksj.service.wechat.WxMpAccountOps;
import com.cyksj.service.wechat.cach.AccountCache;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author chan
 * @date 2021-10-10 下午12:27
 */
@Slf4j
@Service
public class WxMpAccountOpsService implements WxMpAccountOps {

    @Autowired
    private AccountCache ACCOUNT_CACHE;

    private static final MiniProgramOps MINI_PROGRAM_OPS = MiniProgramOps.create();


    @Override
    public String accessToken(String appId) throws Exception {
        if (StringUtils.isBlank(appId)) {
            throw BusinessRuntimeException.getInstance("Empty appId.");
        }

        String accessToken = ACCOUNT_CACHE.getAccessToken(appId);
        log.info("appId[{}] accessToken: {}", appId, accessToken);

        return accessToken;
    }

    @Override
    public String jsTicket(String appId) throws Exception {

        if (StringUtils.isBlank(appId)) {
            throw BusinessRuntimeException.getInstance("Empty appId.");
        }

        String ticket = ACCOUNT_CACHE.getJsTicket(appId);
        log.info("appId[{}] jsTicket: {}", appId, ticket);

        return ticket;
    }
    
    @Override
    public MiniProgramSession miniProgramCode2Session(String appId, String code) throws Exception {

        if (StringUtils.isBlank(appId)) {
            throw BusinessRuntimeException.getInstance("Empty appId.");
        }
        if (StringUtils.isBlank(code)) {
            throw BusinessRuntimeException.getInstance("Empty code.");
        }

        WxAppMapper wxAppMapper = SpringCtxUtils.getBean(WxAppMapper.class);
        LambdaQueryWrapper<WxApp> wxAppLambdaQueryWrapper = new QueryWrapper<WxApp>().lambda();
        wxAppLambdaQueryWrapper.eq(WxApp::getAppId,appId);
        WxApp wxApp = wxAppMapper.selectOne(wxAppLambdaQueryWrapper);

        if (null == wxApp) {
            throw BusinessRuntimeException.getInstance("No appid configured.");
        }
        final String secret = wxApp.getAppSecret();

        MiniProgramSession session = MINI_PROGRAM_OPS.code2session(appId, secret, code);
        log.info("miniProgram[{}]: unionid[{}] / session_key[{}]", appId, session.getUnionid(), session.getSessionKey());

        return session;

    }

}
