package com.tykj.dev.device.user.subject.service.impl;

import com.tykj.dev.config.service.SystemConfigService;
import com.tykj.dev.device.user.base.req.UnitNameVo;
import com.tykj.dev.device.user.base.req.UnitsAddVo;
import com.tykj.dev.device.user.base.ret.*;
import com.tykj.dev.device.user.cache.AreaCache;
import com.tykj.dev.device.user.cache.AreaExhibitionCache;
import com.tykj.dev.device.user.cache.UnitsCache;
import com.tykj.dev.device.user.subject.dao.AreaDao;
import com.tykj.dev.device.user.subject.dao.UnitsDao;
import com.tykj.dev.device.user.subject.entity.Area;
import com.tykj.dev.device.user.subject.entity.AreaExhibition;
import com.tykj.dev.device.user.subject.entity.SecurityUser;
import com.tykj.dev.device.user.subject.entity.Units;
import com.tykj.dev.device.user.subject.service.AreaExhibitionService;
import com.tykj.dev.device.user.subject.service.UnitsService;
import com.tykj.dev.misc.exception.ApiException;
import com.tykj.dev.misc.utils.DeviceModelSort;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zjm
 * @version 1.0.0
 * @ClassName UnitsServiceImpl.java
 * @Description TODO
 * @createTime 2020年07月28日 10:14:00
 */
@Service
@Slf4j
public class UnitsServiceImpl implements UnitsService {
    @Autowired
    UnitsDao unitsDao;
    @Autowired
    AreaDao areaDao;
    @Autowired
    UnitsCache unitsCache;

    @Autowired
    AreaCache areaCache;

    @Autowired
    AreaExhibitionCache areaExhibitionCache;

    @Autowired
    SystemConfigService systemConfigService;

    @Autowired
    AreaExhibitionService areaExhibitionService;

    @Override
    public Units findById(Integer unitId) {
        Optional<Units> unit = unitsDao.findById(unitId);
        return unit.orElse(null);
    }

    @Override
    public Units findbyName(String name) {
        return unitsDao.findByName(name);
    }

    @Override
    public Units findUnitAreaId(Integer areaId) {
        return unitsDao.findByAreaId(areaId).get(0);
    }

    @Override
    public List<Units> findListById(Integer leven) {
        return unitsDao.findAllByLevel(leven);
    }

    @Override
    public List<AreaVo> findListAreaUnitsVo(SecurityUser securityUser) {
        return new ArrayList<>();
    }

    /**
     * 根据所在区域是省还是市
     * 省 则把下属市以及市下属都区都单位统一放入市AreaVo 在放入List<AreaVo> 集合中。
     * 市 则把下属区都单位放入市都AreaVo对象中
     *
     * @param thisArea 本单位区域
     * @param areas    下级区域列表
     */
    private List<LeftNavigation> provinceAndCity(Area thisArea, List<Area> areas, List<LeftNavigation> leftNavigationList) {
        if (thisArea.getType() == 1) {
            areas.forEach(area -> {
                LeftNavigation leftNavigation = area.toLeftNavigation();
                List<LeftNavigation> leftNavigationList1 = new ArrayList<>();
                unitsDao.findAllByAreaId(area.getId()).forEach(
                        units -> {
                            LeftNavigation leftNavigation1 = units.toLeftNavigation();
                            leftNavigation1.setTheirId(units.getAreaId());
                            leftNavigationList1.add(leftNavigation1);
                        }

                );
                List<Area> countys = areaDao.findAllByFatherId(area.getId()).stream().filter(area1 -> area1.getType() <= 3).collect(Collectors.toList());
                if (countys != null && countys.size() != 0) {
                    countys.forEach(
                            area1 -> unitsDao.findAllByAreaId(area1.getId()).forEach(
                                    units -> {
                                        LeftNavigation leftNavigation1 = units.toLeftNavigation();
                                        leftNavigation1.setTheirId(area.getId());
                                        leftNavigationList1.add(leftNavigation1);
                                    }

                            )
                    );
                }
                leftNavigation.setLeftNavigations(leftNavigationList1.stream().sorted(Comparator.comparing(LeftNavigation::getOrder, Comparator.nullsLast(Integer::compareTo))).collect(Collectors.toList()));
                leftNavigationList.add(leftNavigation);
            });
        } else if (thisArea.getType() == 2) {
            areas.forEach(area -> {
                unitsDao.findAllByAreaId(area.getId()).forEach(
                        units -> {
                            LeftNavigation leftNavigation1 = units.toLeftNavigation();
                            leftNavigation1.setTheirId(thisArea.getId());
                            leftNavigationList.add(leftNavigation1);
                        }

                );
            });
        } else {
            return leftNavigationList;
        }
        return leftNavigationList;
    }


    @Override
    public List<Units> findListlevenGreaterThanEqual(Integer leven) {
        return unitsDao.findAllByLevelGreaterThanEqual(leven);
    }


    @Override
    public List<Integer> findListSubordinateId(Integer unitsId) {
        Integer areaId = unitsDao.findById(unitsId).get().getAreaId();
        List<Integer> areaIds = areaDao.findAllByFatherId(areaId).stream().filter(area -> area.getType() <= 3).map(Area::getId).collect(Collectors.toList());
        return unitsDao.findAllByAreaIdIn(areaIds).stream().map(Units::getUnitId).collect(Collectors.toList());
    }

    @Override
    public List<UnitsVo> findListVoSubordinateAreaId(Integer areaId) {
        List<UnitsVo> unitsVos = new ArrayList<>();
        List<Integer> areaIds = areaDao.findAllByFatherId(areaId).stream().filter(area -> area.getType() <= 3).map(Area::getId).collect(Collectors.toList());
        if (areaIds.size() != 0) {
            unitsVos = unitsDao.findAllByAreaIdIn(areaIds).stream().map(Units::toVo).collect(Collectors.toList());
        }
        return unitsVos;
    }

    @Override
    public List<UnitsVo> findListVoAreaId(Integer areaId) {
        return unitsDao.findAllByAreaId(areaId).stream().map(Units::toVo).collect(Collectors.toList());
    }

    @Override
    public List<UnitsTrainVo> findListUnitsTrainVo(Integer unitsId) {
        Integer areaId = unitsDao.findById(unitsId).get().getAreaId();
        List<Integer> areaIds = areaDao.findAllByFatherId(areaId).stream().filter(area -> area.getType() <= 3).map(Area::getId).collect(Collectors.toList());
        return unitsDao.findAllByAreaIdIn(areaIds).stream().map(Units::toUnitsTrainVo).collect(Collectors.toList());
    }

    @Override
    public List<Integer> findSuperiorByunitsId(Integer unitsId) {
        Area area = areaDao.findById(this.findById(unitsId).getAreaId()).get();
        return unitsDao.findAllByAreaId(area.getFatherId()).stream().map(Units::getUnitId).collect(Collectors.toList());
    }

    @Override
    public Units findByAreaId(Integer unitsId) {

        return unitsDao.findAllByAreaId(
                areaDao.findById(
                        findById(unitsId).getAreaId()
                ).get().getFatherId()
        ).get(0);

    }

    @Override
    public List<Units> findBySubordinate(Integer unitsId) {
        Units units = unitsDao.findById(unitsId).get();
        List<Integer> areaIds = areaDao.findAllByFatherId(units.getAreaId()).stream().filter(area -> area.getType() <= 3).map(Area::getId).collect(Collectors.toList());
        List<Units> units1 = unitsDao.findAllByAreaIdIn(areaIds);
        if (units.getLevel() == 1) {
            units1.add(units);
            units1.addAll(unitsDao.findAllByType(2));
        }
        return units1.stream().sorted(Comparator.comparing(Units::getShowOrder)).distinct().collect(Collectors.toList());
    }

    @Override
    public List<Units> findBySubordinateAll(Integer unitsId) {
        Units units =  unitsDao.findById(unitsId).get();
        List<Integer> areaIds= areaDao.findAllByFatherId(units.getAreaId()).stream().filter(area -> area.getType() <= 3).map(Area::getId).collect(Collectors.toList());
        List<Units> units1=  unitsDao.findAllByAreaIdIn(areaIds);
        if (units.getLevel()==1){
            units1.addAll(unitsDao.findAllByType(2));
        }
        units1.add(units);
        return units1.stream().sorted(Comparator.comparing(Units::getShowOrder)).distinct().collect(Collectors.toList());
    }

    @Override
    public List<Units> findBySubordinateNotOneself(Integer unitsId) {
        Units units = unitsDao.findById(unitsId).get();
        List<Integer> areaIds = areaDao.findAllByFatherId(units.getAreaId()).stream().filter(area -> area.getType() <= 3).map(Area::getId).collect(Collectors.toList());
        List<Units> units1 = unitsDao.findAllByAreaIdIn(areaIds);
        if (units.getLevel() == 1) {
//            units1.add(units);
            units1.addAll(unitsDao.findAllByType(2));
        }
        return units1.stream().sorted(Comparator.comparing(Units::getShowOrder)).distinct().collect(Collectors.toList());
    }

    @Override
    public List<String> findBySubordinateUnitName(Integer unitsId) {
        Units units = unitsDao.findById(unitsId).get();
        List<Integer> areaIds = areaDao.findAllByFatherId(units.getAreaId()).stream().map(Area::getId).collect(Collectors.toList());
        List<String> list = new ArrayList<>();
        list.add(units.getName());
        unitsDao.findAllByAreaIdIn(areaIds).forEach(
                units1 -> list.add(units1.getName())
        );
        return list;
    }

    @Override
    public List<Units> findBySubordinateUnit(Integer unitsId) {
        Units units = unitsDao.findById(unitsId).get();
        List<Integer> areaIds = areaDao.findAllByFatherId(units.getAreaId()).stream().map(Area::getId).collect(Collectors.toList());
        List<Units> list = unitsDao.findAllByAreaIdIn(areaIds);
        list.add(units);
        return list;
    }

    @Override
    public UnitsPage selectPage(Integer page, Integer size) {
        Pageable pageable = PageRequest.of(page, size, Sort.Direction.ASC, "level");
        Page<Units> unitsPage = unitsDao.findAll(pageable);
        List<Units> list = unitsPage.getContent();
        list.forEach(units -> {
            if (units.getAreaId() > 0) {
                units.setAreaName(areaDao.findById(units.getAreaId()).get().getName());
            } else if (units.getType() == 2) {
                units.setAreaName("浙江省");
            } else {
                units.setAreaName("-");
            }
        });
        return UnitsPage.builder().data(list)
                .page(page)
                .size(size)
                .total(Math.toIntExact(unitsPage.getTotalElements()))
                .build();
    }

    @Override
    public List<Units> findByUserIdUnitsTrainListVo(Integer unitsId) {
        Optional<Units> unitsOptional = unitsDao.findById(unitsId);
        if (unitsOptional.isPresent()) {
            Units units = unitsOptional.get();
            List<Integer> areaIds = areaDao.findAllByFatherId(units.getAreaId()).stream().filter(area -> area.getType() <= 3).map(Area::getId).collect(Collectors.toList());
            List<Units> unitsList = unitsDao.findAllByAreaIdIn(areaIds);
            unitsList.add(units);
            return unitsList;
        } else {
            throw new ApiException(ResponseEntity.status(500).body("单位没有查到"));
        }
    }

    @Override
    public List<Units> findAllByIdIn(List<Integer> ids) {
        return unitsDao.findAllById(ids);
    }

    @Override
    public List<Units> finAllDirectlUnderUnits() {
        return unitsDao.findAllByType(2);
    }

    @Override
    public LeftNavigation findLeftNavigation(SecurityUser securityUser) {
        LeftNavigation leftNavigation = new LeftNavigation();
        List<LeftNavigation> leftNavigationList = new ArrayList<>();
        Units units=securityUser.getCurrentUserInfo().getUnits();
        if (units.getLevel()==1 || units.getLevel()==2){
            AreaExhibition areaExhibition=areaExhibitionCache.findById(units.getExhibitionId());
            AreaExhibition areaExhibitionParent=areaExhibitionCache.findById(areaExhibition.getFatherId());
            leftNavigation=areaExhibitionParent.toLeftNavigation();
            //根据上级展示区域id查询所有的下级区域展示对象
            List<AreaExhibition> areaExhibitions= areaExhibitionCache.findByFatherId(areaExhibitionParent.getId());
            for (AreaExhibition areaEx:areaExhibitions){
                //生成以及新的展示区域 LeftNavigation type =1
                LeftNavigation leftNavigation1 = areaEx.toLeftNavigation();
                //根据区域展示ID查询相关的单位且转成单位LeftNavigation type =2
                List<LeftNavigation> leftNavigationList1=unitsCache.findAllByAreaExhibitionId(areaEx.getId()).stream().map(Units::toLeftNavigation).collect(Collectors.toList());
                leftNavigation1.setLeftNavigations(leftNavigationList1);
                //最大的一级LeftNavigation 进行附值
                leftNavigationList.add(leftNavigation1);
                leftNavigation.setLeftNavigations(leftNavigationList);
            }
        }else {
            leftNavigation= units.toLeftNavigation();
            leftNavigation.setLeftNavigations(leftNavigationList);
        }
        return leftNavigation;
    }


    @Override
    public LeftNavigation findLeftNavigation1(SecurityUser securityUser) {
        LeftNavigation leftNavigation = new LeftNavigation();
        List<LeftNavigation> leftNavigationList = new ArrayList<>();
        Integer areaId = securityUser.getCurrentUserInfo().getUnits().getAreaId();
        Area belongsArea = areaDao.findById(areaId).get();
        if (belongsArea.getType() == 1) {
            leftNavigation = belongsArea.toLeftNavigation();
            LeftNavigation units = securityUser.getCurrentUserInfo().getUnits().toLeftNavigation();
            List<LeftNavigation> leftNavigationList1 = new ArrayList<>();
            systemConfigService.getStorageLocationMap().forEach(
                    (k, v) -> {
                        leftNavigationList1.add(new LeftNavigation(0, v, null, v, 3, k, units.getId()));
                    }
            );
            units.setLeftNavigations(leftNavigationList1.stream().sorted(Comparator.comparing(LeftNavigation::getOrder, Comparator.nullsLast(Integer::compareTo))).collect(Collectors.toList()));
            leftNavigationList.add(units);
            //把省直属组合一下 直属单位（type=2） 处室单位（type=4）
//            leftNavigationList.addAll(unitsDao.findAllByType(4).stream().map(Units::toLeftNavigation).collect(Collectors.toList()));
            List<LeftNavigation> leftNavigationList2 = unitsDao.findAllByType(2).stream().filter(units1 -> !units1.getName().equals("省应急小组") && !units1.getName().equals("省机科技管理处") && !units1.getName().equals("省机通信报务处") && units1.getEscrow() == 1).map(Units::toLeftNavigation).collect(Collectors.toList());
            LeftNavigation leftNavigation2 = new LeftNavigation(0, "省直属", leftNavigationList2, UUID.randomUUID().toString(), 1, 22, null);
            leftNavigationList.add(leftNavigation2);
        }
        if (belongsArea.getType() == 2) {
            leftNavigation = belongsArea.toLeftNavigation();
            leftNavigationList = unitsDao.findAllByAreaId(belongsArea.getId()).stream().map(Units::toLeftNavigation).collect(Collectors.toList());
        }
        List<Area> areas = areaDao.findAllByFatherId(areaId).stream().filter(area -> area.getType() <= 3).collect(Collectors.toList());
        if (areas.size() != 0) {
            provinceAndCity(belongsArea, areas, leftNavigationList);
        } else {
            leftNavigation = belongsArea.toLeftNavigation();
            leftNavigationList = unitsDao.findAllByAreaId(belongsArea.getId()).stream().map(Units::toLeftNavigation).collect(Collectors.toList());
        }

        leftNavigation.setLeftNavigations(leftNavigationList.stream().sorted(Comparator.comparing(LeftNavigation::getOrder, Comparator.nullsLast(Integer::compareTo))).collect(Collectors.toList()));

        return leftNavigation;
    }


    @Override
    public LeftNavigation findLeftNavigation2(SecurityUser securityUser) {
        List<LeftNavigation> leftNavigationList2 = unitsDao.findAllByType(2).stream().filter(units1 -> !units1.getName().equals("省机科技管理处") && !units1.getName().equals("省机通信报务处") && units1.getEscrow() == 1).map(Units::toLeftNavigation).collect(Collectors.toList());
        LeftNavigation leftNavigation2 = new LeftNavigation(0, "省直属", leftNavigationList2, UUID.randomUUID().toString(), 1, 22, null);
        return leftNavigation2;
    }


    @Override
    public LeftNavigation findLeftNavigationNotDirectlyUnit(SecurityUser securityUser) {
        LeftNavigation leftNavigation = new LeftNavigation();
        List<LeftNavigation> leftNavigationList = new ArrayList<>();
        Integer areaId = securityUser.getCurrentUserInfo().getUnits().getAreaId();
        Area belongsArea = areaDao.findById(areaId).get();
        if (belongsArea.getType() == 1 || belongsArea.getType() == 2) {
            leftNavigation = belongsArea.toLeftNavigation();
            List<LeftNavigation> leftNavigationList1 = new ArrayList<>();
            unitsDao.findAllByAreaId(belongsArea.getId()).forEach(
                    units -> {
                        LeftNavigation leftNavigation1 = units.toLeftNavigation();
                        leftNavigation1.setTheirId(belongsArea.getId());
                        leftNavigationList1.add(leftNavigation1);
                    }

            );
            leftNavigationList = leftNavigationList1;

        }
        List<Area> areas = areaDao.findAllByFatherId(areaId).stream().filter(area -> area.getType() <= 3).collect(Collectors.toList());
        if (areas.size() != 0) {
            provinceAndCity(belongsArea, areas, leftNavigationList);
        } else {
            leftNavigation = belongsArea.toLeftNavigation();
            List<LeftNavigation> leftNavigationList1 = new ArrayList<>();
            unitsDao.findAllByAreaId(belongsArea.getId()).forEach(
                    units -> {
                        LeftNavigation leftNavigation1 = units.toLeftNavigation();
                        leftNavigation1.setTheirId(belongsArea.getId());
                        leftNavigationList1.add(leftNavigation1);
                    }

            );
            leftNavigationList = leftNavigationList1;
        }

        leftNavigation.setLeftNavigations(leftNavigationList.stream().sorted(Comparator.comparing(LeftNavigation::getOrder, Comparator.nullsLast(Integer::compareTo))).collect(Collectors.toList()));

        return leftNavigation;
    }

    @Override
    public List<Units> findSuperiorUnitsList() {

        return unitsDao.findAllByType(3);
    }

    @Override
    public List<Units> findDirectlyUnder() {
        List<Units> unitsList = unitsDao.findAllByType(2);
        unitsList.addAll(unitsDao.findAllByType(4));
        return unitsList;
    }


    @Override
    public List<Units> findSubordinateList(Integer unitsId) {
        Units units = unitsDao.findById(unitsId).get();
        List<Integer> areaIds = areaDao.findAllByFatherId(units.getAreaId()).stream().filter(area -> area.getType() <= 3).map(Area::getId).collect(Collectors.toList());
        return unitsDao.findAllByAreaIdIn(areaIds);
    }

    @Override
    public Units findNameUnit(UnitNameVo unitNameVo) {
        return unitsDao.findByName(unitNameVo.getUnitName());
    }

    @Override
    public void addUnitSortMap() {
        DeviceModelSort.mapUnitSort = unitsDao.findAll().stream().collect(Collectors.toMap(Units::getName, Units::getShowOrder));
        DeviceModelSort.mapUnitNameToDisName = unitsDao.findAll().stream().collect(Collectors.toMap(Units::getName, Units::getUnitDesc));
    }

    /**
     * 判断该unit是否是省本级单位
     *
     * @param unitId 单位主键id
     * @return true = 省本级单位 , false = 不是省本级单位
     */
    @Override
    public boolean isProvUnit(Integer unitId) {
        Units units = unitsDao.findById(unitId).get();
        if (units.getLevel() == 1 && units.getType() == 1) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public List<Integer> findByAreaId2(Integer areaId) {
        return unitsDao.findByAreaId(areaId).stream().map(Units::getUnitId).distinct().collect(Collectors.toList());
    }

    @Override
    public List<Units> unitManagement() {
        List<Units> unitsList=unitsDao.findAll();
        unitsList.forEach(
                units -> {
                   AreaExhibition areaExhibition = areaExhibitionService.findById(units.getExhibitionId());
                   units.setAreaName(areaExhibition.getAreaName());
                   //查询当前单位的逻辑区域
                     Units units1=findByParentUnit(units);
                  if (units1!=null){
                      units.setParentUnitId(units1.getUnitId());
                  }
                }
        );
        unitsList= unitsList.stream().sorted(Comparator.comparing(Units::getShowOrder)).collect(Collectors.toList());
        return unitsList;
    }

    @Override
    public List<Units> saveUnits(UnitsAddVo unitsAddVo) {
        Units units= unitsAddVo.toUnits();
        //查询上级设备的单位
        Units parentUnits=unitsCache.findById(unitsAddVo.getParentUnitId());
        //查询上级的设备的区域a
        Area ParentArea=areaCache.findById(parentUnits.getAreaId());
        //创建一个区域b 上级id为a
        Area area =new Area();
        area.setFatherId(ParentArea.getId());
        area.setOrders("999");
        area.setName(unitsAddVo.getName());
        area.setType(unitsAddVo.getLevel());
        area= areaDao.save(area);
        //创建单位ub 区域id绑定为b
        units.setAreaId(area.getId());
        units.setType(levelToType(unitsAddVo.getLevel()));
        units.setShowOrder(unitsCache.findAll().size()+1);
        unitsDao.save(units);
        unitsCache.refresh(unitsDao.findAll());
        areaCache.refresh(areaDao.findAll());
        return unitsCache.findAll();
    }

    @Override
    public List<Units> belongsUnits() {
        return unitsDao.findAll().stream().filter(units -> units.getLevel()==1 || units.getLevel()==2).sorted(Comparator.comparing(Units::getShowOrder)).collect(Collectors.toList());
    }

    private Units findByParentUnit(Units units){
        Area area=areaCache.findById(units.getAreaId());
        if (area.getFatherId()!=null){
            Area area1=areaCache.findById(area.getFatherId());
            return unitsCache.findByAreaId(area1.getId());
        }else {
            return null;
        }
    }
    @Override
    public Units updateUnit(Units units) {
        Units unitsOld=unitsCache.findById(units.getUnitId());
        if (!units.getLevel().equals(unitsOld.getLevel())){
            units.setType(levelToType(units.getLevel()));
        }
        Units parentUnitOld= findByParentUnit(units);
        if (units.getParentUnitId()!=null){
           if (parentUnitOld==null ||!parentUnitOld.getUnitId().equals(units.getParentUnitId())){
               //查询需要修改的上级id
               Units parentUnitNow = unitsCache.findById(units.getParentUnitId());
               Area newArea = areaCache.findById(parentUnitNow.getAreaId());
               Area oldArea = areaCache.findById(unitsOld.getAreaId());
               oldArea.setFatherId(newArea.getId());
               areaDao.save(oldArea);
           }
        }else {
            if (parentUnitOld!=null){
                Area oldArea = areaCache.findById(unitsOld.getAreaId());
                oldArea.setFatherId(null);
                areaDao.save(oldArea);
            }
        }
        if (!unitsOld.getShowOrder().equals(units.getShowOrder())){
            int count=unitsCache.findAll().size();
            if (units.getShowOrder()>count){
                units.setShowOrder(count+1);
            }else {
                sortingUnit(unitsOld.getShowOrder(),units.getShowOrder());
            }
        }
        unitsDao.save(units);
        unitsCache.refresh(unitsDao.findAll());
        areaCache.refresh(areaDao.findAll());
        return units;
    }

    private void sortingUnit(Integer originalOrder,Integer newOrder){
        List<Units> unitsList;
        if (originalOrder>newOrder){
            unitsList=unitsCache.findListGeNewAndLtOriginal(newOrder,originalOrder);
            unitsList.forEach(
                    units -> units.setShowOrder(units.getShowOrder()+1)
            );
        }else {
            unitsList=unitsCache.findListLgOriginalAndLeNew(newOrder,originalOrder);
            unitsList.forEach(
                    units -> units.setShowOrder(units.getShowOrder()-1)
            );
        }
        unitsCache.refresh(unitsDao.saveAll(unitsList));
    }



    /**
     * 工具类
     * @return 单位类型
     */
    private Integer levelToType(Integer level){
        switch (level){
            case 0:
                return 3;
            case 1:
                return 2;
            case 2:
                return 1;
            case 3:
                return 1;
            case 4:
                return 2;
                default:
                    return null;
        }
    }

    @Override
    public Units save(Units units) {
        if (units.getAreaId() != null && units.getAreaId() != 0) {
            Optional<Area> optionalArea = areaDao.findById(units.getAreaId());
            if (optionalArea.isPresent()) {
                units.setLevel(optionalArea.get().getType());
//                units.setType(1);
            } else {
                throw new ApiException(ResponseEntity.ok("[单位] 没找到对应的区域，请检查"));
            }
        } else {
            units.setLevel(4);
            units.setType(3);
        }
        Integer maxShowCode = unitsDao.findTopByOrderByShowOrderDesc().getShowOrder();
        units.setShowOrder(maxShowCode + 1);
        Units units1 = unitsDao.save(units);
        unitsCache.refresh(unitsDao.findAll());
        return units1;
    }

    @Override
    public boolean delete(Integer id) {
        unitsDao.deleteById(id);
        unitsCache.refresh(unitsDao.findAll());
        return true;
    }

    @Override
    public List<Units> findAll() {
        return unitsDao.findAll();
    }

    @Override
    public Units update(Units units) {
        Units units1 = unitsDao.save(units);
        unitsCache.refresh(unitsDao.findAll());
        return units1;
    }
}
