package com.xunmei.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xunmei.common.core.constant.CacheConstants;
import com.xunmei.common.core.constant.Constants;
import com.xunmei.common.core.exception.ServiceException;
import com.xunmei.common.core.utils.DateUtils;
import com.xunmei.common.core.utils.StringUtils;
import com.xunmei.common.core.web.page.TableDataInfo;
import com.xunmei.common.redis.utils.RedisUtils;
import com.xunmei.common.security.utils.SecurityUtils;
import com.xunmei.system.api.domain.SysOrg;
import com.xunmei.system.mapper.SysOrgMapper;
import com.xunmei.system.mapper.SysUserMapper;
import com.xunmei.system.service.ISysOrgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author xunmei
 * @date 2023-08-10
 */
@Service
public class SysOrgServiceImpl extends ServiceImpl<SysOrgMapper, SysOrg> implements ISysOrgService {
    @Autowired
    private SysOrgMapper sysOrgMapper;
    @Autowired
    private SysUserMapper sysUserMapper;



    /**
     * 项目启动时，缓存机构数据
     */
    @PostConstruct
    public void init() {
        loadingOrgCache();
    }


    @Override
    public TableDataInfo<SysOrg> selectPage(SysOrg org) {
        //未删除
        org.setDeleted(0);
        Page<SysOrg> page;
        //分页
        if (org.getPageNum() != null && org.getPageSize() != null) {
            page = new Page<>(org.getPageNum(), org.getPageSize());
        } else {
            page = new Page<>();
        }
        Long parentId = org.getParentId();
        if(parentId == null){
            parentId = SecurityUtils.getLoginUser().getSysUser().getOrgId();
        }
        SysOrg sysOrg = sysOrgMapper.selectById(parentId);

        org.setParentId(null);
        //查询条件
        QueryWrapper<SysOrg> query = new QueryWrapper<>(org);
        //下穿
        if (org.getCheckSub()) {
            query.lambda().likeRight(SysOrg::getPath, sysOrg.getPath());
        } else {
            query.lambda().eq(SysOrg::getPath,sysOrg.getPath());
        }
        //模糊查询
        if (StringUtils.isNotNull(org.getName())) {
            query.like("name", org.getName());
            org.setName(null);
        }
        query.lambda().orderByAsc(SysOrg::getPath);
        //获取数据
        page = baseMapper.selectPage(page, query);
        //抓换为TableDataInfo适配前端
        return TableDataInfo.build(page);

    }

    @Override
    public List<Long> selectCheckSubOrgIdList(Long orgId) {
        return sysOrgMapper.selectCheckSubOrgIdList(orgId);
    }

    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public SysOrg selectSysOrgById(Long id) {
        return sysOrgMapper.selectById(id);
    }

    @Override
    public List<Long> findListByOrgType(Integer execOrgType) {
        return sysOrgMapper.findListByOrgType(execOrgType);
    }

    @Override
    public List<SysOrg> listByTypes(Long topId, List<String> types) {
        SysOrg top = sysOrgMapper.selectById(topId);
        if (ObjectUtil.isNull(top)) {
            return new ArrayList<>();
        }

        LambdaQueryWrapper<SysOrg> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysOrg::getDeleted, 0);
        wrapper.in(SysOrg::getType, types);
        wrapper.likeRight(SysOrg::getPath, top.getPath());
        return sysOrgMapper.selectList(wrapper);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param sysOrg 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<SysOrg> selectSysOrgList(SysOrg sysOrg) {
        return sysOrgMapper.selectSysOrgList(sysOrg);
    }

    @Override
    @Async
    public void batchSaveOrUpdate(List<SysOrg> orgList) {
        saveOrUpdateBatch(orgList);
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param sysOrg 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertSysOrg(SysOrg sysOrg) {
        sysOrg.setCreateTime(DateUtils.getNowDate());
        return sysOrgMapper.insertSysOrg(sysOrg);
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param sysOrg 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateSysOrg(SysOrg sysOrg) {
        sysOrg.setUpdateTime(DateUtils.getNowDate());
        return sysOrgMapper.updateSysOrg(sysOrg);
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteSysOrgByIds(Long[] ids) {
        return sysOrgMapper.deleteSysOrgByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteSysOrgById(Long id) {
        return sysOrgMapper.deleteSysOrgById(id);
    }

    @Override
    public String selectPathById(Long orgId) {
        LambdaQueryWrapper<SysOrg> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysOrg::getId, orgId);
        wrapper.select(SysOrg::getPath);
        SysOrg sysOrg = sysOrgMapper.selectOne(wrapper);
        if (sysOrg != null) {
            return sysOrg.getPath();
        }
        throw new RuntimeException("未找到机构信息");
    }

    @Override
    public SysOrg selectByParentId(Long orgId) {
        LambdaQueryWrapper<SysOrg> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysOrg::getParentId, orgId);
        return sysOrgMapper.selectOne(wrapper);
    }

    @Override
    public List<SysOrg> selectByOrgType(Integer orgType) {
        LambdaQueryWrapper<SysOrg> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysOrg::getType, orgType);
        wrapper.eq(SysOrg::getDeleted, 0);
        return sysOrgMapper.selectList(wrapper);
    }

    @Override
    public SysOrg getSysOrgByUserId(Long userId) {
        return sysUserMapper.selectSysByUserId(userId);
    }

    @Override
    public List<SysOrg> selectDeptTreeList(SysOrg dept) {
        Long userId = SecurityUtils.getUserId();
        SysOrg sysOrg = baseMapper.selectSysOrgByUserId(userId);
        if (ObjectUtil.isNull(sysOrg)) {
            throw new ServiceException("当前用户没有部门信息");
        }
        final LambdaQueryWrapper<SysOrg> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysOrg::getDeleted, 0);
        wrapper.isNotNull(SysOrg::getParentId);
        Long parentId = Constants.TOP_ORG_PARENT_ID;
        if (ObjectUtil.notEqual(Constants.TOP_ORG_PARENT_ID, sysOrg.getParentId())) {
            parentId = sysOrg.getParentId();
            wrapper.likeRight(SysOrg::getPath, sysOrg.getPath());
        }
        List<SysOrg> depts = baseMapper.selectList(wrapper);
        final Map<Long, List<SysOrg>> collect = depts.stream().collect(Collectors.groupingBy(SysOrg::getParentId));
        return handleTree(collect, parentId);
    }

    @Override
    public void loadingOrgCache() {
        QueryWrapper<SysOrg> qw = new QueryWrapper<>();
        qw.lambda().ge(SysOrg::getDeleted, 0);
        List<SysOrg> list = baseMapper.selectList(qw);
        clearOrgCache();
        RedisUtils.setCacheList(CacheConstants.ORG_CACHE_LIST_KEY, list);
        //redisService.setCacheList(CacheConstants.ORG_CACHE_LIST_KEY, list);
    }

    @Override
    public void clearOrgCache() {
        RedisUtils.deleteObject(CacheConstants.ORG_CACHE_LIST_KEY);
        //redisService.deleteObject(CacheConstants.ORG_CACHE_LIST_KEY);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveOrUpdateOrg(SysOrg org) {

        boolean isOk = false;
        if (org.getId() != null) {
            isOk = this.updateById(org);
        } else {
            isOk = this.save(org);
        }

        /*
         * 重置缓存
         */
        this.clearOrgCache();
        this.loadingOrgCache();

        return isOk;
    }

    @Override
    public boolean removeOrg(Long orgId) {
        boolean rel = this.removeById(orgId);
        /*
         * 重置缓存
         */
        this.clearOrgCache();
        this.loadingOrgCache();
        return rel;
    }

    private static List<SysOrg> handleTree(Map<Long, List<SysOrg>> map, Long parentId) {
        List<SysOrg> orgList = map.get(parentId);
        if (ObjectUtil.isNotEmpty(orgList)) {
            orgList.forEach(org -> {
                final List<SysOrg> tree = handleTree(map, org.getId());
                org.setChildren(tree);
            });
        }
        return orgList;
    }
}
