package org.jeecg.modules.okki.wechatgroup.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhipu.oapi.ClientV4;
import com.zhipu.oapi.Constants;
import com.zhipu.oapi.service.v4.model.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.util.*;
import org.jeecg.modules.okki.site.dto.WeChatMsgDto;
import org.jeecg.modules.okki.site.service.IFeiShuCommonService;
import org.jeecg.modules.okki.site.service.IFeiShuMsgService;
import org.jeecg.modules.okki.utils.HttpClientUtils;
import org.jeecg.modules.okki.wechatgroup.dto.WechatGroupMsgRespDto;
import org.jeecg.modules.okki.wechatgroup.entity.OkkiShopWechatGroupMsg;
import org.jeecg.modules.okki.wechatgroup.mapper.OkkiShopWechatGroupMsgMapper;
import org.jeecg.modules.okki.wechatgroup.service.IOkkiShopWechatGroupMsgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Description: okki_shop_wechat_group_msg
 * @Author: jeecg-boot
 * @Date: 2024-09-09
 * @Version: V1.0
 */
@Service
@Slf4j
public class OkkiShopWechatGroupMsgServiceImpl extends ServiceImpl<OkkiShopWechatGroupMsgMapper, OkkiShopWechatGroupMsg> implements IOkkiShopWechatGroupMsgService {

    @Value("${OKKI.BASE_URL}")
    private String URL;

    @Value("${OKKI.CLIENT_SECRET}")
    private String CLIENT_SECRET;

    @Resource
    private OkkiShopWechatGroupMsgMapper okkiShopWechatGroupMsgMapper;

    @Autowired
    private IFeiShuCommonService feiShuCommonService;

    @Autowired
    private IFeiShuMsgService feiShuMsgService;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 获取站点信息
     *
     * @param siteId
     * @return
     */
    @Override
    public void getSiteWechatMsgMaxSeq(String siteId) {
        List<OkkiShopWechatGroupMsg> shopWechatGroupMsgs = okkiShopWechatGroupMsgMapper.getSiteWechatMsgList(siteId);
        log.info("一共有：{}个站点,需要企业微信群消息", shopWechatGroupMsgs.size());
        for (int i = 0; i < shopWechatGroupMsgs.size(); i++) {
            int finalI = i;
            ThreadPoolUtil.execute(() -> {
                OkkiShopWechatGroupMsg okkiShopWechatGroupMsg = shopWechatGroupMsgs.get(finalI);
                int maxSeq = okkiShopWechatGroupMsg.getSeq() == 0 ? 1 : okkiShopWechatGroupMsg.getSeq();
                log.info("开始处理第{}个，站点ID为：{},seq为：{},企业微信群消息", finalI + 1, okkiShopWechatGroupMsg.getSiteId(), maxSeq);
                saveWechatGroupMsg(String.valueOf(okkiShopWechatGroupMsg.getSiteId()), maxSeq);
            });
        }
    }

    /**
     * 保存企业微信群消息
     *
     * @param siteId
     * @param minSeq
     */
    public void saveWechatGroupMsg(String siteId, Integer minSeq) {
        List<OkkiShopWechatGroupMsg> wechatGroupMsgList = sendWechatGroupMsgRequest(siteId, minSeq);
        List<OkkiShopWechatGroupMsg> shopWechatGroupMsgs = new ArrayList<>();
        if (!CollectionUtils.isEmpty(wechatGroupMsgList)) {
            wechatGroupMsgList.forEach(c -> {
                OkkiShopWechatGroupMsg shopWechatGroupMsg = new OkkiShopWechatGroupMsg();
                shopWechatGroupMsg.setMsgId(c.getMsgId());
                shopWechatGroupMsg.setRoomId(c.getRoomId());
                shopWechatGroupMsg.setSeq(c.getSeq());
                shopWechatGroupMsg.setAction(c.getAction());
                shopWechatGroupMsg.setFromId(StringUtils.isNotBlank(c.getFrom()) ? c.getFrom() : "");
                shopWechatGroupMsg.setTolist(c.getTolist());
                shopWechatGroupMsg.setMsgType(c.getMsgType());
                shopWechatGroupMsg.setMsgTime(c.getMsgTime());
                shopWechatGroupMsg.setContent(c.getContent());
                shopWechatGroupMsg.setClientId(c.getClientId());
                shopWechatGroupMsg.setSiteId(c.getSiteId());
                shopWechatGroupMsg.setCreateTime(c.getCreateTime());
                shopWechatGroupMsg.setUpdateTime(c.getUpdateTime());
                shopWechatGroupMsgs.add(shopWechatGroupMsg);
            });
            this.saveBatch(shopWechatGroupMsgs);

            //获取下一页数据
            OkkiShopWechatGroupMsg lastWechatGroupMsg = shopWechatGroupMsgs.get(shopWechatGroupMsgs.size() - 1);
            saveWechatGroupMsg(siteId, lastWechatGroupMsg.getSeq());
        }
    }

    /**
     * 发送获取企业微信群消息请求
     *
     * @param siteId
     */
    public List<OkkiShopWechatGroupMsg> sendWechatGroupMsgRequest(String siteId, Integer minSeq) {
        List<OkkiShopWechatGroupMsg> okkiShopWechatGroupMsgs = new ArrayList<>();
        // 请求okki平台接口
        Map<String, String> query = new TreeMap<>();
        query.put("sign_method", "hmac-md5");
        query.put("timestamp", String.valueOf(System.currentTimeMillis()));
        query.put("site_id", String.valueOf(siteId));
        query.put("method", "query_wechat_group_msg");

        Map<String, Object> postData = new HashMap<>();
        postData.put("page", 1);
        postData.put("page_size", 100);
        postData.put("min_seq", minSeq);
        try {
            String queryStr = HttpClientUtils.buildQueryString(query);
            String body = HttpClientUtils.toJsonString(postData);
            String signStr = queryStr + body;
            query.put("signature", HttpClientUtils.generateHmacMD5(signStr, CLIENT_SECRET));
            String okkiUrl = URL + "?" + HttpClientUtils.buildQueryString(query);
            log.info("url:" + okkiUrl + ",body:" + body);
            String msgResult = HttpClientUtils.doPost(okkiUrl, body);
            // {"code":0,"msg":"success","now":"2024-09-09 09:42:28","data":[]}
            WechatGroupMsgRespDto wechatGroupMsgRespDto = JSONObject.parseObject(msgResult, WechatGroupMsgRespDto.class);
//            log.info("wechatGroupMsgRespDto:{}",FastJsonUtil.toJSONString(wechatGroupMsgRespDto));
            if (wechatGroupMsgRespDto.getCode() != 0) {
                throw new RuntimeException(wechatGroupMsgRespDto.getMsg());
            }
            okkiShopWechatGroupMsgs = wechatGroupMsgRespDto.getData();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return okkiShopWechatGroupMsgs;
    }

    /**
     * 根据英文名称分组
     *
     * @return
     */
    public Map<String, List<JSONObject>> getSiteGroupByEnName(String excludePhaseName) {
        Map<String, List<JSONObject>> kfTeamSheetListMap = feiShuCommonService.getKfTeamSheet();
        Map<String, List<JSONObject>> kfListMap = new HashMap<>();
        for (Map.Entry<String, List<JSONObject>> entry : kfTeamSheetListMap.entrySet()) {
            String key = entry.getKey();
            List<JSONObject> jsonObjectList = entry.getValue();
            List<JSONObject> resultList = new ArrayList<>();
            for (JSONObject jsonObject : jsonObjectList) {
                JSONArray kfNameArr = jsonObject.getJSONArray("建站顾问");
                String kfZhName = kfNameArr.getJSONObject(0).getString("name");
                String kfUserId = kfNameArr.getJSONObject(0).getString("id");

                JSONObject kfEnNameObj = jsonObject.getJSONObject("英文名称");
                String kfEnName = kfEnNameObj.getJSONArray("value").getJSONObject(0).getString("text");

                JSONArray companyNameArr = jsonObject.getJSONArray("公司名称");
                String companyName = companyNameArr.getJSONObject(0).getString("text");

                String websitePhase = jsonObject.getString("服务阶段");

                int websiteId = jsonObject.getDouble("网站ID").intValue();

                String feiShuGroupId = "";
                if (jsonObject.containsKey("群名称")) {
                    JSONArray feiShuGroupArr = jsonObject.getJSONArray("群名称");
                    feiShuGroupId = feiShuGroupArr.getJSONObject(0).getString("id");
                }
                JSONObject newObject = new JSONObject();
                newObject.put("siteId", websiteId);
                newObject.put("companyName", companyName);
                newObject.put("zhName", kfZhName);
                newObject.put("enName", kfEnName);
                newObject.put("userId", kfUserId);
                newObject.put("feiShuGroupId", feiShuGroupId);
                newObject.put("websitePhase", websitePhase);
                if (StringUtils.isBlank(excludePhaseName) || !excludePhaseName.equals(websitePhase)) {
                    resultList.add(newObject);
                }
            }
            kfListMap.put(key, resultList);
        }
        log.info("kfListMap:{}", FastJsonUtil.toJSONString(kfListMap));
        return kfListMap;
    }

    /**
     * 获取客户全部站点
     *
     * @return
     */
    public List<JSONObject> getKfAllSiteList() {
        Map<String, List<JSONObject>> kfGroupData = getSiteGroupByEnName(null);
        List<JSONObject> siteList = new ArrayList<>();
        for (Map.Entry<String, List<JSONObject>> entry : kfGroupData.entrySet()) {
            List<JSONObject> jsonObjectList = entry.getValue();
            for (JSONObject jsonObject : jsonObjectList) {
                String websiteId = jsonObject.getString("siteId");
                String companyName = jsonObject.getString("companyName");
                String kfZhName = jsonObject.getString("zhName");
                String kfEnName = jsonObject.getString("enName");
                String kfUserId = jsonObject.getString("userId");
                String feiShuGroupId = jsonObject.getString("feiShuGroupId");

                JSONObject newObject = new JSONObject();
                newObject.put("siteId", websiteId);
                newObject.put("companyName", companyName);
                newObject.put("zhName", kfZhName);
                newObject.put("enName", kfEnName);
                newObject.put("userId", kfUserId);
                newObject.put("feiShuGroupId", feiShuGroupId);
                siteList.add(newObject);
            }
        }
        log.info("siteList:{}", FastJsonUtil.toJSONString(siteList));
        return siteList;
    }

    /**
     * 获取客户全部站点
     *
     * @return
     */
    public List<JSONObject> getKfSitePhaseByName(String excludePhaseName) {
        Map<String, List<JSONObject>> kfGroupData = getSiteGroupByEnName(excludePhaseName);
        List<JSONObject> siteList = new ArrayList<>();
        for (Map.Entry<String, List<JSONObject>> entry : kfGroupData.entrySet()) {
            List<JSONObject> jsonObjectList = entry.getValue();
            for (JSONObject jsonObject : jsonObjectList) {
                String websiteId = jsonObject.getString("siteId");
                String companyName = jsonObject.getString("companyName");
                String kfZhName = jsonObject.getString("zhName");
                String kfEnName = jsonObject.getString("enName");
                String kfUserId = jsonObject.getString("userId");
                String feiShuGroupId = jsonObject.getString("feiShuGroupId");

                JSONObject newObject = new JSONObject();
                newObject.put("siteId", websiteId);
                newObject.put("companyName", companyName);
                newObject.put("zhName", kfZhName);
                newObject.put("enName", kfEnName);
                newObject.put("userId", kfUserId);
                newObject.put("feiShuGroupId", feiShuGroupId);
                siteList.add(newObject);
            }
        }
        log.info("siteList:{}", FastJsonUtil.toJSONString(siteList));
        return siteList;
    }

    /**
     * 获取站点未回复的群消息
     *
     * @param siteId
     * @return
     */
    @Override
    public void getWechatNoReplySiteByDays(String siteId, Integer days) {
        log.info("-------- getWechatNoReplySiteByDays ------- ：siteId：{}，days：{}", siteId, days);
        List<OkkiShopWechatGroupMsg> wechatNoReplySiteList = okkiShopWechatGroupMsgMapper.getWechatNoReplySiteByDays(siteId, days);
        log.info("一共有：{}个站点,超过 {}天没有回复企业微信群消息", wechatNoReplySiteList.size(), days);
//        log.info("wechatNoReplySiteList:{}", FastJsonUtil.toJSONString(wechatNoReplySiteList));

        List<JSONObject> allSiteList = getKfSitePhaseByName("营销推广");
        sendFeiShuRemindMsg(allSiteList, wechatNoReplySiteList, days, null);
    }

    /**
     * 获取客户发送消息未回复的站点
     *
     * @param siteId
     * @param type
     */
    @Override
    public void getNoReplyCustomerMsgByHours(String siteId, Integer days, String type) {
        log.info("-------- getNoReplyCustomerMsgByHours ------- ：siteId：{}，days：{}，type：{}", siteId, days, type);
        double hours = 4;
        // 工作时间
        if ("workingHour".equals(type)) {
            hours = 0.5;
        }

        // 下班时间
        if ("afterHour".equals(type)) {
            hours = 2;
        }

        // 非工作时间
        if ("restDay".equals(type)) {
            hours = 4;
        }

        List<String> enNames = feiShuCommonService.getFeiShuEnNameByTeamSheet();
        enNames.add("Lily1");
        enNames.add("Jane2");
//        log.info("enNames:{}", enNames);

        List<OkkiShopWechatGroupMsg> wechatNoReplySiteList = okkiShopWechatGroupMsgMapper.getWechatNoReplySiteByHours(siteId, days, hours, enNames);
        log.info("一共有：{}个站点,超过 {}小时没有回复企业微信群消息", wechatNoReplySiteList.size(), hours);
//        log.info("wechatNoReplySiteList:{}", FastJsonUtil.toJSONString(wechatNoReplySiteList));

        List<JSONObject> allSiteList = getKfSitePhaseByName(null);
        sendFeiShuRemindMsg(allSiteList, wechatNoReplySiteList, null, hours);
    }

    /**
     * 发送飞书提醒消息
     *
     * @param wechatNoReplySiteList
     * @param hours
     */
    private void sendFeiShuRemindMsg(List<JSONObject> allSiteList, List<OkkiShopWechatGroupMsg> wechatNoReplySiteList, Integer days, Double hours) {
//        log.info("allSiteMapBySiteId:{}", FastJsonUtil.toJSONString(allSiteMapBySiteId));
        Map<Integer, JSONObject> allSiteMapBySiteId = new HashMap<>();
        for (JSONObject jsonObject : allSiteList) {
            allSiteMapBySiteId.put(jsonObject.getInteger("siteId"), jsonObject);
        }
        for (int i = 0; i < wechatNoReplySiteList.size(); i++) {
            int finalI = i;
            ThreadPoolUtil.execute(() -> {
                OkkiShopWechatGroupMsg okkiShopWechatGroupMsg = wechatNoReplySiteList.get(finalI);
                if (allSiteMapBySiteId.containsKey(okkiShopWechatGroupMsg.getSiteId())) {
                    JSONObject jsonObject = allSiteMapBySiteId.get(okkiShopWechatGroupMsg.getSiteId());

                    String currentSiteId = okkiShopWechatGroupMsg.getSiteId().toString();
                    String companyName = jsonObject.getString("companyName");
                    String zhName = jsonObject.getString("zhName");
                    String feiShuGroupId = jsonObject.getString("feiShuGroupId");
                    String userId = jsonObject.getString("userId");

                    String isReplyCustomerText = "无需回复";
                    String aiAnswerContent = "";
                    if (hours != null) {
                        aiAnswerContent = getZhiPuAIContent(currentSiteId);
                        log.info("aiAnswerContent:{}", aiAnswerContent);
                        isReplyCustomerText = aiAnswerContent.contains("无需回复") ? "无需回复" : "需要回复";
                    }

                    log.info("开始处理 第{}个 通知客服发送告警提醒,站点ID：{},公司名称：{},客服：{},feiShuGroupId：{}",
                            finalI + 1, currentSiteId, companyName, zhName, feiShuGroupId);

                    String msgType = "remindCustomerMsg";
                    String exceptionMsg = "";
                    String msgText = "";
                    if (days != null) {
//                    msgText = "我们注意到【" + companyName + "】的企业微信群已连续" + days + "天没有消息更新。最后一条消息的记录时间为" + DateUtil.format(okkiShopWechatGroupMsg.getMsgTime(), DatePattern.CHINESE_DATE_TIME_FORMATTER) + "。为了确保我们服务的高效性，请大家保持微信群内消息的畅通。特别是当收到客户提问或寻求帮助时，请务必及时回应，以提升我们的服务质量和效率。感谢配合！";
                        exceptionMsg = "已连续" + days + "天没有消息更新";
                    }

                    if (hours != null) {
                        String hourStr = hours + "小时";
                        if (hours == 0.5) {
                            hourStr = "30分钟";
                        }
//                    msgText = "我们注意到【" + companyName + "】的企业微信群中，客户发送的消息已超过" + hourStr + "未得到回复。最后一条消息的记录时间为" + DateUtil.format(okkiShopWechatGroupMsg.getMsgTime(), DatePattern.CHINESE_DATE_TIME_FORMATTER) + "。请及时回复客户消息，以确保服务的及时性和质量！";
                        exceptionMsg = "未回复客户消息超过" + hourStr;
                    }

                    StringBuilder sb = new StringBuilder();
                    sb.append("<b>Production：###OKKI建站企微群异常通知</b> ");
                    sb.append("\n");
                    sb.append("<b>企业名称：</b> ").append(companyName);
                    sb.append("\n");
                    sb.append("<b>Client Id：</b> ").append(okkiShopWechatGroupMsg.getClientId());
                    sb.append("\n");
                    sb.append("<b>异常类型：</b> ").append(exceptionMsg);
                    sb.append("\n");
                    sb.append("<b>商家套餐：</b> ").append(okkiShopWechatGroupMsg.getTcName());
                    sb.append("\n");
                    sb.append("<b>服务顾问：</b> ").append(zhName);
                    sb.append("\n");

                    String content = "请看企微群消息";
                    if ("text".equals(okkiShopWechatGroupMsg.getMsgType())) {
                        content = okkiShopWechatGroupMsg.getContent();
                    }
                    sb.append("<b>最后一条消息：</b> ").append(content);
                    sb.append("\n");
                    if ("需要回复".equals(isReplyCustomerText)) {
                        sb.append("<b>分析建议：</b> ").append(aiAnswerContent);
                        sb.append("\n");
                    }
                    msgText = sb.toString();
                    log.info("msgText:{}", msgText);

                    // todo 测试使用
//                    feiShuGroupId = "oc_184b7dbca30579372652f5cef04ae645";
                    if (StringUtils.isNotBlank(feiShuGroupId)) {
                        if (days != null || "需要回复".equals(isReplyCustomerText)) {
                            try {
                                Thread.sleep(1500);
                                feiShuCommonService.sendKfRemindMsg(feiShuGroupId, msgText, userId, msgType);
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }
                }
            });
        }
    }


    /**
     * 检测机器人或用户是否在群中
     */
    @Override
    public void checkBotOrUserIsExistGroup() {
        List<JSONObject> feiShuGroupNoExistList = new ArrayList<>();
        List<JSONObject> allSiteList = getKfAllSiteList();
        for (JSONObject jsonObject : allSiteList) {
            String feiShuGroupId = jsonObject.getString("feiShuGroupId");
            String feiShuGroupName = jsonObject.getString("companyName");
            boolean isExistGroup = feiShuCommonService.checkBotOrUserIsExistGroup(feiShuGroupId);
            if (!isExistGroup) {
                JSONObject feiShuGroupInfoObj = new JSONObject();
                feiShuGroupInfoObj.put("feiShuGroupId", feiShuGroupId);
                feiShuGroupInfoObj.put("feiShuGroupName", feiShuGroupName);
                feiShuGroupNoExistList.add(feiShuGroupInfoObj);
            }
        }
        log.info("不存在“ OK助手” 机器人的群聊有:{}", FastJsonUtil.toJSONString(feiShuGroupNoExistList));
    }

    /**
     * 判断是否为工作日
     *
     * @return
     */
    @Override
    public Map<String, Object> todayCheckWorkDay() {
        Map<String, Object> map = new HashMap<>();
        int isnotwork = 0;
        int daycode = 0;
        String holidayResult = "";
        String today = DateUtil.today();
        String todayKey = "holiday_today:" + today;
        log.info("todayKey:{}", todayKey);
        String todayKeyResult = (String) redisUtil.get(todayKey);
        if (StringUtils.isNotBlank(todayKeyResult)) {
            holidayResult = todayKeyResult;
        } else {
            holidayResult = fetchHolidayInfo(today);
            long seconds = DateUtils.getSecondsUtilTomorrow();
            log.info("截止明日凌晨还有 {} 秒。", seconds);
            redisUtil.set(todayKey, holidayResult, seconds);
        }
        log.info("holidayResult:{}", holidayResult);
        JSONObject jsonObject = JSONObject.parseObject(holidayResult);
        if (jsonObject.getInteger("code") == 200) {
            JSONObject resultObj = jsonObject.getJSONObject("result");
            JSONObject todayObj = resultObj.getJSONArray("list").getJSONObject(0);
            isnotwork = todayObj.getInteger("isnotwork");
            daycode = todayObj.getInteger("daycode");
        }
        map.put("isnotwork", isnotwork);
        map.put("daycode", daycode);
        return map;
    }

    /**
     * 获取holiday接口数据
     *
     * @param date
     * @return
     */
    public String fetchHolidayInfo(String date) {
        String holidayUrl = "https://apis.tianapi.com/jiejiari/index?key=96423e175822df92e809802a567d7d1e&date=[]&type=0";
        String replaceUrl = holidayUrl.replace("[]", date);
        return HttpClientUtil.doGet(replaceUrl);
    }

    /**
     * 获取AI回复
     *
     * @param siteId
     */
    public String getZhiPuAIContent(String siteId) {
        List<String> enNames = feiShuCommonService.getFeiShuEnNameByTeamSheet();
        enNames.add("Lily1");
        enNames.add("Jane2");
        List<OkkiShopWechatGroupMsg> shopWechatGroupMsgList = okkiShopWechatGroupMsgMapper.getLatestWechatMsgList(siteId, enNames);
        shopWechatGroupMsgList.sort(Comparator.comparing(OkkiShopWechatGroupMsg::getMsgTime));
        log.info("shopWechatGroupMsgList:{}", FastJsonUtil.toJSONString(shopWechatGroupMsgList));

        StringBuilder sb = new StringBuilder();
        shopWechatGroupMsgList.forEach(c -> {
            sb.append(c.getFromId()).append(":")
                    .append(c.getContent()).append(",")
                    .append("发送时间：")
                    .append(DateUtil.format(c.getMsgTime(), DatePattern.CHINESE_DATE_TIME_FORMATTER))
                    .append("\n");
        });
        log.info("sb：{}", sb.toString());

        List<ChatMessage> messages = new ArrayList<>();
        ChatMessage systemChatMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), "#角色 作为情感、心理学和社会学领域的专家，你可以通过聊天记录中的语言和情感线索判断是否需要进一步回复。" +
                "如果需要回复，请回答继续回复；否则请回答无需回复；请提供建议为什么需要这样做。");
        messages.add(systemChatMessage);

        String promot = sb.toString();
        ChatMessage userChatMessage = new ChatMessage(ChatMessageRole.USER.value(), promot);
        messages.add(userChatMessage);

        ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
                .model(Constants.ModelChatGLM4)
                .stream(Boolean.FALSE)
                .invokeMethod(Constants.invokeMethod)
                .messages(messages)
                .build();

        ClientV4 client = new ClientV4.Builder("3e1dc0e5cee1a8f0cc7b1fd01e5276c0.ueEh44nuymbAbUle")
                .networkConfig(900, 300, 300, 300, TimeUnit.SECONDS)
                .connectionPool(new okhttp3.ConnectionPool(8, 1, TimeUnit.SECONDS))
                .build();

        ModelApiResponse invokeModelApiResp = client.invokeModelApi(chatCompletionRequest);
        log.info("model output: {}", FastJsonUtil.toJSONString(invokeModelApiResp));

        String answerText = "";
        if (invokeModelApiResp.isSuccess()) {
            List<Choice> choices = invokeModelApiResp.getData().getChoices();
            answerText = choices.get(0).getMessage().getContent().toString();
        }
        log.info("answerText:{}", answerText);
        return answerText;
    }

    /**
     * 根据站点ID获取站点信息
     *
     * @param weChatMsgDto
     * @return
     */
    @Override
    public List<OkkiShopWechatGroupMsg> getSiteWechatMsgBySiteId(WeChatMsgDto weChatMsgDto) {
        QueryWrapper<OkkiShopWechatGroupMsg> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("site_id", weChatMsgDto.getSiteId());
        queryWrapper.last("limit " + weChatMsgDto.getLimit());
        queryWrapper.orderByDesc("msg_time");
        return list(queryWrapper);
    }
}
