package org.jeecg.modules.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.base.service.BaseCommonService;
import org.jeecg.modules.system.constant.SendChangeMsgConstant;
import org.jeecg.modules.system.entity.SysArea;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.enums.AreaEnum;
import org.jeecg.modules.system.service.ISysAreaService;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysTenantService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.system.vo.SysAreaVo;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Description: sys_area
 * @Author: jeecg-boot
 * @Date: 2022-01-05
 * @Version: V1.0
 */
@Api(tags = "区划管理")
@RestController
@RequestMapping("/gtSysArea")
@Slf4j
public class SysAreaController extends JeecgController<SysArea, ISysAreaService> {
    @Autowired
    private ISysAreaService sysAreaService;
    @Autowired
    private ISysBaseAPI sysBaseAPI;
    @Resource
    private BaseCommonService baseCommonService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysTenantService tenantService;
    @Autowired
    private ISysDepartService sysDepartService;

    /**
     * 分页列表查询
     *
     * @param sysArea
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "sys_area-分页列表查询")
    @ApiOperation(value = "sys_area-分页列表查询", notes = "sys_area-分页列表查询")
    @GetMapping(value = "/rootList")
    public Result<?> queryPageList(SysArea sysArea,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        //获取当前用户信息和角色信息
        //直接获取当前用户不适用前端token
        List<SysArea> list = new ArrayList<>();
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //获取用户权限信息
        Map<String, Object> userOtherInfo = sysUserService.getUserOtherInfo(loginUser);
        if (userOtherInfo == null) {
            return Result.OK(list);
        }
        Boolean isAreaAdmin = (Boolean) userOtherInfo.get("isAreaAdmin");
        Boolean isDeptAdmin = (Boolean) userOtherInfo.get("isDeptAdmin");
        Boolean isBasicOperation = (Boolean) userOtherInfo.get("isBasicOperation");
        Boolean isAdmin = (Boolean) userOtherInfo.get("isAdmin");
        SysDepart currentDept = (SysDepart) userOtherInfo.get("currentDept");
        SysArea currentArea = (SysArea) userOtherInfo.get("currentArea");

        String hasQuery = req.getParameter("hasQuery");
        if (hasQuery != null && "true".equals(hasQuery)) {
            QueryWrapper<SysArea> queryWrapper = QueryGenerator.initQueryWrapper(sysArea, req.getParameterMap());
            list = sysAreaService.queryTreeListNoPage(queryWrapper);
            IPage<SysArea> pageList = new Page<>(1, 10, list.size());
            pageList.setRecords(list);
            return Result.OK(pageList);
        } else {
            String parentId = sysArea.getParentId();
            if (oConvertUtils.isEmpty(parentId)) {
                parentId = "0";
            }
            sysArea.setParentId(null);
            QueryWrapper<SysArea> queryWrapper = QueryGenerator.initQueryWrapper(sysArea, req.getParameterMap());
            queryWrapper.eq("status", "1");
            // 使用 eq 防止模糊查询..只能查询比小于自己层级+1的区划
            if (!isAdmin && !isBasicOperation) {
                //不是admin只能查看从自己层级开始的。如果parentId为空则获取自己所在的区划
                if ("0".equals(parentId)) {
                    queryWrapper.eq("id", currentArea.getId()).orderByAsc("area_order");
                } else {
                    queryWrapper.eq("parent_id", parentId).orderByAsc("area_order");
                }
                //区划管理员权限省级是2，如果要看市级的要+2
                if (isAreaAdmin) {
                    queryWrapper.le("area_level", Integer.parseInt(currentArea.getAreaLevel()) + 2);
                } else {
                    if (isDeptAdmin) {
                        //部门管理员，只能看到自己的区划
                        queryWrapper.lt("area_level", Integer.parseInt(currentArea.getAreaLevel()) + 1);
                    }
                    if (!isDeptAdmin) {
                        queryWrapper.lt("area_level", Integer.parseInt(currentArea.getAreaLevel()) + 1);
                    }
                }
            } else {
                queryWrapper.eq("parent_id", parentId).orderByAsc("area_order");
            }
            //queryWrapper.orderByAsc("area_order");
            //Page<SysArea> page = new Page<SysArea>(pageNo, pageSize);
            //IPage<SysArea> pageList = sysAreaService.page(page, queryWrapper);
            if (isAreaAdmin && !isBasicOperation && !isAdmin) {
                if (!"0".equals(parentId)) {
                    list = sysAreaService.list(queryWrapper);
                    return Result.OK(list);
                }
                String[] parentIdPath = sysAreaService.findParentIdPath(currentArea.getId());
                List<SysArea> collect = null;
                for (int i = parentIdPath.length - 1; i >= 0; i--) {
                    if (i == parentIdPath.length - 1) {
                        SysArea area = sysAreaService.getById(parentIdPath[i]);
                        area.setChildren(list);
                        collect = Stream.of(area).collect(Collectors.toList());
                    }
                    if (i < parentIdPath.length - 1) {
                        SysArea area = sysAreaService.getById(parentIdPath[i]);
                        area.setChildren(collect);
                        collect = Stream.of(area).collect(Collectors.toList());
                    }
                }
                return Result.OK(collect);
            } else if (isDeptAdmin && !isBasicOperation && !isAdmin) {
                if (!"0".equals(parentId)) {
                    list = sysAreaService.list(queryWrapper);
                    return Result.OK(list);
                }
//				String[] parentIdPathName = sysAreaService.findParentIdPathName(currentArea.getId());
//				List<String> strings = Arrays.asList(parentIdPathName);
                String[] parentIdPath = sysAreaService.findParentIdPath(currentArea.getId());
                List<SysArea> collect = null;
                for (int i = parentIdPath.length - 1; i >= 0; i--) {
                    if (i == parentIdPath.length - 1) {
                        SysArea byId = sysAreaService.getById(parentIdPath[i]);
                        byId.setChildren(list);
                        collect = Stream.of(byId).collect(Collectors.toList());
                    }
                    if (i < parentIdPath.length - 1) {
                        SysArea byId = sysAreaService.getById(parentIdPath[i]);
                        byId.setChildren(collect);
                        collect = Stream.of(byId).collect(Collectors.toList());
                    }
                }
                return Result.OK(collect);
            } else if (!isAdmin && !isBasicOperation) {
                if (!"0".equals(parentId)) {
                    list = sysAreaService.list(queryWrapper);
                    return Result.OK(list);
                }
//				String[] parentIdPathName = sysAreaService.findParentIdPathName(currentArea.getId());
//				List<String> strings = Arrays.asList(parentIdPathName);
                String[] parentIdPath = sysAreaService.findParentIdPath(currentArea.getId());
                List<SysArea> collect = null;
                for (int i = parentIdPath.length - 1; i >= 0; i--) {
                    if (i == parentIdPath.length - 1) {
                        SysArea byId = sysAreaService.getById(parentIdPath[i]);
                        byId.setChildren(list);
                        collect = Stream.of(byId).collect(Collectors.toList());
                    }
                    if (i < parentIdPath.length - 1) {
                        SysArea byId = sysAreaService.getById(parentIdPath[i]);
                        byId.setChildren(collect);
                        collect = Stream.of(byId).collect(Collectors.toList());
                    }
                }
                return Result.OK(collect);
            } else {
                list = sysAreaService.list(queryWrapper);
            }
            return Result.OK(list);
        }
    }

    @AutoLog(value = "sys_area-通过id查询子元素")
    @ApiOperation(value = "sys_area-通过id查询子元素", notes = "sys_area-通过id查询子元素")
    @GetMapping(value = "/queryChildById")
    public Result<?> queryChildById() {
        List<SysArea> entities = sysAreaService.listWithTreeById();
        return Result.OK(entities);
    }

    @AutoLog(value = "sys_area-区划树查询")
    @ApiOperation(value = "sys_area-区划树查询", notes = "sys_area-区划树查询")
    @GetMapping(value = "/allList")
    public Result<?> queryPageList() {
        List<SysArea> collect = sysAreaService.getAllChild();
        return Result.OK(collect);
    }

    @AutoLog(value = "sys_area-组织机构树")
    @ApiOperation(value = "sys_area-组织机构树", notes = "sys_area-组织机构树")
    @GetMapping(value = "/departAllList")
    public Result<?> queryDepartPageList() {
        List<SysArea> collect = sysAreaService.getDepartAllChild();
        return Result.OK(collect);
    }

    @AutoLog(value = "sys_area-全部条件查询")
    @ApiOperation(value = "sys_area-全部条件查询", notes = "sys_area-全部条件查询")
    @GetMapping(value = "/queryList")
    public Result<?> queryList() {
        List<SysArea> entities = sysAreaService.listWithTreeByNameAndCode();
        return Result.OK(entities);
    }

    /**
     * 获取子数据
     *
     * @param sysArea
     * @param req
     * @return
     */
    @AutoLog(value = "sys_area-获取子数据")
    @ApiOperation(value = "sys_area-获取子数据", notes = "sys_area-获取子数据")
    @GetMapping(value = "/childList")
    public Result<?> queryPageList(SysArea sysArea, HttpServletRequest req) {
        System.out.println("sysArea" + sysArea);
        System.out.println("req" + req.toString());
        QueryWrapper<SysArea> queryWrapper = QueryGenerator.initQueryWrapper(sysArea, req.getParameterMap());
        List<SysArea> list = sysAreaService.list(queryWrapper);
        IPage<SysArea> pageList = new Page<>(1, 10, list.size());
        pageList.setRecords(list);
        return Result.OK(pageList);
    }

    /**
     * 批量查询子节点
     *
     * @param parentIds 父ID（多个采用半角逗号分割）
     * @param parentIds
     * @return 返回 IPage
     * @return
     */
    @AutoLog(value = "sys_area-批量获取子数据")
    @ApiOperation(value = "sys_area-批量获取子数据", notes = "sys_area-批量获取子数据")
    @GetMapping("/getChildListBatch")
    public Result getChildListBatch(@RequestParam("parentIds") String parentIds) {
        try {
            QueryWrapper<SysArea> queryWrapper = new QueryWrapper<>();
            List<String> parentIdList = Arrays.asList(parentIds.split(","));
            queryWrapper.in("parent_id", parentIdList);
            List<SysArea> list = sysAreaService.list(queryWrapper);
            IPage<SysArea> pageList = new Page<>(1, 10, list.size());
            pageList.setRecords(list);
            return Result.OK(pageList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("批量查询子节点失败：" + e.getMessage());
        }
    }

    /**
     * 添加
     *
     * @param sysArea
     * @return
     */
    @AutoLog(value = "sys_area-添加")
    @ApiOperation(value = "sys_area-添加", notes = "sys_area-添加")
    @PostMapping(value = "/add")
    @Transactional
    public Result<?> add(@RequestBody SysArea sysArea, HttpServletRequest request) {
        String id = sysArea.getParentId();
        String[] path = sysAreaService.findParentIdPath(id);
        if (path.length == 1) {
            sysArea.setProvince(path[0]);
        } else if (path.length == 2) {
            sysArea.setProvince(path[0]);
            sysArea.setCity(path[1]);
        } else if (path.length == 3) {
            sysArea.setProvince(path[0]);
            sysArea.setCity(path[1]);
            sysArea.setCounty(path[2]);
        } else if (path.length == 4) {
            sysArea.setProvince(path[0]);
            sysArea.setCity(path[1]);
            sysArea.setCounty(path[2]);
            sysArea.setTown(path[3]);
        }
        SysArea sysArea1 = sysAreaService.getById(sysArea.getParentId());
        sysArea.setParentAreaName(sysArea1.getAreaName());
        sysArea.setAreaLevel("".equals(sysArea.getParentId()) ? "2" : String.valueOf(Integer.parseInt(sysArea1.getAreaLevel()) + 1));
        sysArea.setStatus("1");
        sysArea.setDelFlag(0);
        SysArea one = sysAreaService.getOne(new QueryWrapper<SysArea>().eq("area_code", sysArea.getAreaCode()).eq("status", "1"));
        if (!oConvertUtils.isEmpty(one)) {
            return Result.error(AreaEnum.AREA_CODE18005.getCode(), AreaEnum.AREA_CODE18005.getMsg());
        } else {
            sysAreaService.addSysArea(sysArea);
        }
        SysArea one1 = sysAreaService.getOne(new QueryWrapper<SysArea>().eq("area_code", sysArea.getAreaCode()).eq("status", "1"));
        sysArea.setId(one1.getId());
        tenantService.sendAreaMsg(sysArea, SendChangeMsgConstant.INSERT);

        String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
        String username = JwtUtil.getUsername(token);
        LoginUser sysUser = sysBaseAPI.getUserByName(username);
        baseCommonService.addLog("用户名: " + sysUser.getRealname() +
                        ",在sys_area表中添加了" + sysArea, CommonConstant.LOG_TYPE_2,
                CommonConstant.OPERATE_TYPE_2, sysUser);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param sysArea
     * @return
     */
    @AutoLog(value = "sys_area-编辑")
    @ApiOperation(value = "sys_area-编辑", notes = "sys_area-编辑")
    @PutMapping(value = "/edit")
    @Transactional
    public Result<?> edit(@RequestBody SysArea sysArea) {
        SysArea sysAreaEntity = sysAreaService.getById(sysArea.getId());
        if (oConvertUtils.isEmpty(sysAreaEntity)) {
            Result.error(500, "未找到对应实体");
        } else {
            if ("0".equals(sysArea.getStatus()) && "1".equals(sysAreaEntity.getStatus())) {
                sysAreaService.changeRelatedStatus(sysArea.getId(), sysArea.getStatus());
            }
            if (!"0".equals(sysArea.getStatus())) {
                SysArea area = sysAreaService.getOne(new QueryWrapper<SysArea>().eq("area_code", sysArea.getAreaCode()).eq("status", 1));
                if (!oConvertUtils.isEmpty(area) && !sysArea.getAreaCode().equals(sysAreaEntity.getAreaCode())) {
                    return Result.error(AreaEnum.AREA_CODE18005.getCode(), AreaEnum.AREA_CODE18005.getMsg());
                }
                if (!oConvertUtils.isEmpty(area) && !sysArea.getId().equals(area.getId())) {
                    return Result.error(AreaEnum.AREA_CODE18005.getCode(), AreaEnum.AREA_CODE18005.getMsg());
                }
            }
            sysAreaService.changeRelatedArea(sysArea, sysAreaEntity);
            sysAreaService.updateSysArea(sysArea);
            tenantService.sendAreaMsg(sysArea, SendChangeMsgConstant.UPDATE);
            return Result.OK("编辑成功");
        }
        return Result.error("编辑失败");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "sys_area-通过id删除")
    @ApiOperation(value = "sys_area-通过id删除", notes = "sys_area-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id") String id, HttpServletRequest request) {
        sysAreaService.deleteSysArea(id);
        String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
        String username = JwtUtil.getUsername(token);
        LoginUser sysUser = sysBaseAPI.getUserByName(username);
        baseCommonService.addLog("用户名: " + sysUser.getRealname() +
                        ",删除了sys_area表的" + id + "字段", CommonConstant.LOG_TYPE_2,
                CommonConstant.OPERATE_TYPE_4, sysUser);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "sys_area-批量删除")
    @ApiOperation(value = "sys_area-批量删除", notes = "sys_area-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids, HttpServletRequest request) {
        this.sysAreaService.removeByIds(Arrays.asList(ids.split(",")));
        String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
        String username = JwtUtil.getUsername(token);
        LoginUser sysUser = sysBaseAPI.getUserByName(username);
        baseCommonService.addLog("用户名: " + sysUser.getRealname() +
                        ",删除了sys_area表的" + ids + "字段", CommonConstant.LOG_TYPE_2, CommonConstant.OPERATE_TYPE_4
                , sysUser);
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     */
    @AutoLog(value = "sys_area-通过id查询")
    @ApiOperation(value = "sys_area-通过id查询", notes = "sys_area-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id") String id) {
        SysArea sysArea = sysAreaService.getById(id);
        if (sysArea == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(sysArea);
    }

    /**
     * 通过区域名称和区域代码查询
     *
     * @param areaName
     * @param areaCode
     * @return
     */
    @AutoLog(value = "sys_area-通过区域名称和区域代码查询")
    @ApiOperation(value = "sys_area-通过区域名称和区域代码查询", notes = "sys_area-通过区域名称和区域代码查询")
    @GetMapping(value = "/queryByNameAndCode")
    public Result<?> queryByname(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                 String areaName, String areaCode, Integer isSpecial, String status) {
        IPage<SysArea> list = sysAreaService.queryPage(pageNo, pageSize, areaName, areaCode, isSpecial, status);
        return Result.OK(list);
    }

    @AutoLog(value = "sys_area-权限区域名称查询")
    @ApiOperation(value = "sys_area-权限区域名称查询", notes = "sys_area-权限区域名称查询")
    @GetMapping(value = "/queryByKey")
    public Result<?> queryByKey(String areaName) {
        List<SysArea> list = new ArrayList<>();
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //获取用户权限信息
        Map<String, Object> userOtherInfo = sysUserService.getUserOtherInfo(loginUser);
        if (userOtherInfo == null) {
            return Result.OK(list);
        }
        Boolean isAreaAdmin = (Boolean) userOtherInfo.get("isAreaAdmin");
        Boolean isBasicOperation = (Boolean) userOtherInfo.get("isBasicOperation");
        Boolean isDeptAdmin = (Boolean) userOtherInfo.get("isDeptAdmin");
        Boolean isAdmin = (Boolean) userOtherInfo.get("isAdmin");
        SysDepart currentDept = (SysDepart) userOtherInfo.get("currentDept");
        SysArea currentArea = (SysArea) userOtherInfo.get("currentArea");

        if (!isAdmin && !isBasicOperation) {
            if (isAreaAdmin) {
                List<String> areaList = sysAreaService.quickGetChild(currentArea.getId());
                areaList.add(currentArea.getId());
                String[] parentIdPath = sysAreaService.findParentIdPath(currentArea.getId());
                List<String> asList = Arrays.asList(parentIdPath);
                areaList.addAll(asList);
                return getResult(areaName, areaList);
            } else {
                return getAreaResult(areaName, currentArea);
            }
        } else {
            List<SysArea> areaList = sysAreaService.list(new QueryWrapper<SysArea>().like("area_name", areaName).eq("status", 1));
            if (!oConvertUtils.isEmpty(areaList) && areaList.size() > 0) {
                return Result.OK(areaList);
            } else {
                return Result.error("暂⽆相关结果");
            }
        }
    }

    @NotNull
    private Result<?> getAreaResult(String areaName, SysArea currentArea) {
        String[] parentIdPath = sysAreaService.findParentIdPath(currentArea.getId());
        List<String> asList = Arrays.asList(parentIdPath);
        return getResult(areaName, asList);
    }

    @NotNull
    private Result<?> getResult(String areaName, List<String> areaList) {
        List<SysArea> id = sysAreaService.list(new QueryWrapper<SysArea>().like("area_name", areaName).eq("status", 1).in("id", areaList));
        if (!oConvertUtils.isEmpty(id) && id.size() > 0) {
            return Result.OK(id);
        } else {
            return Result.error("暂⽆相关结果");
        }
    }

    /**
     * 导出excel
     *
     * @param request
     * @param sysArea
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, SysArea sysArea) {
        return super.exportXls(request, sysArea, SysArea.class, "sys_area");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, SysArea.class);
    }

    /**
     * 通过下拉搜索获取数据
     */
    @ApiOperation(value = "下拉搜索区划接口", notes = "sys_area-添加")
    @RequestMapping(value = "/findArea", method = RequestMethod.GET)
    public Result<?> findArea(@ApiParam(name = "areaName", value = "区划名称", defaultValue = "") @RequestParam(value = "areaName", defaultValue = "") String areaName, @ApiParam(name = "limit", value = "限制多少条", defaultValue = "10") @RequestParam(value = "limit", defaultValue = "10") String limit) {
        QueryWrapper<SysArea> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isEmpty(limit)) {
            queryWrapper.last(" limit 10");
        } else {
            int i = Integer.parseInt(limit);
            i = i > 100 ? 100 : i;
            queryWrapper.last(" limit " + i);
        }
        if (!StringUtils.isEmpty(areaName)) {
            queryWrapper.like("area_name", areaName);
        }
        List<SysArea> list = sysAreaService.list(queryWrapper);
        return Result.OK(list);
    }

    /**
     * 当前用户所在区县以及以下区县
     */
    @ApiOperation(value = "监测用户区划信息")
    @RequestMapping(value = "/userAuthArea", method = RequestMethod.GET)
    public Result<?> userAuthArea() {
        List<SysArea> areaTree = new ArrayList<>();
        SysArea root = new SysArea();
        root.setAreaName("全部");
        root.setAreaCode("all");
        root.setParentId("0");

        areaTree.add(root);//新增一个全部
        //获取当前用户所在区划
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //获取用户部门信息
        SysDepart userDept = sysDepartService.getDeptByUserId(loginUser.getId());
        if (userDept == null || userDept.getAreaId() == null) {
            return Result.error("部门信息或部门所在区划信息为空");
        }
        //通过部门信息获取区划信息
        SysArea userArea = sysAreaService.getById(userDept.getAreaId());
        if (userArea == null || userArea.getAreaLevel() == null) {
            return Result.error("区划信息或区划层级为空");
        }

        areaTree.add(userArea);//本级加入到列表

        List<SysArea> sunAreaList = sysAreaService.getChildArea(userArea.getId());
        if (userArea.getAreaLevel().equals("2")) {//省级别
            //要获取下面的市级区划信息
            areaTree.addAll(sunAreaList);
        }else{
            userArea.setChildren(sunAreaList);
        }
        return Result.OK(areaTree);
    }


    /**
     * 当前用户所在区县以及以下区县
     */
    @ApiOperation(value = "区划下拉筛选")
    @RequestMapping(value = "/userAuthAreaSelect", method = RequestMethod.GET)
    public Result<?> userAuthAreaSelect() {
        List<SysArea> areaTree = new ArrayList<>();

        //获取当前用户所在区划
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //获取用户部门信息
        SysDepart userDept = sysDepartService.getDeptByUserId(loginUser.getId());
        if (userDept == null || userDept.getAreaId() == null) {
            return Result.error("部门信息或部门所在区划信息为空");
        }
        //通过部门信息获取区划信息
        SysArea userArea = sysAreaService.getById(userDept.getAreaId());
        if (userArea == null || userArea.getAreaLevel() == null) {
            return Result.error("区划信息或区划层级为空");
        }

        areaTree.add(userArea);//本级加入到列表

        List<SysArea> sunAreaList = sysAreaService.getChildArea(userArea.getId());
        userArea.setChildren(sunAreaList);
        return Result.OK(areaTree);
    }
}
