package com.yunzhi.marketing.common;

import com.alibaba.fastjson.JSONObject;
import com.yunzhi.marketing.config.WorkConfig;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import me.chanjar.weixin.cp.config.impl.WxCpDefaultConfigImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@EnableConfigurationProperties(WorkConfig.class)
public class WorkWxUtils {
    WxCpServiceImpl wxCpService;

    @Autowired
    public WorkWxUtils(WorkConfig conf) {
        WxCpDefaultConfigImpl config = new WxCpDefaultConfigImpl();
        config.setCorpId(conf.getCorpid());
        config.setCorpSecret(conf.getSecret());
        config.setAgentId(Integer.valueOf(conf.getAgentid()));
//        config.setToken("...");
//        config.setAesKey("...");

        wxCpService = new WxCpServiceImpl();
        wxCpService.setWxCpConfigStorage(config);
    }

    public String getLivingCode(String livingid, String openid) throws Exception {
        if (StringUtils.isEmpty(livingid) || StringUtils.isEmpty(openid)) {
            throw new Exception("房间号或者人员openid不能为空");
        }

        try {
            String url = wxCpService.getWxCpConfigStorage().getApiUrl("/cgi-bin/living/get_living_code");
            JSONObject params = new JSONObject();
            params.put("livingid", livingid);
            params.put("openid", openid);

            String response = wxCpService.post(url, params.toJSONString());
            JSONObject result = JSONObject.parseObject(response);
            return result.getString("living_code");
        } catch (WxErrorException e) {
            if (90601 == e.getError().getErrorCode()) {
                throw new Exception("直播房间不存在");
            } else {
                throw new Exception(String.format("获取直播凭证失败: %s", e.getError().getErrorMsg()));
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
}
