package com.zbkj.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbkj.common.model.bcx.BcxRegion;
import com.zbkj.common.response.BcxRegionResponse;
import com.zbkj.service.dao.BcxRegionDao;
import com.zbkj.service.service.BcxRegionService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * description: v5区域表 服务实现类
 * author : linchunpeng
 * date : 2023/8/3
 */
@Service
public class BcxRegionServiceImpl extends ServiceImpl<BcxRegionDao, BcxRegion> implements BcxRegionService {
    
    @Resource
    private BcxRegionDao dao;

    /**
     * description：通过区域code查询区域
     * author：linchunpeng
     * date：2023/10/24
     */
    @Override
    public BcxRegion findByCode(String code) {
        LambdaQueryWrapper<BcxRegion> lqw = new LambdaQueryWrapper<>();
        lqw.eq(BcxRegion::getRegionCode, code);
        return dao.selectOne(lqw);
    }

    /**
     * description：获取区域tree列表
     * author：linchunpeng
     * date：2023/8/4
     */
    @Override
    public List<BcxRegionResponse> findAllTree() {
        List<BcxRegion> allList = this.list();
        List<BcxRegionResponse> responseList = allList.stream().map(this::getBcxRegionResponse).collect(Collectors.toList());
        Map<String, BcxRegionResponse> responseMap = responseList.stream().collect(Collectors.toMap(BcxRegionResponse::getRegionCode, Function.identity()));

        for (BcxRegionResponse response : responseList) {
            BcxRegionResponse parent = responseMap.get(response.getParentCode());
            if (parent != null) {
                parent.addChildren(response);
            }
        }
        List<BcxRegionResponse> rootList = responseList.stream().filter(region -> region.getParentCode().equals("100000")).collect(Collectors.toList());
        return rootList;
    }

    /**
     * description：获取BcxRegionResponse对象
     * author：linchunpeng
     * date：2023/8/4
     */
    private BcxRegionResponse getBcxRegionResponse(BcxRegion region) {
        BcxRegionResponse regionResponse = new BcxRegionResponse();
        regionResponse.setRegionCode(region.getRegionCode());
        regionResponse.setParentCode(region.getParentCode());
        regionResponse.setRegionName(region.getRegionName());
        return regionResponse;
    }
    
}