package com.xjrsoft.module.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.xjrsoft.module.system.dto.AddXjrMenuGroupDto;
import com.xjrsoft.module.system.dto.XjrMenuGroupMenuListDto;
import com.xjrsoft.module.system.entity.XjrMenuGroup;
import com.xjrsoft.module.system.entity.XjrMenuGroupSet;
import com.xjrsoft.module.system.mapper.XjrMenuGroupMapper;
import com.xjrsoft.module.system.mapper.XjrMenuGroupSetMapper;
import com.xjrsoft.module.system.service.IXjrMenuGroupSetService;
import com.xjrsoft.module.system.vo.XjrMenuGroupMenuListVo;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
* @title: 功能分类设置
* @Author dzx
* @Date: 2024-08-09
* @Version 1.0
*/
@Service
@AllArgsConstructor
public class XjrMenuGroupSetServiceImpl extends MPJBaseServiceImpl<XjrMenuGroupSetMapper, XjrMenuGroupSet> implements IXjrMenuGroupSetService {
    private final XjrMenuGroupSetMapper setMapper;

    private final XjrMenuGroupMapper groupMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean add(XjrMenuGroupSet xjrMenuGroupSet) {
        setMapper.insert(xjrMenuGroupSet);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean update(XjrMenuGroupSet xjrMenuGroupSet) {
        setMapper.updateById(xjrMenuGroupSet);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delete(List<Long> ids) {
        setMapper.deleteBatchIds(ids);
        groupMapper.delete(Wrappers.lambdaQuery(XjrMenuGroup.class).in(XjrMenuGroup::getXjrMenuGroupSetId, ids));

        return true;
    }

    @Override
    public List<XjrMenuGroupMenuListVo> getMenuList(XjrMenuGroupMenuListDto dto) {
        return groupMapper.getMenuList(dto);
    }

    @Override
    public Boolean setMenu(AddXjrMenuGroupDto dto) {
        groupMapper.delete(
                new QueryWrapper<XjrMenuGroup>().lambda()
                        .eq(XjrMenuGroup::getXjrMenuGroupSetId, dto.getXjrMenuGroupSetId())
        );
        for (Long xjrMenuId : dto.getXjrMenuIds()) {
            groupMapper.insert(
                    new XjrMenuGroup(){{
                        setCreateDate(new Date());
                        setXjrMenuId(xjrMenuId);
                        setXjrMenuGroupSetId(dto.getXjrMenuGroupSetId());
                    }}
            );
        }
        return true;
    }

    @Override
    public List<XjrMenuGroup> getXjrMenuGroupMenu() {
        return groupMapper.selectList(new QueryWrapper<XjrMenuGroup>());
    }
}
