/*
 * Author: wangjian
 * 生成ServiceImpl
 */
package com.tofly.base.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.base.entity.Menu;
import com.tofly.base.entity.MenuBatch;
import com.tofly.base.mapper.MenuMapper;
import com.tofly.base.service.MenuService;
import com.tofly.common.core.util.StringUtil;
import com.tofly.common.core.util.io.ExcelUtil;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.common.oauth.util.SecurityUtils;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 菜单表
 *
 * @author admin
 * @date Thu Oct 10 00:00:00 CST 2019
 */
@Service("menuService")
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {



    @Override
    public List<Menu> getMenuListByRole(Long roleId) {
        return baseMapper.getMenuListByRole(roleId);
    }

    @Override
    public List<Menu> getMenuListByUser(String platform) {

        return baseMapper.getMenuListByUser(SecurityUtils.getUserId(),platform);
    }

    @Override
    @Transactional
    public String removeMenuByIds(List<Long> list) {
        List<Long> listcopy=new ArrayList<>();
        listcopy.addAll(list);
        //校验菜单，从子级一步步进行校验
        List<Menu> menus = (List<Menu>) this.listByIds(list);
        List<Long> newList=new ArrayList();
        for(Menu menu:menus){
            //校验父级ID是否存在在ID中
            if(list.contains(menu.getParentId())){
                newList.add(menu.getParentId());
            }
        }
        list.removeAll(newList);
        StringBuffer sb=new StringBuffer();
        //先清除子级菜单
        for(Long id:list){
            //查询是否存在子菜单
            List<Menu> menuList=this.list(Wrappers.<Menu>lambdaQuery()
                    .eq(Menu::getParentId,id));
            if(menuList.size()>0){

                sb.append("id:").append(id).append(",对应子级菜单还存在").append(menuList.size())
                        .append("条数据;");
            }
        }
        if(StringUtil.isEmpty(sb.toString())){
            this.removeByIds(list);
            if(newList.size()>0){
                return removeMenuByIds(newList);
            }else{
                return null;
            }
        }else{
            return null;
        }
    }

    @Override
    @SneakyThrows
    @Transactional
    public String uploadBatchMenu(MultipartFile file) {
        if(file==null){
            throw new ToflyDeniedException("上传文件为空");
        }

        InputStream inputStream = file.getInputStream();
        ExcelUtil menuExcel=new ExcelUtil(MenuBatch.class);
        List<MenuBatch> listMenu= menuExcel.importExcel(inputStream);
        List<Menu> listAllMenu=this.list();
        Map<String, Menu> collect = listAllMenu.stream().collect(Collectors.toMap(Menu::getName, m ->m, (k1,k2)->k1));
        StringBuffer sb=new StringBuffer();
        List<String> collect1 = listMenu.stream().filter(k -> collect.get(k.getName()) != null)
                .map(MenuBatch::getName).collect(Collectors.toList());
        if(collect1.size()>0){
            throw new ToflyDeniedException("数据库已经存在菜单名称，不能导入"+ JSONArray.toJSONString(collect1));
        }

        listMenu.sort((m1,m2)->m1.getParentName().compareTo(m2.getParentName()));
        listMenu.stream().forEach(menuBatch -> {
            if(menuBatch.getParentId()==null && !StringUtil.isEmpty(menuBatch.getParentName())){
                menuBatch.setParentId(collect.get(menuBatch.getParentName()).getId());
            }
            this.save(menuBatch);
            collect.put(menuBatch.getName(),menuBatch);
        });
        return "成功导入"+listMenu.size()+"条数据";
    }


}
