package com.tuoheng.admin.service.menu;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tuoheng.admin.entity.*;
import com.tuoheng.admin.enums.ClientEnum;
import com.tuoheng.admin.mapper.*;
import com.tuoheng.admin.query.MenuQuery;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.admin.vo.menu.MenuListVo;
import com.tuoheng.admin.vo.menu.MenuindexVo;
import com.tuoheng.common.core.common.BaseServiceImpl;
import com.tuoheng.common.core.utils.DateUtils;
import com.tuoheng.common.core.utils.JsonResult;
import com.tuoheng.common.core.utils.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author ChengWang
 * @Date 2022/12/16
 */
@Service
public class MenuServiceImpl implements IMenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OpPermissionsMapper permissionsMapper;

    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    /**
     * 获取菜单列表
     *
     * @param menuQuery
     * @return
     */
    @Override
    public JsonResult getList(MenuQuery menuQuery) {
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();

        MenuindexVo vo = new MenuindexVo();
        QueryWrapper<OpPermissions> queryWrapper1 = new QueryWrapper<>();

        // 查询条件
        if (1 == menuQuery.getMenuType()) {
            queryWrapper.eq("client_id", ClientEnum.ADMIN.getDescription());
            queryWrapper1.eq("client_id", ClientEnum.ADMIN.getDescription());
        } else {
            queryWrapper.eq("client_id", ClientEnum.MP.getDescription());
            queryWrapper1.eq("client_id", ClientEnum.MP.getDescription());
        }
        if (!StringUtils.isEmpty(menuQuery.getName())) {
            queryWrapper1.like("name", menuQuery.getName());
        }
        queryWrapper1.eq("mark", 1);
        //返回权限
        List<OpPermissions> opPermissions = permissionsMapper.selectList(queryWrapper1);
        vo.setPermissionList(opPermissions);
        // 菜单名称
        if (!StringUtils.isEmpty(menuQuery.getName())) {
            queryWrapper.like("name", menuQuery.getName());
        }
        queryWrapper.eq("mark", 1);
        queryWrapper.orderByAsc("sort");

        // 查询分页数据
        List<Menu> menuList = menuMapper.selectList(queryWrapper);
        List<MenuListVo> menuListVoList = new ArrayList<>();
        if (!menuList.isEmpty()) {
            menuList.forEach(item -> {
                MenuListVo menuListVo = new MenuListVo();
                BeanUtils.copyProperties(item, menuListVo);
//                // 是否有子级
//                if (item.getType() == 0) {
//                    menuListVo.setHasChildren(true);
//                }
                menuListVoList.add(menuListVo);
            });
        }

        vo.setMenuListVoList(menuListVoList);
        return JsonResult.success(vo);

    }

    @Override
    public JsonResult info(Integer menuId) {
        if (menuId == null && menuId <= 0) {
            return JsonResult.error("记录ID不能为空");
        }
        Object result = menuMapper.selectById(menuId);
        return JsonResult.success(result);
    }

    @Override
    public JsonResult edit(Menu entity) {
        if (entity == null) {
            return JsonResult.error("实体对象不存在");
        }
        Integer result = null;
        if (entity.getId() != null && entity.getId() > 0) {
            // 修改记录
            entity.setUpdateUser(CurrentUserUtil.getUserId());
            entity.setUpdateTime(DateUtils.now());
            result = menuMapper.updateById(entity);
            if (result <= 0) {
                return JsonResult.error();
            }
        } else {
            // 新增记录
            //entity.setTenantId(ShiroUtils.getTenantId());
            entity.setCreateUser(CurrentUserUtil.getUserId());
            entity.setCreateTime(DateUtils.now());
            entity.setMark(1);
            result = menuMapper.insert(entity);
            if (result <= 0) {
                return JsonResult.error();
            }
            //添加对应创建权限时的关联关系->只给超管角色进行添加对应菜单或权限并分配
            RoleMenu roleMenu1 = roleMenuMapper.selectOne(Wrappers.<RoleMenu>lambdaQuery()
                    .eq(RoleMenu::getMenuId, entity.getId()).eq(RoleMenu::getRoleId, 1));
            if (null == roleMenu1) {
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setRoleId(1);
                roleMenu.setMenuId(entity.getId());
                roleMenuMapper.insert(roleMenu);
            }
        }
        // 隐藏时同时隐藏所有子级
        List<Menu> menus = menuMapper.selectList(new LambdaQueryWrapper<Menu>().eq(Menu::getParentId, entity.getId()));
        if (menus.size() > 0) {
            menus.forEach(item -> {
                item.setIsHidden(entity.getIsHidden());
                menuMapper.updateById(item);
                // 获取子级
                List<Menu> menus2 = menuMapper.selectList(new LambdaQueryWrapper<Menu>().eq(Menu::getParentId, item.getId()));
                menus2.forEach(subItem -> {
                    subItem.setIsHidden(entity.getIsHidden());
                    menuMapper.updateById(subItem);
                    // 获取子级
                    List<Menu> menus3 = menuMapper.selectList(new LambdaQueryWrapper<Menu>().eq(Menu::getParentId, subItem.getId()));
                    menus3.forEach(subItem2 -> {
                        subItem2.setIsHidden(entity.getIsHidden());
                        menuMapper.updateById(subItem2);
                    });
                });
            });
        }

        return JsonResult.success("操作成功");
    }

    @Override
    public JsonResult deleteById(Integer menuId) {
        if (null == menuId) {
            return JsonResult.error("记录ID不能为空");
        }
        // 设置Mark=0
        LambdaUpdateWrapper<Menu> qw = new LambdaUpdateWrapper<Menu>().eq(Menu::getId, menuId).set(Menu::getMark, 0);
        Menu menu = new Menu();
        int result = menuMapper.update(menu, qw);
        if (result <= 0) {
            return JsonResult.error();
        }
        return JsonResult.success("删除成功");
    }

    @Override
    public List<Menu> getMenuAll() {
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("tenant_id", ShiroUtils.getTenantId());
        queryWrapper.eq("status", 1);
        //queryWrapper.le("type", 2);
        queryWrapper.eq("is_hidden", 0);
        queryWrapper.eq("mark", 1);
        queryWrapper.orderByAsc("sort");
        List<Menu> menuList = menuMapper.selectList(queryWrapper);
        return menuList;
    }
}
