package com.ningdatech.pmapi.sys.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ningdatech.pmapi.AppTests;
import com.ningdatech.pmapi.sys.model.entity.Menu;
import com.ningdatech.pmapi.sys.model.entity.RoleMenu;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.SQLException;
import java.util.List;

/**
 * <p>
 * IMenuServiceTest
 * </p>
 *
 * @author WendyYang
 * @since 11:18 2023/1/29
 */
class IMenuServiceTest extends AppTests {

    @Autowired
    private IMenuService menuService;

    @Test
    public void test() throws SQLException {
        menuService.remove(null);
        List<Entity> menu = Db.use().findAll("nd_menu");
        menu.forEach(System.out::println);
        menu.forEach(w -> {
            Menu bean = w.toBean(Menu.class);
            menuService.save(bean);
        });
    }


    @Autowired
    private IRoleMenuService roleMenuService;

    @Test
    public void initMenu() {
        /*String str = FileUtil.readString("/Users/wendy/Desktop/long_text_2023-02-13-15-28-42.txt", "UTF-8");
        List<JSONObject> obj = JSONUtil.toList(str, JSONObject.class);
        save(obj, 0);*/
        menuService.list().forEach(w -> {
            roleMenuService.save(new RoleMenu(){{
                setRoleId(1L);
                setMenuId(w.getId());
            }});
        });
    }

    public void save(List<JSONObject> objs, long parentId) {
        objs.forEach(w -> {
            Menu menu = new Menu();
            menu.setActiveMenu(w.getStr("activeMenu"));
            menu.setComponent(w.getStr("component"));
            menu.setIcon(w.getStr("icon"));
            menu.setPath(w.getStr("path"));
            menu.setName(w.getStr("path").replace("/", ""));
            menu.setTopMenu(w.getStr("topMenu"));
            menu.setTitle(w.getStr("title"));
            menu.setHidden(w.getBool("hidden"));
            menu.setPid(parentId);
            menu.setRedirect(w.getStr("redirect"));
            menu.setSort(w.getInt("sort"));
            menu.setDataScopeOption("");
            menu.setHasDataScope(false);
            menuService.save(menu);
            List<JSONObject> children = w.getBeanList("children", JSONObject.class);
            if (CollUtil.isNotEmpty(children)) {
                save(children, menu.getId());
            }
        });
    }

}