package com.willalp.web.demo.treetable.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.willalp.common.core.service.impl.TreeCommonServiceImpl;
import com.willalp.common.utils.StringUtils;
import com.willalp.web.demo.treetable.entity.TreeTable;
import com.willalp.web.demo.treetable.mapper.TreeTableMapper;
import com.willalp.web.demo.treetable.service.ITreeTableService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


/**
 * All rights Reserved, Designed By www.sunseagear.com
 *
 * @version V1.0
 * @package test.treetable
 * @title: 树形结构表控制器
 * @description: 树形结构表控制器
 * @author: admin
 * @date: 2019-11-13 21:38:34
 * @copyright: www.sunseagear.com Inc. All rights reserved.
 */
@Transactional
@Service("treeTableService")
public class TreeTableServiceImpl extends TreeCommonServiceImpl<TreeTableMapper, TreeTable> implements ITreeTableService {


//    @Override
//    public List<TreeTable> list(Wrapper<TreeTable> wrapper) {
//        List<TreeTable> list = super.list(wrapper);
//        return getTreeTables(list);
//    }

    private List<TreeTable> getTreeTables(List<TreeTable> treeNodeList) {
        List<TreeTable> TreeTableListAll = list(new QueryWrapper());
        HashMap<Long, TreeTable> TreeTableHashMapAll = new HashMap<>();
        TreeTableListAll.forEach(TreeTable -> {
            TreeTableHashMapAll.put(Long.valueOf(TreeTable.getId()), TreeTable);
        });
        HashMap<Long, TreeTable> TreeTableHashMap = new HashMap<>();
        treeNodeList.forEach(treeNode -> {
            String parentIds = treeNode.getAncestors();
            if (!StringUtils.isEmpty(parentIds)) {
                Arrays.asList(parentIds.split("/")).forEach(id -> {
                    TreeTable TreeTable = TreeTableHashMapAll.get(Long.valueOf(id));
                    TreeTableHashMap.put(Long.valueOf(id), TreeTable);
                });
            }
            TreeTableHashMap.put(Long.valueOf(treeNode.getId()), TreeTableHashMapAll.get(treeNode.getId()));

        });
        List<TreeTable> TreeTableList = new ArrayList<>();
        TreeTableHashMap.values().forEach(item -> {
            TreeTableList.add(item);
        });
        TreeTableList.sort(new Comparator<TreeTable>() {
            @Override
            public int compare(TreeTable o1, TreeTable o2) {
                return o1.getCreateTime().compareTo(o2.getCreateTime());
            }
        });
        return TreeTableList;
    }

}
