package com.yeejoin.amos.boot.module.ccs.biz.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.module.ccs.api.dto.BaseDto;
import com.yeejoin.amos.boot.module.ccs.api.dto.FireBuildingDto;
import com.yeejoin.amos.boot.module.ccs.api.entity.FireBuilding;
import com.yeejoin.amos.boot.module.ccs.api.mapper.FireBuildingMapper;
import com.yeejoin.amos.boot.module.ccs.api.service.IFireBuildingService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.core.rdbms.annotation.Condition;
import org.typroject.tyboot.core.rdbms.annotation.Operator;
import org.typroject.tyboot.core.rdbms.service.BaseService;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 消防建筑表服务实现类
 *
 * @author system_generator
 * @date 2021-11-09
 */
@Service
public class FireBuildingServiceImpl extends BaseService<FireBuildingDto, FireBuilding, FireBuildingMapper> implements IFireBuildingService {

    public static final String ROOT_ID = "-1";
    /**
     * 分页查询
     */
    public Page<FireBuildingDto> queryForFireBuildingPage(Page<FireBuildingDto> page, @Condition(Operator.like) String name, @Condition String stationCode, String type) {
        return this.queryForPage(page, "create_date", false, name, stationCode, type);
    }


    public List<FireBuildingDto> buildingTree(String stationCode) {
        List<FireBuildingDto> dtoList = this.queryForList("create_date", true, stationCode);
        FireBuildingDto parentNode = new FireBuildingDto();
        parentNode.setId(ROOT_ID);
        parentNode.setName("全部建筑");
        parentNode.setMrid(ROOT_ID);
        parentNode.setTreeMrids(ROOT_ID);
        List<FireBuildingDto> childrenNode = dtoList.stream().filter(d -> StringUtils.isBlank(d.getParentMrid()) || "0".equals(d.getParentMrid()) || "-1".equals(d.getParentMrid())).peek(s -> s.setChildren(this.getChildren(s.getMrid(), dtoList))).sorted(Comparator.comparing(BaseDto::getCreateDate)).collect(Collectors.toList());
        parentNode.setChildren(childrenNode);
        return Collections.singletonList(parentNode);
    }

    private List<FireBuildingDto> getChildren(String mrid, List<FireBuildingDto> dtoList) {
        return dtoList.stream().filter(d -> StringUtils.isNotBlank(d.getParentMrid()) && d.getParentMrid().equals(mrid)).peek(s -> s.setChildren(this.getChildren(s.getMrid(), dtoList))).sorted(Comparator.comparing(BaseDto::getCreateDate)).collect(Collectors.toList());
    }
}