package com.yunzhi.marketing.common;

import com.alibaba.fastjson.JSONArray;
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;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@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);
    }

    /**
     * 依据手机号获取人员信息
     * @param mobile
     * @return
     * @throws WxErrorException
     */
    public String getUserByPhone(String mobile) throws WxErrorException {
        return wxCpService.getUserService().getUserId(mobile);
    }

    /**
     * 获取人员直播房间列表
     * @param userId
     * @return
     * @throws Exception
     */
    public List<JSONObject> getLivingRoomsOfUser(String userId) throws Exception {
        if (StringUtils.isEmpty(userId)) {
            throw new Exception("未指定用户ID");
        }

        try {
            JSONObject params = new JSONObject();
            params.put("userid", userId);
            params.put("limit", 20);
            JSONObject response = post("/cgi-bin/living/get_user_all_livingid", params);
            JSONArray lst = response.getJSONArray("livingid_list");

            List<JSONObject> rtn = new ArrayList<>();
            if (lst.size() > 0) {
                for (int i = 0; i < lst.size(); i++) {
                    String livingId = lst.get(i).toString();
                    JSONObject res = post("/cgi-bin/living/get_living_info?livingid="+StringUtils.urlEncode(livingId), null);
                    JSONObject liveInfo = res.getJSONObject("living_info");
                    if (null != liveInfo) {
                        liveInfo.put("livingid", livingId);
                        rtn.add(liveInfo);
                    }
                }
            }

            return rtn;
        } 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;
        }
    }

    /**
     * 获取房间信息
     * @param livingId
     * @return
     * @throws Exception
     */
    public JSONObject getLivingInfoById(String livingId) throws Exception {
        if (StringUtils.isEmpty(livingId)) {
            throw new Exception("未指定房间ID");
        }

        try {
            JSONObject res = post("/cgi-bin/living/get_living_info?livingid="+StringUtils.urlEncode(livingId), null);
            JSONObject liveInfo = res.getJSONObject("living_info");
            if (null != liveInfo) {
                liveInfo.put("livingid", livingId);
            }
            return  liveInfo;
        } 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;
        }
    }

    /**
     * 获取直播授权码
     * @param livingid
     * @param openid
     * @return
     * @throws Exception
     */
    public String getLivingCode(String livingid, String openid) throws Exception {
        if (StringUtils.isEmpty(livingid) || StringUtils.isEmpty(openid)) {
            throw new Exception("房间号或者人员openid不能为空");
        }

        try {
            JSONObject params = new JSONObject();
            params.put("livingid", livingid);
            params.put("openid", openid);
            JSONObject response = post("/cgi-bin/living/get_living_code", params);
            return response.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;
        }
    }

    private JSONObject post(String url, JSONObject data) throws WxErrorException {
        String uri = wxCpService.getWxCpConfigStorage().getApiUrl(url);
        String response = wxCpService.post(uri, null != data  ? data.toJSONString() : null);
        return JSONObject.parseObject(response);
    }
}
