package com.dxhy.admin.sys.service.impl;

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

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dxhy.admin.sys.config.SysConfig;
import com.dxhy.admin.sys.dao.SysMenuDao;
import com.dxhy.admin.sys.entity.SysMenuEntity;
import com.dxhy.admin.sys.entity.SysRoleMenuEntity;
import com.dxhy.admin.sys.model.QueryModel;
import com.dxhy.admin.sys.service.SysMenuService;
import com.dxhy.admin.sys.service.SysRoleMenuService;
import com.dxhy.admin.sys.service.SysUserService;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.constant.RedisConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.util.redis.RedisUtils;
import com.dxhy.common.utils.Aops;
import com.dxhy.common.utils.Constant;
import com.dxhy.common.utils.PageUtils;
import com.dxhy.common.utils.Query;

import lombok.extern.slf4j.Slf4j;

/**
 * @author jiaohongyang
 */
@Service("sysMenuService")
@Slf4j
public class SysMenuServiceImpl extends ServiceImpl<SysMenuDao, SysMenuEntity> implements SysMenuService {
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysRoleMenuService sysRoleMenuService;
    @Resource
    private RedisUtils redisUtils;

    @Override
    public List<SysMenuEntity> queryListParentId(Long parentId, List<Long> menuIdList) {
        List<SysMenuEntity> menuList = queryListParentId(parentId);
        if (menuIdList == null) {
            return menuList;
        }

        List<SysMenuEntity> userMenuList = new ArrayList<>();
        for (SysMenuEntity menu : menuList) {
            if (menuIdList.contains(menu.getMenuId())) {
                userMenuList.add(menu);
            }
        }
        return userMenuList;
    }

    @Override
    public List<SysMenuEntity> queryListParentId(Long parentId) {
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        return baseMapper.queryListParentId(parentId);
    }

    @Override
    public List<SysMenuEntity> queryNotButtonList() {
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        return baseMapper.queryNotButtonList();
    }

    @Override
    public List<SysMenuEntity> getUserMenuList(Long userId) {

        if (userId == Constant.SUPER_ADMIN) {
            return this.queryMenu();
        }
        return this.queryMenuRoleList(userId);
    }

    public List<SysMenuEntity> queryMenu() {
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        return baseMapper.selectList(new QueryWrapper<SysMenuEntity>().orderByAsc("order_num"));
    }

    public List<SysMenuEntity> queryMenuRoleList(Long userId) {
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        return baseMapper.queryMenuRoleList(userId);
    }

    @Override
    public void delete(Long menuId) {
        DynamicContextHolder.push(DbConstant.BASICS_WRITE);
        Aops.getSelf(this).deleteMenu(menuId);
        // 查询所有菜单数据
        List<SysMenuEntity> menuList = baseMapper.selectList(null);
        redisUtils.set(RedisConstant.KEY_MENU, menuList, -1);
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteMenu(Long menuId) {
        // 删除菜单
        this.removeById(menuId);
        // 删除菜单与角色关联
        sysRoleMenuService.remove(new QueryWrapper<SysRoleMenuEntity>().eq("menu_id", menuId));
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        String menuId = (String)params.get("menuId");
        IPage<SysMenuEntity> page = this.page(new Query<SysMenuEntity>().getPage(params),
            new QueryWrapper<SysMenuEntity>().eq(StringUtils.isNotBlank(menuId), "parent_id", menuId)
                .eq(StringUtils.isBlank(menuId), "type", "0").orderByAsc("order_num"));
        return new PageUtils(page);
    }

    @Override
    public List<SysMenuEntity> querylistMenu(String company, Long userId) {
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        List<SysMenuEntity> menuList;
        if (StringUtils.isBlank(company)) {
            menuList = baseMapper.selectList(null);
        } else {
            menuList = baseMapper.queryMenuRoleList(userId);
        }

        return sysUserService.getChildPerms(menuList, 0);
    }

    @Override
    public boolean saveMenu(SysMenuEntity menu) {
        DynamicContextHolder.push(DbConstant.BASICS_WRITE);
        boolean flg = Aops.getSelf(this).insertMenu(menu);

        // 查询所有菜单数据
        List<SysMenuEntity> menuList = this.selectList();
        redisUtils.set(RedisConstant.KEY_MENU, menuList, -1);
        return flg;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean insertMenu(SysMenuEntity menu) {
        try {
            baseMapper.insert(menu);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public List<SysMenuEntity> selectList() {
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        List<SysMenuEntity> menuList = baseMapper.selectList(null);
        return sysUserService.getChildPerms(menuList, 0);

    }

    @Override
    public boolean updateMenu(SysMenuEntity menu) {
        DynamicContextHolder.push(DbConstant.BASICS_WRITE);
        boolean flg = Aops.getSelf(this).update(menu);
        // 查询所有菜单数据
        List<SysMenuEntity> menuList = this.selectList();
        redisUtils.set(RedisConstant.KEY_MENU, menuList, -1);
        return flg;
    }

    public boolean renovateMenu(SysMenuEntity menu) {
        return sysUserService.queryUserMenu(menu.getMenuId());
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean update(SysMenuEntity menu) {
        try {
            baseMapper.updateById(menu);

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public List<SysMenuEntity> getMenuAll() {
        List<SysMenuEntity> menuList;
        String menuJson = redisUtils.get(RedisConstant.KEY_MENU);
        if (StringUtils.isNotBlank(menuJson)) {
            menuList = JSON.parseArray(menuJson, SysMenuEntity.class);
            if (menuList.size() <= 0) {
                menuList = this.selectList();
            }
        } else {
            menuList = this.selectList();
        }
        return menuList;
    }

    @Override
    public SysMenuEntity queryMenuById(Long id) {
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        return baseMapper.selectById(id);
    }

    @Override
    public List<SysMenuEntity> queryMenuLog(String menuUrl) {
        DynamicContextHolder.push(DbConstant.BASICS_READ);

        return baseMapper.queryMenuLog(menuUrl);
    }

    @Override
    public SysMenuEntity queryMenuType(String url, int type, String systemCode) {
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        return baseMapper.queryMenuType(url, type, systemCode);
    }

    @Override
    public void saveMenuBatch(List<SysMenuEntity> menu) {
        DynamicContextHolder.push(DbConstant.BASICS_WRITE);
        Aops.getSelf(this).insertMenuBatch(menu);
        // 查询所有菜单数据
        List<SysMenuEntity> menuList = this.selectList();
        redisUtils.set(RedisConstant.KEY_MENU, menuList, -1);
    }

    @Override
    public List<SysMenuEntity> queryMenuRoleCompanyList(String company) {
        if (StringUtils.isBlank(company)) {
            return null;
        }
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        List<SysMenuEntity> sysMenuEntities;
        if (SysConfig.ZXQY.equals(company)) {
            sysMenuEntities = this.queryMenu();
        } else {
            sysMenuEntities = baseMapper.queryMenuRoleCompanyList(company);

        }
        return sysUserService.getChildPerms(sysMenuEntities, 0);
    }

    @Override
    public int saveQuery(String dataList) {
        try {
            QueryModel queryModel = JSON.parseObject(dataList, QueryModel.class);
            if (StringUtils.isBlank(queryModel.getMenuId())) {
                return 2;
            }
            List<SysMenuEntity> sysMenuList = queryModel.getDomains();
            if (sysMenuList.size() > 0) {
                for (SysMenuEntity sysMenuEntity : sysMenuList) {
                    sysMenuEntity.setParentId(Long.parseLong(queryModel.getMenuId()));
                    sysMenuEntity.setType(4);
                }
                Aops.getSelf(this).saveMenuBatch(sysMenuList);
            }

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 3;
        }

    }

    @Override
    public List<SysMenuEntity> getQueryList(long menuId, int type) {
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        return baseMapper.selectList(new QueryWrapper<SysMenuEntity>().eq("parent_id", menuId).eq("type", type));
    }

    @Override
    public List<Long> queryIdList(List<Long> menuIds) {
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        return baseMapper.queryIdList(menuIds);
    }

    @Transactional(rollbackFor = Exception.class)
    public void insertMenuBatch(List<SysMenuEntity> menu) {
        try {
            this.saveOrUpdateBatch(menu);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
