package com.chinaweal.aiccs.org.controller;

import com.chinaweal.aiccs.common.base.controller.BaseController;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aiccs.org.entity.vo.CascaderVO;
import com.chinaweal.aiccs.org.service.AicorgService;
import com.chinaweal.youfool.framework.springboot.rest.RestResult;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 机构表 控制器
 *
 * @author zhouxy
 * @since 2026-01-10
 */
@Api(tags = "组织结构")
@ApiSort(2)
@RestController
@RequestMapping("/tOrgunits")
public class TOrgunitsController extends BaseController {

    @Resource
    private AicorgService aicorgService;

    @ApiOperation(value = "获取某个地市下面所有机关")
    @PostMapping("/getAllOrgunits")
    public RestResult<?> getAllOrgunits(String orgNumber,Integer orgLevel) {
        List<CascaderVO> orgunits;
        if(StringUtils.isNotEmpty(orgNumber)){
            orgNumber = orgNumber+"%";
        }
        if(orgLevel == 0){
            orgLevel = 1;
        }
        orgunits = aicorgService.queryAll(orgNumber);
        List<CascaderVO> level1 = new ArrayList<>();
        CascaderVO cascader = new CascaderVO();
        List<CascaderVO> level2 = new ArrayList<>();
        for (CascaderVO orgunit : orgunits) {
            if (orgunit.getOrgLevel() == orgLevel.intValue()) {
                cascader.setLabel(orgunit.getLabel());
                cascader.setOrgUnitId(orgunit.getOrgUnitId());
                cascader.setParentID(orgunit.getParentID());
                cascader.setValue(orgunit.getValue());
                cascader.setOrgLevel(orgunit.getOrgLevel());
            }
            if (Objects.equals(orgunit.getOrgLevel(), orgLevel + 1)) {
                level2.add(orgunit);
            }
        }
        merge(level2, orgunits);
        cascader.setChildren(level2);
        level1.add(cascader);
        return RestResult.ok(level1);
    }

    private void merge(List<CascaderVO> pre, List<CascaderVO> all) {
        List<CascaderVO> ooo = new ArrayList<>();
        for (CascaderVO orgunits : pre) {
            for (CascaderVO org : all) {
                if (StringUtils.equals(org.getParentID(), orgunits.getOrgUnitId())) {
                    if (orgunits.getChildren() == null) {
                        orgunits.setChildren(new ArrayList<>());
                    }
                    orgunits.getChildren().add(org);
                    ooo.add(org);
                }
            }
        }
        if (ooo.size() > 0) {
            merge(ooo, all);
        }
    }

}
