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

import com.crunii.micro.common.exception.BusinessException;
import com.crunii.micro.domain.common.jdbc.BaseJdbcTemplate;
import com.crunii.micro.domain.common.jdbc.BaseNPJdbcTemplate;
import com.crunii.micro.domain.entity.main.TsmMenu;
import com.crunii.micro.domain.entity.main.YcqMenuShortcut;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author zjw
 */
@Repository(value = "ycqMenuShortcutJdbcDao")
@Slf4j
public class YcqMenuShortcutJdbcDao {
    @Resource(name = "mainJT")
    protected BaseJdbcTemplate JT;

    @Resource(name = "mainNPJT")
    protected BaseNPJdbcTemplate NPJT;


    private static final String QUERY_CAN_USE_MENU_CODE_SQL = "select menu_code from TSM_ROLE_MENU where role_id in(select twr.role_id from TSM_WORKER_ROLE twr where twr.login_id = ?)";
    private static final String QUERY_MENU_SELECTED = "select menu_code from YCQ_MENU_SHORTCUT where del_flag = 0 and login_id = ? ";

    private static final String QUERY_CAN_USER_MENU_SQL = "select * from TSM_MENU where menu_type != 2 and state = 1 and menu_code in (select menu_code from TSM_ROLE_MENU where role_id in(select twr.role_id from TSM_WORKER_ROLE twr where twr.login_id = ?))";
    private static final String QUERY_MENU_WITHOUT_BUTTON_TYPE = "select * from TSM_MENU where menu_type != 2 and state = 1 ";
    private static final String QUERY_MENU_IS_EXIST = "select count(*) from TSM_MENU where  state = 1 and menu_code = ?";

    private static final String QUERY_SHORTCUT_MENU = "select * from YCQ_MENU_SHORTCUT where del_flag = 0 and login_id = ? ";

    private static final String DELETE_MENU = "update YCQ_MENU_SHORTCUT set del_flag = 1 where login_id = ? and menu_code in('";
    private static final String DELETE_MENU_BY_LOGIN_ID = "update YCQ_MENU_SHORTCUT set del_flag = 1,update_time = ? where login_id = ?";

    private static final String QUERY_IS_EXIST = "select count(*) from YCQ_MENU_SHORTCUT where del_flag = 0 and login_id = ? and menu_code = ?";

    public List<TsmMenu> queryUnselectedMenu(Integer loginId) {
        StringBuilder stringBuilder = new StringBuilder(QUERY_MENU_WITHOUT_BUTTON_TYPE);
        // 查询用户所有有权限的菜单数据
        List<TsmMenu> menuCodeList = JT.queryForBeans(TsmMenu.class, QUERY_CAN_USE_MENU_CODE_SQL, loginId);
        // 如果没有权限的数据，啥都不展示
        if (CollectionUtils.isEmpty(menuCodeList)) {
            return Collections.emptyList();
        }
        // 查询所有添加了快捷服务的数据
        boolean flag;
        List<YcqMenuShortcut> selectMenuCode = JT.queryForBeans(YcqMenuShortcut.class, QUERY_MENU_SELECTED, loginId);
        if (!CollectionUtils.isEmpty(selectMenuCode)) {
//            String collect = selectMenuCode.stream().map(YcqMenuShortcut::getMenuCode).collect(Collectors.joining("','"));
//            stringBuilder.append("and MENU_CODE not in ('").append(collect).append("') ");
            flag = true;
        } else {
            flag = false;
        }
        Set<String> selectedSet = selectMenuCode.stream().map(YcqMenuShortcut::getMenuCode).collect(Collectors.toSet());
        // 有权限且未添加服务的菜单
        List<String> inMenuList = menuCodeList.stream().map(TsmMenu::getMenuCode).filter(item -> {
            if (flag) {
                return !selectedSet.contains(item);
            }
            return true;
        }).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(inMenuList)) {
            String collect = String.join("','", inMenuList);
            stringBuilder.append("and MENU_CODE in ('").append(collect).append("') ");
        }
        String sql = stringBuilder.toString();
        List<TsmMenu> ycqMenuShortcuts = JT.queryForBeans(TsmMenu.class, sql);
        if (CollectionUtils.isEmpty(ycqMenuShortcuts)) {
            log.error("当前登陆人：{}数据异常,sql:{}", loginId, sql);
            throw new BusinessException("数据异常，请联系管理员");
        }
        return ycqMenuShortcuts;
    }

    public List<TsmMenu> querySelectedMenu(Integer loginId) {
        // 查询所有有权限的数据
        List<TsmMenu> menuCodeList = JT.queryForBeans(TsmMenu.class, QUERY_CAN_USER_MENU_SQL, loginId);
        if (CollectionUtils.isEmpty(menuCodeList)){
            return Collections.emptyList();
        }
        StringBuilder sql = new StringBuilder(QUERY_SHORTCUT_MENU);
        String collect1 = menuCodeList.stream().map(TsmMenu::getMenuCode).collect(Collectors.joining("','"));
        sql.append("and menu_code in ('").append(collect1).append("');");
        List<YcqMenuShortcut> ycqMenuShortcuts = JT.queryForBeans(YcqMenuShortcut.class, sql.toString(), loginId);
        if (!CollectionUtils.isEmpty(ycqMenuShortcuts)){
            Set<String> collect = ycqMenuShortcuts.stream().map(YcqMenuShortcut::getMenuCode).collect(Collectors.toSet());
            menuCodeList = menuCodeList.stream().filter(item -> Objects.equals(item.getMenuType(), 0) || collect.contains(item.getMenuCode())).collect(Collectors.toList());
        }
        return menuCodeList;
    }

    public List<TsmMenu> querySelectedMenuWithoutTop(Integer loginId) {
        StringBuilder stringBuilder = new StringBuilder(QUERY_CAN_USER_MENU_SQL);
        stringBuilder.append(" and menu_type != 0");

        List<YcqMenuShortcut> ycqMenuShortcuts = JT.queryForBeans(YcqMenuShortcut.class, QUERY_SHORTCUT_MENU, loginId);
        if (CollectionUtils.isEmpty(ycqMenuShortcuts)){
            return Collections.emptyList();
        }
        Set<String> collect = ycqMenuShortcuts.stream().map(YcqMenuShortcut::getMenuCode).collect(Collectors.toSet());
        String join = String.join("','", collect);
        stringBuilder.append(" and menu_code in ('").append(join).append("')");
        System.out.println(stringBuilder);
        List<TsmMenu> menuCodeList = JT.queryForBeans(TsmMenu.class, stringBuilder.toString(), loginId);
        if (CollectionUtils.isEmpty(menuCodeList)){
            return Collections.emptyList();
        }
        return menuCodeList;
    }

    public Boolean deleteBatch(List<String> menucodeList, Integer loginId) {
        String join = String.join("','", menucodeList);
        String s = DELETE_MENU + join + "');";
        JT.update(s, loginId);
        return true;
    }

    public Boolean deleteByLoginId(Integer loginId) {
        JT.update(DELETE_MENU_BY_LOGIN_ID, new Date(),loginId);
        return true;
    }

    public int queryExist(String menuCode, Integer loginId) {
        return JT.queryForInt(QUERY_IS_EXIST, loginId, menuCode);
    }

    public int exist(String menuCode) {
        return JT.queryForInt(QUERY_MENU_IS_EXIST, menuCode);
    }
}
