package com.crunii.micro.service.sysmgr.jdbc;

import cn.hutool.core.util.ObjectUtil;
import com.crunii.micro.common.dto.Result;
import com.crunii.micro.domain.common.jdbc.BaseJdbcTemplate;
import com.crunii.micro.domain.dto.Worker;
import com.crunii.micro.domain.util.CurrWorkerUtil;
import com.crunii.micro.service.sysmgr.dto.sysmgr.MoreServiceResp;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Repository
public class MoreServiceJdbcDao {

    @Resource(name = "mainJT")
    protected BaseJdbcTemplate jdbcTemplate;

    public Result<List<MoreServiceResp>> query() {
        List<Integer> roleIds = jdbcTemplate.queryForList("select role_id from TSM_WORKER_ROLE where login_id = ?", Integer.class, getWorker().getLoginId());

        Set<String> menuCodes = new HashSet<>();
        for(Integer rId : roleIds){
            menuCodes.addAll(jdbcTemplate.queryForList("select menu_code from TSM_ROLE_MENU where role_id = ?", String.class, rId));
        }

        StringBuilder sql = new StringBuilder("select * from TSM_MENU a where a.state = 1 and a.menu_type = 1 and a.menu_code not in (");
        for(String code : menuCodes){
            sql.append("'").append(code).append("'").append(",");
        }
        sql = new StringBuilder(sql.substring(0, sql.length() - 1));
        sql.append(")");

        List<String> parentCode = new ArrayList<>();
        parentCode.add("1");
        parentCode.addAll(jdbcTemplate.queryForList("select menu_code from TSM_MENU where parent_menu_code = '1'", String.class));
        StringBuilder sql2 = new StringBuilder("select menu_code from TSM_MENU where menu_type = 0 and parent_menu_code in (");
        for(String code : parentCode){
            sql2.append("'").append(code).append("'").append(",");
        }
        sql2 = new StringBuilder(sql2.substring(0, sql2.length() - 1));
        sql2.append(")");
        List<String> catalogueCode = jdbcTemplate.queryForList(sql2.toString(), String.class);
        catalogueCode.remove("1001");

        sql.append("and parent_menu_code in (");
        for(String code : catalogueCode){
            sql.append("'").append(code).append("'").append(",");
        }
        sql = new StringBuilder(sql.substring(0, sql.length() - 1));
        sql.append(")");

        List<MoreServiceResp> menus = jdbcTemplate.queryForBeans(MoreServiceResp.class, sql.toString());
        return new Result(menus);
    }

    private Worker getWorker() {
        Worker worker = CurrWorkerUtil.getCurrWorker();
        if (ObjectUtil.isEmpty(worker)) {
            throw new RuntimeException("获取当前登录用户失败");
        }
        return worker;
    }

}
