package jnpf.certificate.helper;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.handler.codec.http.HttpUtil;
import jnpf.ImRobotApi;
import jnpf.base.ActionResult;
import jnpf.from.*;
import jnpf.util.JsonUtil;
import jnpf.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.HttpGet;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

/**
 * 证照提醒消息发送工具。
 * 参考健康证定时任务的消息结构，实现按用户集合发送提醒。
 */
@Component
@Slf4j
public class NoticeHelper {

    private static final String APP_NAME = "证照管理";
    public static final String MP_ID_CERTIFICATE = "__UNI__C5F3D72";
    public static final String URL_CERTIFICATE = "/pages/license/detail?id=%s&label=健康证";
    public static final String BUTTON_NAME_HANDLER = "去处理";
    private static final String LOGO_URL = "https://jnpf-resource-1304460613.cos.ap-chengdu.myqcloud.com/jnpf-resources/UserAvatar/665ecb69e4b0ae5df114c87a.png";
    private static final int SEND_BATCH_SIZE = 450;

    @Resource
    private ImRobotApi imRobotApi;

    /**
     * 发送机器人提醒消息。
     *
     * @param userIds    接收用户ID集合
     * @param tenantId   租户ID
     * @param title      消息标题
     * @param content    消息内容
     * @param buttonName 跳转按钮名称（可为空）
     * @param url        跳转地址（可为空）
     * @param mpId       小程序ID（可为空）
     */
    public void sendMessage(Collection<String> userIds, String tenantId, String title, String content,
                            String buttonName, String url, String mpId) {
        List<String> targetUserIds = normalizeUserIds(userIds);
        if (CollUtil.isEmpty(targetUserIds) || StrUtil.isBlank(tenantId) || StrUtil.isBlank(title) || StrUtil.isBlank(content)) {
            return;
        }

        SingleSendRobotNoticeForm form = new SingleSendRobotNoticeForm();
        form.setRobotTypeEnum(ImRobotTypeEnum.FTB_XZS);
        form.setTenantId(tenantId);
        if (StrUtil.isNotBlank(mpId)) {
            form.setMessageAttributionRobotMpId(mpId);
        }
        form.setRobotNoticeDataForm(buildNoticeData(title, content, buttonName, url, mpId));

        for (int start = 0; start < targetUserIds.size(); start += SEND_BATCH_SIZE) {
            int end = Math.min(start + SEND_BATCH_SIZE, targetUserIds.size());
            form.setToUserIds(targetUserIds.subList(start, end));
            ActionResult<?> actionResult = imRobotApi.sendSingleRobotNotice(form);
            if (actionResult == null || !Integer.valueOf(200).equals(actionResult.getCode())) {
                log.error("证照提醒消息发送失败，req={},result={}", JSONUtil.toJsonStr(form), JSONUtil.toJsonStr(actionResult));
            }
        }
    }

    /**
     * 构建消息体。
     */
    private SendRobotNoticeDataForm buildNoticeData(String title, String content, String buttonName, String url, String mpId) {
        SendRobotNoticeDataForm noticeData = new SendRobotNoticeDataForm();
        noticeData.setLogo(LOGO_URL);
        noticeData.setAppName(APP_NAME);
        noticeData.setTitle(title);
        noticeData.setContent(content);

        if (StrUtil.isNotBlank(buttonName) && StrUtil.isNotBlank(url) && StrUtil.isNotBlank(mpId)) {
            JumpUrlListModel jumpUrl = new JumpUrlListModel();
            jumpUrl.setDisplayMethodEnum(JumpUrlListModel.DisplayMethodEnum.TRUE);
            jumpUrl.setButtonName(buttonName);
            jumpUrl.setReqMethod(JumpUrlListModel.ReqMethodEnum.GET);
            jumpUrl.setType(1);
            jumpUrl.setUrl(url);
            jumpUrl.setMpId(mpId);
            //fixme 有空改为传参，不这样处理
            if(url.contains("?")){
                jumpUrl.setMiniAppUrl(buildMiniAppUrl(mpId,url));
            }
            LinkedList<JumpUrlListModel> jumpUrlList = new LinkedList<>();
            jumpUrlList.add(jumpUrl);
            noticeData.setJumpUrlList(jumpUrlList);
        }
        return noticeData;
    }

    private String buildUrl(String url) {
        if(!url.contains("?")){
            return url;
        }
        return url.substring(0,url.indexOf("?"));
    }

    private MiniAppUrl buildMiniAppUrl(String mpId,String url) {
        String params = url.substring(url.indexOf("?")+1);
        if(StringUtil.isBlank(params)){
            return null;
        }
        JSONObject mpParam = new JSONObject();
        for (String kv:params.split("&")){
            String [] kvs = kv.split("=");
            if(kvs.length != 2){
                return null;
            }
            mpParam.set(kvs[0],kvs[1]);
        }
        return MiniAppUrl.builder()
                .mpId(mpId)
                .mpPage(buildUrl(url))
                .mpParam(mpParam.toString())
                .build();
    }

    /**
     * 规整接收用户集合：去空、去重、去首尾空格。
     */
    private List<String> normalizeUserIds(Collection<String> userIds) {
        if (CollUtil.isEmpty(userIds)) {
            return new ArrayList<>();
        }
        Set<String> userIdSet = new LinkedHashSet<>();
        for (String userId : userIds) {
            String trimUserId = StrUtil.trim(userId);
            if (StrUtil.isNotBlank(trimUserId)) {
                userIdSet.add(trimUserId);
            }
        }
        return new ArrayList<>(userIdSet);
    }
}
