/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.manager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.node.ForestNodeMerger;
import org.springblade.core.tool.utils.Func;
import org.springblade.manager.dto.ArchiveTreeDTO;
import org.springblade.manager.entity.ArchiveTree;
import org.springblade.manager.vo.ArchiveTreeVO;
import org.springblade.manager.mapper.ArchiveTreeMapper;
import org.springblade.manager.service.IArchiveTreeService;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 服务实现类
 *
 * @author liuyc
 * @since 2022-06-29
 */
@Service
@AllArgsConstructor
public class ArchiveTreeServiceImpl extends BaseServiceImpl<ArchiveTreeMapper, ArchiveTree> implements IArchiveTreeService {

    private final ArchiveTreeMapper archiveTreeMapper;

    private static List<String> getDiffrent(List<String> list1, List<String> list2) {
        List<String> diff = new ArrayList<String>();
        List<String> maxList = list1;
        List<String> minList = list2;
        if (list2.size() > list1.size()) {
            maxList = list2;
            minList = list1;
        }
        Map<String, Integer> map = new HashMap<String, Integer>(maxList.size());
        for (String string : maxList) {
            map.put(string, 1);
        }
        for (String string : minList) {
            if (map.get(string) != null) {
                map.put(string, 2);
                continue;
            }
            diff.add(string);
        }
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            if (entry.getValue() == 1) {
                diff.add(entry.getKey());
            }
        }
        return diff;
    }

    @Override
    public boolean initArchiveTree() {
        QueryWrapper<ArchiveTree> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", 0);
        queryWrapper.eq("ancestors", 0);
        queryWrapper.eq("status", 1);
        ArchiveTree archiveTree1 = archiveTreeMapper.selectOne(queryWrapper);
        if (archiveTree1 != null) {
            throw new ServiceException("根节点已存在,请先删除后再进行初始化");
        }
        ArchiveTree archiveTree = new ArchiveTree();
        archiveTree.setTenantId(AuthUtil.getTenantId());
        archiveTree.setParentId(0L);
        archiveTree.setAncestors(String.valueOf(0));
        archiveTree.setNodeName("系统级归档树");
        archiveTree.setFullName("系统级归档树");
        if (AuthUtil.getUserId() != null && AuthUtil.getDeptId() != null) {
            archiveTree.setCreateDept(Long.valueOf(AuthUtil.getDeptId()));
            archiveTree.setCreateUser(AuthUtil.getUserId());
        }
        return this.save(archiveTree);
    }


    @Override
    public List<ArchiveTreeVO> lazyTree(String tenantId, Long parentId) {
        if (AuthUtil.isAdministrator()) {
            tenantId = StringPool.EMPTY;
        }
        return ForestNodeMerger.merge(baseMapper.lazyTree(tenantId, parentId));
    }

    @Override
    public List<ArchiveTreeVO> tree(String tenantId, Integer disPlayTree, Integer nodeType) {
        return ForestNodeMerger.merge(baseMapper.tree(tenantId, disPlayTree, nodeType));
    }

    @Override
    public List<ArchiveTree> selectByParentId(String id) {
        return baseMapper.selectList(Wrappers.<ArchiveTree>query().lambda().eq(ArchiveTree::getParentId, id));
    }

    @Override
    public boolean submitDisplayConfigTree(String ids) {
        //获取当前已配置的显示树
        List<ArchiveTree> archiveTrees = baseMapper.selectList(Wrappers.<ArchiveTree>query().lambda()
                .eq(ArchiveTree::getIsUploadFileDisplayConfigurationTree, 1));
        String[] idList = ids.split(",");
        List<String> idQ = Arrays.asList(idList);
        List<String> idList1 = idQ.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
        List<String> idList2 = new ArrayList<>();
        archiveTrees.stream().forEach(id -> {
            idList2.add(String.valueOf(id.getId()));
        });
        List<String> diffRent = getDiffrent(idList1, idList2);
        if (diffRent.size() == 0) {
            return true;
        } else {
            int row;
            if (idList1.size() > idList2.size()) {
                //新增
                row = baseMapper.updateBatch(diffRent);
            } else {
                //删除
                row = baseMapper.updateBatch2(diffRent);
            }
            return row > 0;
        }
    }

    @Override
    public boolean submit(ArchiveTreeDTO archiveTreeDTO) {
        if (Func.isEmpty(archiveTreeDTO.getParentId())) {
            archiveTreeDTO.setTenantId(AuthUtil.getTenantId());
            archiveTreeDTO.setParentId(BladeConstant.TOP_PARENT_ID);
            archiveTreeDTO.setAncestors(String.valueOf(BladeConstant.TOP_PARENT_ID));
        }
        if (archiveTreeDTO.getParentId() > 0) {
            ArchiveTree parent = getById(archiveTreeDTO.getParentId());
            if (Func.toLong(archiveTreeDTO.getParentId()) == Func.toLong(archiveTreeDTO.getId())) {
                throw new ServiceException("父节点不可选择自身!");
            }
            archiveTreeDTO.setTenantId(parent.getTenantId());
            String ancestors = parent.getAncestors() + StringPool.COMMA + archiveTreeDTO.getParentId();
            archiveTreeDTO.setAncestors(ancestors);
        }
        if (AuthUtil.getUserId() != null && StringUtils.isNotEmpty(AuthUtil.getDeptId())) {
            archiveTreeDTO.setCreateDept(Long.valueOf(AuthUtil.getDeptId()));
            archiveTreeDTO.setCreateUser(AuthUtil.getUserId());
        }
        archiveTreeDTO.setIsDeleted(BladeConstant.DB_NOT_DELETED);
        archiveTreeDTO.setFullName(archiveTreeDTO.getNodeName());
        return save(archiveTreeDTO);
    }

}
