package com.yida.data.school.index.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.yida.data.common.core.entity.constant.YidaAppConstant;
import com.yida.data.common.core.entity.school.EduSchoolMenu;
import com.yida.data.common.core.entity.system.EduYidaApp;
import com.yida.data.school.vo.index.MenuInfoVO;
import java.util.List;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class AppUtil {

    /**
     * 订阅号保存菜单
     */
    public static void subscribeSaveMenu(String accountId, EduYidaApp app, List<MenuInfoVO> menuList) {
        StringBuilder url = new StringBuilder();
        url.append(app.getAppUrl())
            .append(YidaAppConstant.SUBSCRIBE_SAVE_MENU);
        JSONArray buttons = new JSONArray();
        for (MenuInfoVO menu : menuList) {
            JSONObject button = new JSONObject() {{
                set("type", EduSchoolMenu.CONTENT_TYPE.get(menu.getContentType()));
                set("name", menu.getName());
                set("url", menu.getUrl());
            }};
            if (menu.getContentType() == 2) {
                button.set("param1", menu.getColId());
                button.set("param2", "909");
            }
            if (CollUtil.isNotEmpty(menu.getChildren())) {
                JSONArray subButtons = new JSONArray();
                for (MenuInfoVO child : menu.getChildren()) {
                    JSONObject subButton = new JSONObject() {{
                        set("type", EduSchoolMenu.CONTENT_TYPE.get(child.getContentType()));
                        set("name", child.getName());
                        set("url", child.getUrl());
                    }};
                    if (child.getContentType() == 2) {
                        button.set("param1", child.getColId());
                        button.set("param2", "909");
                    }
                    subButtons.put(subButton);
                }
                button.set("subButton", subButtons);
            }
            buttons.put(button);
        }
        JSONObject body = new JSONObject() {{
            set("accountId", accountId);
            set("buttons", buttons);
        }};

        String res = HttpUtil.post(url.toString(), body.toString());
        log.info("保存易达菜单,res:[{}],param:[{}]", res, body);
    }
}
