/*
 * Author: wangjian
 * 生成ServiceImpl
 */
package com.tofly.water.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.water.entity.TfRegionP;
import com.tofly.water.mapper.TfRegionPMapper;
import com.tofly.water.service.TfRegionPService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 行政区划
 *
 * @author JF
 * @date Wed Aug 03 00:00:00 CST 2022
 */
@Service("tfRegionPService")
public class TfRegionPServiceImpl extends ServiceImpl<TfRegionPMapper, TfRegionP> implements TfRegionPService {

    @Override
    public List<TfRegionP> getTfRegionPTree(TfRegionP tfRegionP) {
//        List<TfRegionP> parents = this.list(new QueryWrapper<TfRegionP>()
//                .eq("REGION_LEVEL","1")
//                .isNull("REGION_ID"));
        List<TfRegionP> parents = this.list(new QueryWrapper<TfRegionP>()
                .eq("REGION_LEVEL","3")
                .eq(tfRegionP.getTenantId() != null,"TENANT_ID",tfRegionP.getTenantId()));
        for(TfRegionP parent : parents){
            if(StringUtils.isBlank(parent.getRegionCode())){
                continue;
            }
            List<TfRegionP> regions = this.list(new QueryWrapper<TfRegionP>()
                    .eq("REGION_ID",Long.parseLong(parent.getRegionCode()))
                    .eq(tfRegionP.getTenantId() != null,"TENANT_ID",tfRegionP.getTenantId()));
            parent.setRegionVos(getRegionList(regions));
        }
        return parents;
    }

    /**
     * @param regionVos
     * @return
     * @descript:递归市区
     */
    public List<TfRegionP> getRegionList(List<TfRegionP> regionVos) {
        List<TfRegionP> regionVosList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(regionVos)) {
            for (TfRegionP regionVo : regionVos) {
                if(StringUtils.isBlank(regionVo.getRegionCode())){
                    continue;
                }
                List<TfRegionP> regions = this.list(new QueryWrapper<TfRegionP>()
                        .eq("REGION_ID",Long.parseLong(regionVo.getRegionCode()))
                        .eq(regionVo.getTenantId() != null,"TENANT_ID",regionVo.getTenantId()));
                if(regionVo.getRegionLevel().equals("4")){
                    regionVo.setRegionVos(regions);
                }else {
                    regionVo.setRegionVos(getRegionList(regions));
                }
                regionVosList.add(regionVo);
            }
        }
        return regionVosList;
    }
}
