package com.huimv.manage.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huimv.manage.sys.entity.Group;
import com.huimv.manage.sys.entity.GroupMenu;
import com.huimv.manage.sys.mapper.GroupMapper;
import com.huimv.manage.sys.mapper.GroupMenuMapper;
import com.huimv.manage.sys.service.IGroupService;
import com.huimv.manage.common.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author astupidcoder
 * @since 2021-09-09
 */
@Service
public class GroupServiceImpl extends ServiceImpl<GroupMapper, Group> implements IGroupService {
    @Autowired
    private GroupMapper groupMapper;
    @Autowired
    private GroupMenuMapper groupMenuMapper;


    @Override
    public Result updateGroup(@RequestBody Group group) {
        try {
            groupMapper.updateById(group);
            return new Result(10000,"修改成功",true);
        }catch (Exception e){
            return new Result(10001,"修改失败",false);
        }
    }

    @Override
    @Transactional
    public Result removeGroup(Integer groupId) {
        try {
            Group group = this.groupMapper.selectById(groupId);
            if (group == null) {
                return new Result(10002,"请选择数据",false);
            }
            // 删除权限组
            this.groupMapper.deleteById(groupId);
            // 删除权限组关联菜单
            QueryWrapper<GroupMenu> groupMenuQueryWrapper = new QueryWrapper<>();
            groupMenuQueryWrapper.eq("group_id",groupId);
            groupMenuMapper.delete(groupMenuQueryWrapper);
            return new Result(10000,"删除成功",true);
        }catch (Exception e){
            return new Result(10001,"删除失败",false);
        }
    }

    @Override
    public  IPage<Group> listGroup(Map map, List<Integer> allChildId) {
        Integer pageNum = (Integer)map.get("pageNum");
        Integer pageSize = (Integer)map.get("pageSize");

        return this.page(new Page<>(pageNum, pageSize),new QueryWrapper<Group>().in("account_id",allChildId).orderByDesc("id"));
    }

    @Override
    public Result addGroup(Group group,Integer userId) {
        try {
            group.setAccountId(userId);
            groupMapper.insert(group);
            return new Result(10000,"添加成功",true);
        }catch (Exception e){
            return new Result(10001,"添加失败",false);
        }
    }
}
