package com.ruoyi.web.controller.grid;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.zqt.ZQTImportExcelUtil;
import com.ruoyi.system.domain.grid.*;
import com.ruoyi.system.domain.grid.vo.GridDxbVO;
import com.ruoyi.system.domain.grid.vo.GridTreeNode;
import com.ruoyi.system.domain.video.ext.Position;
import com.ruoyi.system.mapper.grid.GridRegionMapper;
import com.ruoyi.system.service.grid.GridRegionFacadeService;
import com.ruoyi.system.service.grid.GridRegionService;
import com.ruoyi.system.service.grid.GridRegionUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Auther: hxc
 * @Date: 2019/2/28 0028 14:09
 * @Description: 网格信息表
 */
@Api(tags = "网格管理 - 网格信息管理")
@RestController
@RequestMapping("/api/grid/region")
public class RegionController extends BaseController {

    @Autowired
    private GridRegionFacadeService gridRegionFacadeService;
    @Autowired
    private GridRegionService gridRegionService;

    @Autowired
    private GridRegionMapper gridRegionMapper;
    @Autowired
    private GridRegionUserService gridRegionUserService;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public String list(@RequestParam(value = "wgName", required = false) String wgName,
                       @RequestParam(value = "wgCode", required = false) String wgCode,
                       @RequestParam("wgType") String wgType,
                       @RequestParam(value = "level", required = false) String level,
                       @RequestParam(value = "wgPurpose", required = false) String wgPurpose,
                       @RequestParam("pageNum") Integer pageNum,
                       @RequestParam("pageSize") Integer pageSize) {
        try {
            AjaxResult result = new AjaxResult();
            SysUser user = SecurityUtils.getLoginUser().getUser();
            //网格
            GridRegionUserExample example = new GridRegionUserExample();
            GridRegionUserExample.Criteria criteria = example.createCriteria();
            criteria.andUserIdEqualTo(user.getUserId());

//            criteria.andUserIdEqualTo("1");
            criteria.andIsValidEqualTo("1");

            List<GridRegionUser> relationship = gridRegionUserService.selectByExample(example);
            String region = relationship.stream().map(GridRegionUser::getWgId).collect(Collectors.joining(","));
            List<String> regions = Arrays.asList(region.split(","));
            List<String> regionList = new ArrayList<>();

//            if(!regions.get(0).equals("320282001")){
//                regionList.add("320282001");
//            }
//            regionList.addAll(regions);

            //3.20权限bug
            if(regions.get(0).equals("320282001")){
                regionList.add("320282001");
            }else{
                regionList.addAll(regions);
            }
            //


            if(wgType.equals("0")){
                gridRegionFacadeService.getRolesWhereTypeZero(wgName, wgCode, wgType, level, wgPurpose, pageNum, pageSize, result);
//                gridRegionFacadeService.getRoles(wgName, wgCode, wgType, level, wgPurpose, pageNum, pageSize, result);
            }else {
//                gridRegionFacadeService.getRoles(wgName, wgCode, wgType, level, wgPurpose, pageNum, pageSize, result);
                gridRegionFacadeService.getRoles(wgName, wgCode, wgType, level, wgPurpose, pageNum, pageSize, result, regionList);
            }
            return JSON.toJSONString(result);
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.error(500, "服务器内部错误"));
        }
    }

    @RequestMapping(value = "/treeNode", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult getGridTreeNode(@RequestParam(value = "wgName", required = false) String wgName,
                                        @RequestParam(value = "wgType") String wgType,
                                      @RequestParam(value = "isShow", required = false) String isShow) {
        try {
            GridTreeNode treeNode = gridRegionFacadeService.getTreeNode(wgName, wgType,isShow);
            return AjaxResult.success(treeNode);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(500, "服务器内部错误");
        }
    }

    /**
     * 层级级联树，最外层包了一层type，基础、经济，闲置，农业，商业字段
     * @return
     */
    @GetMapping("/levelTree")
    @ResponseBody
    public AjaxResult getLevelTree(@RequestParam(value = "isShow", required = false)String isShow){
        return AjaxResult.success(gridRegionFacadeService.getLevelTreeNode("wgType", isShow));
    }

    /**
     * 一模一样，先注释
     * @param wgType
     * @return
     */

//    @RequestMapping(value = "/zswgNode", method = RequestMethod.GET)
//    @ResponseBody
//    public String getZswgNode(@RequestParam(value = "wgName", required = false) String wgName,
//                              @RequestParam("wgType") String wgType) {
//        try {
//            AjaxResult result = new AjaxResult();
//            SysUser sysUser = getLoginUser().getUser();
//            GridTreeNode treeNode = gridRegionFacadeService.getTreeNode(sysUser, wgName, wgType);
//
//            return JSON.toJSONString(treeNode);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return JSON.toJSONString(AjaxResult.error(500, "服务器内部错误"));
//        }
//    }

    @RequestMapping(value = "/roleNode", method = RequestMethod.GET)
    @ResponseBody
    public String roleNode(@RequestParam("wgType") String wgType) {
        try {
            GridTreeNode treeNode = gridRegionFacadeService.getTreeNode("", wgType,"");
            return JSON.toJSONString(treeNode);
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.error(500, "服务器内部错误"));
        }
    }

    @RequestMapping(value = "", method = RequestMethod.DELETE)
    @ResponseBody
    public String delete(@RequestBody GridRegion body) {
        try {
            return gridRegionFacadeService.commit(body, "delete");
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.error(500, "服务器内部错误"));
        }
    }

    @RequestMapping(value = "", method = RequestMethod.POST)
    @ResponseBody
    public String insert(@RequestBody GridRegion body) {
        try {
            String level = body.getLevel();
            if(level.equals("1")||level.equals("2")){
                body.setStatus("1");
            }else {
                body.setStatus(level);
            }
            body.setPosition(gridRegionMapper.selectMaxPosition()+1);
            return gridRegionFacadeService.commit(body, "insert");
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.error(500, "服务器内部错误"));
        }
    }

    @RequestMapping(value = "", method = RequestMethod.PATCH)
    @ResponseBody
    public String update(@RequestBody GridRegion body) {
        try {
            return gridRegionFacadeService.commit(body, "update");
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.error(500, "服务器内部错误"));
        }
    }


    @RequestMapping(value = "/autoGenerationWgcode", method = RequestMethod.GET)
    @ResponseBody
    public String autoGenerationWgcode(@RequestParam("parentCode") String parentCode) {
        try {
            String wgcode = gridRegionFacadeService.autoGenerationWgcode(parentCode);
            return JSON.toJSONString(wgcode);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 读取Excel
     *
     * @param file
     * @param wgType      网格类型
     * @param memberClass excel文件名
     * @return
     */
    @ApiOperation(value = "导入网格信息Excel", notes = "将网格信息Excel导入数据库")
    @RequestMapping(value = "importExcel", method = RequestMethod.POST)
    public AjaxResult readExcel(MultipartFile file, @RequestParam String wgType, @RequestParam String userName, @RequestParam String memberClass) {
        String msg = "";
        List<GridRegion> list = new ArrayList<>(); //返回的集合

        InputStream is = null;
        Workbook workbook = null;
        String fileName = file.getOriginalFilename();
        if (file == null) {
            return AjaxResult.error(400, "文件不存在");
        } else {
            try {
                is = file.getInputStream();//创建文件流
//                is = new FileInputStream(filePath); //创建文件流
                if ("xls".equals(ZQTImportExcelUtil.getPostFix(fileName))) {
                    workbook = new HSSFWorkbook(is);  //xls对应的HSSFWorkbook工作簿对象
                } else if ("xlsx".equals(ZQTImportExcelUtil.getPostFix(fileName))) {
                    workbook = new XSSFWorkbook(is);  //xlsx对应的XSSFWorkbook工作簿对象
                } else {
                    return AjaxResult.error(400, "文件格式不正确");
                }

            } catch (FileNotFoundException e) {
                e.printStackTrace();
                msg += e.getMessage();
            } catch (IOException e) {
                e.printStackTrace();
                msg += e.getMessage();
                return AjaxResult.error(400, "系统错误" + msg);
            }

            //循环遍历工作簿里面的sheet表
            for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
                Sheet sheet = workbook.getSheetAt(i); //读取工作表
                if (sheet == null) //空判断
                    continue;
                for (int j = 1; j <= sheet.getLastRowNum(); j++) {
                    Row row = sheet.getRow(j); //读取每行
                    if (row != null && memberClass != null && memberClass.equals("网格信息")) {
                        GridRegion bsRegion = new GridRegion();
                        //设置网格信息实体各属性的值
                        if (StringUtils.isEmpty(ZQTImportExcelUtil.getValue(row.getCell(0)))) {
                            msg += "第" + j + "行网格编码不能为空" + "\n";
                        } else {
                            bsRegion.setWgCode(ZQTImportExcelUtil.getValue(row.getCell(0)));
                        }
                        if (StringUtils.isEmpty(ZQTImportExcelUtil.getValue(row.getCell(1)))) {
                            msg += "第" + j + "行网格名称不能为空" + "\n";
                        } else {
                            bsRegion.setWgName(ZQTImportExcelUtil.getValue(row.getCell(1)));
                        }
//                        if(ImportExcelUtil.getValue(row.getCell(2))==null){
//                            msg+="第"+j+"行上级网格编码不能为空"+"\n";
//                        }else {
//                            bsRegion.setWgParentId(ImportExcelUtil.getValue(row.getCell(2)));
//                        }
                        if (ZQTImportExcelUtil.getValue(row.getCell(2)) != null)
                            bsRegion.setWgParentId("".equals(ZQTImportExcelUtil.getValue(row.getCell(2))) ? null : ZQTImportExcelUtil.getValue(row.getCell(2)));
                        if (ZQTImportExcelUtil.getValue(row.getCell(3)) != null)
                            bsRegion.setWgArea(ZQTImportExcelUtil.getValue(row.getCell(3)));
//                        if(StringUtils.isEmpty(ImportExcelUtil.getValue(row.getCell(4)))){
//                            msg+="第"+j+"行网格范围编码不能为空"+"\n";
//                        }else {
//                            bsRegion.setWgCoordinate(ImportExcelUtil.getValue(row.getCell(4)));
//                        }
                        bsRegion.setWgCoordinate(ZQTImportExcelUtil.getValue(row.getCell(4)));
//                        if(StringUtils.isEmpty(ImportExcelUtil.getValue(row.getCell(5)))){
//                            msg+="第"+j+"行中心坐标编码不能为空"+"\n";
//                        }else {
//                            bsRegion.setWgCentreCoordinate(ImportExcelUtil.getValue(row.getCell(5)));
//                        }
                        bsRegion.setWgCentreCoordinate(ZQTImportExcelUtil.getValue(row.getCell(5)));
                        if (ZQTImportExcelUtil.getValue(row.getCell(6)) != null)
                            bsRegion.setYlzd2(ZQTImportExcelUtil.getValue(row.getCell(6)));
                        if (StringUtils.isEmpty(ZQTImportExcelUtil.getValue(row.getCell(7)))) {
                            msg += "第" + j + "行网格层级不能为空" + "\n";
                        } else {
                            bsRegion.setLevel(ZQTImportExcelUtil.getValue(row.getCell(7)));
                        }
                        list.add(bsRegion);
                    }
                }

            }
        }

        if (msg.length() == 0) {
//            msg.length()==0则说明没有不符合规范的数据
            int records = 0;
            int countActivity = 0;
            int temp = 0;
            try {
                for (GridRegion member : list) {
                    //逐条导入数据库
                    List<GridRegion> wgxxbList = gridRegionFacadeService.getRolesForExample(wgType, member.getWgCode());
                    if (wgxxbList.isEmpty()) {
                        String id = UUID.randomUUID().toString();
                        member.setId(id);
                        member.setWgType(wgType);
                        member.setCreateTime(DateUtils.getTime());
                        member.setCreateBy(userName);
                        member.setUpdateTime(DateUtils.getTime());
                        member.setUpdateBy(userName);
                        member.setIsValid("1");
                        temp = gridRegionService.insertSelective(member);
                    } else {
                        member.setId(wgxxbList.get(0).getId());
                        member.setUpdateTime(DateUtils.getDate());
                        member.setUpdateBy(userName);
                        temp = gridRegionService.updateByPrimaryKeySelective(member);
                    }
                    if (temp == 1) {
                        records++;
                    } else {
                        msg += "第" + records + 1 + "条数据导入出错：";
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                msg += e.getMessage();
                return AjaxResult.error(400, msg);
            }
            msg = "导入" + records + "条数据";
            return AjaxResult.success("success", msg);
        }
        return AjaxResult.error(400, msg);
    }

    /***************************************提供对外接口********************/

    /**
     * 获取网格树
     *
     * @param wgType 网格类型 1基础网格、2专属
     * @return
     */
    @RequestMapping(value = "/getTreeNode", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult getTreeNode(@RequestParam("wgType") String wgType, @RequestParam(value = "isShow", required = false)String isShow) {
        SysUser sysUser = getLoginUser().getUser();
        List<String> wgCodeList = new ArrayList<>();
        if(wgType.equals("1")){
            //目前只有基础地块有权限配置
            List<GridRegionUser> list = gridRegionUserService.getPermissionWgCodes(sysUser.getUserId());
            if(CollectionUtils.isEmpty(list)) {
                return AjaxResult.success(new GridTreeNode());
            }
            wgCodeList = list.stream().map(GridRegionUser::getWgId).collect(Collectors.toList());
        }
        return AjaxResult.success(gridRegionFacadeService.treeNode(wgType, wgCodeList, isShow));
    }

    @RequestMapping(value = "/getRegionList", method = RequestMethod.GET)
    @ResponseBody
    public String getRegionList(@RequestParam("wgType") String wgType,  @RequestParam("wgCode") String wgCode) {
        try {
            AjaxResult result = new AjaxResult();
            GridRegionExample example = new GridRegionExample();
            GridRegionExample.Criteria criteria = example.createCriteria();
            criteria.andIsValidEqualTo("1");
            if (StringUtils.isNotEmpty(wgType)) {
                criteria.andWgTypeEqualTo(wgType);
            }
            if (StringUtils.isNotEmpty(wgCode)) {
                criteria.andWgParentIdEqualTo(wgCode);
            }
            gridRegionFacadeService.getRegionListByExample(example, result);
            return JSON.toJSONString(result);
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.error(500, "服务器内部错误"));
        }
    }

    @RequestMapping(value = "/getRegionListByWgCode", method = RequestMethod.GET)
    @ResponseBody
    public String getRegionListByWgCode(@RequestParam("wgType") String wgType,  @RequestParam("wgCode") String wgCode) {
        try {
            AjaxResult result = new AjaxResult();
            gridRegionFacadeService.getRegionListForTreeNode(wgCode, wgType, result);
            return JSON.toJSONString(result);
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.error(500, "服务器内部错误"));
        }
    }

    @RequestMapping(value = "/getRegionByWgcode", method = RequestMethod.GET)
    @ResponseBody
    public String getRegionByWgcode(@RequestParam("wgCode") String wgCode) {
        try {
            AjaxResult result = new AjaxResult();
            GridRegionExample example = new GridRegionExample();
            GridRegionExample.Criteria criteria = example.createCriteria();
            criteria.andIsValidEqualTo("1");
            if (!StringUtils.isNotEmpty(wgCode)) {
                result.buildError(400, "wgCode不能为空");
                return JSON.toJSONString(result);
            }
            criteria.andWgCodeEqualTo(wgCode);
            gridRegionFacadeService.getRegionListByExample(example, result);

            return JSON.toJSONString(result);
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.error(500, "服务器内部错误"));
        }
    }


    @RequestMapping(value = "/getRegionByWgId", method = RequestMethod.GET)
    @ResponseBody
    public String getRegionByWgId(@RequestParam("wgId") String wgId) {
        try {
            AjaxResult result = new AjaxResult();
            GridRegionExample example = new GridRegionExample();
            GridRegionExample.Criteria criteria = example.createCriteria();
            criteria.andIsValidEqualTo("1");
            if (!StringUtils.isNotEmpty(wgId)) {
                result.buildError(400, "wgCode不能为空");
                return JSON.toJSONString(result);
            }
            criteria.andIdEqualTo(wgId);
            gridRegionFacadeService.getRegionListByExample(example, result);

            return JSON.toJSONString(result);
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.error(500, "服务器内部错误"));
        }
    }

    @RequestMapping(value = "/getRegionByWgmj", method = RequestMethod.GET)
    @ResponseBody
    public String getRegionByWgmj(@RequestParam("wgCode") String wgCode) {
        try {
            AjaxResult result = new AjaxResult();
            GridRegionExample example = new GridRegionExample();
            GridRegionExample.Criteria criteria = example.createCriteria();
            criteria.andIsValidEqualTo("1");
            criteria.andWgTypeEqualTo("1");
            if (!StringUtils.isNotEmpty(wgCode)) {
                result.buildError(400, "wgCode不能为空");
                return JSON.toJSONString(result);
            }
            criteria.andWgCodeLike("%" + wgCode + "%");
            gridRegionFacadeService.getRegionListByWgmj(example, result);

            return JSON.toJSONString(result);
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.error(500, "服务器内部错误"));
        }
    }

    //---------------------新的网格地图接口--------------------
    @RequestMapping(value = "/getCurrentRegion", method = RequestMethod.GET)
    @ResponseBody
    public String getCurrentRegion(@RequestParam("wgType") String wgType) {
        try {
            AjaxResult result = new AjaxResult();
            if (!StringUtils.isNotEmpty(wgType)) {
                result.buildError(400, "wgType不能为空");
                return JSON.toJSONString(result);
            }
            GridRegionExample example = new GridRegionExample();
            GridRegionExample.Criteria criteria = example.createCriteria();
            criteria.andIsValidEqualTo("1");
            if ("2".equals(wgType)) {
                criteria.andWgTypeEqualTo(wgType);
            } else {
                criteria.andWgTypeEqualTo(wgType).andWgParentIdIsNull();
            }
            gridRegionFacadeService.getRegionListByExample(example, result);
            return JSON.toJSONString(result);
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.error(500, "服务器内部错误"));
        }
    }

    @RequestMapping(value = "/getChildRegion", method = RequestMethod.GET)
    @ResponseBody
    public String getChildRegion(@RequestParam("wgType") String wgType,
                                 @RequestParam("wgCode") String wgCode,
                                 @RequestParam("dxlx") String dxlx,
                                 @RequestParam("qylx") String qylx) {
        try {
            AjaxResult result = new AjaxResult();
            if (!StringUtils.isNotEmpty(wgType)) {
                result.buildError(400, "wgType不能为空");
                return JSON.toJSONString(result);
            }
            if (!StringUtils.isNotEmpty(dxlx)) {
                result.buildError(400, "dxlx不能为空");
                return JSON.toJSONString(result);
            }
            GridRegionExample example = new GridRegionExample();
            GridRegionExample.Criteria criteria = example.createCriteria();
            criteria.andIsValidEqualTo("1");
            if ("2".equals(wgType)) {
                criteria.andWgTypeEqualTo(wgType);
            } else {
                criteria.andWgTypeEqualTo(wgType).andWgParentIdEqualTo(wgCode);
            }
            gridRegionFacadeService.getChildRegion(example, dxlx, qylx, result);
            return JSON.toJSONString(result);
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.error(500, "服务器内部错误"));
        }
    }

    @RequestMapping(value = "/countRoleUserByWgcode", method = RequestMethod.GET)
    @ResponseBody
    public String countRoleUserByWgcode(@RequestParam("wgCode") String wgCode) {
        try {
            AjaxResult result = new AjaxResult();
            if (!StringUtils.isNotEmpty(wgCode)) {
                result.buildError(400, "wgCode不能为空");
                return JSON.toJSONString(result);
            }
            gridRegionFacadeService.countRoleUserByWgcode(wgCode, result);
            return JSON.toJSONString(result);
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.error(500, "服务器内部错误"));
        }
    }

    @RequestMapping(value = "/selectThirdGridNameByBaseId", method = RequestMethod.GET)
    @ResponseBody
    public String selectThirdGridNameByBaseId(Integer pageNum, Integer pageSize) {
        try {
            AjaxResult result = new AjaxResult();
            gridRegionFacadeService.selectThirdGridNameByBaseId(result, pageNum, pageSize);
            return JSON.toJSONString(result);
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.error(500, "服务器内部错误"));
        }
    }


    /**
     * 获取网格树
     *
     * @param wgType 网格类型 1基础网格、2专属
     * @param isShow 是否显示四级网格,isAll:是否不要代入权限，就显示全部
     * @return
     */
    @RequestMapping(value = "/getWsTreeNode", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult getWsTreeNode(@RequestParam("wgType") String wgType, String isShow, @RequestParam(value = "isAll", required = false) String isAll) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        //网格
        GridRegionUserExample example = new GridRegionUserExample();
        GridRegionUserExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(user.getUserId());

//        criteria.andUserIdEqualTo("1");

        criteria.andIsValidEqualTo("1");
        List<GridRegionUser> relationship = gridRegionUserService.selectByExample(example);
        String region = relationship.stream().map(GridRegionUser::getWgId).collect(Collectors.joining(","));
        List<String> regions = Arrays.asList(region.split(","));
        List<String> regionList = new ArrayList<>();
        if(!regions.get(0).equals("320282001")){
            regionList.add("320282001");
        }
        regionList.addAll(regions);

        if(wgType.equals("0")){
            return AjaxResult.success(gridRegionFacadeService.getWsTreeNodeIncludeTwoPointFive(null,null,null,regionList));
//            return AjaxResult.success(gridRegionFacadeService.getWsTreeNodeIncludeTwoPointFive(null,null,null));
        }

//        SysUser sysUser = getLoginUser().getUser();
        List<String> wgCodeList = new ArrayList<>();
        if(StringUtils.isBlank(isAll) && wgType.equals("1")){
            //目前只有基础网格有权限
//            List<GridRegionUser> list = gridRegionUserService.getPermissionWgCodes(sysUser.getUserId());
            List<GridRegionUser> list = gridRegionUserService.getPermissionWgCodes("1");
            if(CollectionUtils.isEmpty(list)) {
                return AjaxResult.success();
            }
            wgCodeList  = list.stream().map(GridRegionUser::getWgId).collect(Collectors.toList());
        }
        return AjaxResult.success(gridRegionFacadeService.getWsTreeNode(wgType, wgCodeList, isShow, regions));
//        return AjaxResult.success(gridRegionFacadeService.getWsTreeNode(wgType, wgCodeList, isShow));

    }


    /**
     * 根据wgType查询二级网格
     *
     * @param wgType
     * @return
     */
    @RequestMapping(value = "/getWsSecondRegion", method = RequestMethod.GET)
    @ResponseBody
    public String getWsSecondRegion(@RequestParam("wgType") String wgType) {
        try {
            AjaxResult result = new AjaxResult();
            GridRegionExample example = new GridRegionExample();
            example.createCriteria().andWgTypeEqualTo(wgType).andIsValidEqualTo("1").andLevelEqualTo("2");
            List<GridRegion> gridRegionList = gridRegionService.selectByExample(example);
            List<Map<String, String>> ret = new ArrayList<Map<String, String>>();
            gridRegionList.forEach(gridRegion -> {
                Map<String, String> map = new HashMap<>();
                map.put("id", gridRegion.getId());
                map.put("wgCode", gridRegion.getWgCode());
                map.put("wgName", gridRegion.getWgName());
                map.put("level", gridRegion.getLevel());
                ret.add(map);
            });
            result.buildSuccess("success", ret);
            return JSON.toJSONString(result);
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.error(500, "服务器内部错误"));
        }
    }


    /**
     * 根据wgType、wgCode获取上级网格信息
     *
     * @param wgType
     * @param wgCode
     * @return
     */
    @RequestMapping(value = "/getWsParentRegion", method = RequestMethod.GET)
    @ResponseBody
    public String getWsParentRegion(String wgType, String wgCode) {
        try {
            AjaxResult result = new AjaxResult();
            GridRegionExample example = new GridRegionExample();
            GridRegionExample.Criteria criteria = example.createCriteria();
            if (StringUtils.isNotEmpty(wgType)) {
                criteria.andWgTypeEqualTo(wgType);
            }
            if (StringUtils.isNotEmpty(wgCode)) {
                criteria.andWgParentIdEqualTo(wgCode);
            }
            criteria.andIsValidEqualTo("1");
            List<GridRegion> gridRegionList = gridRegionService.selectByExample(example);
            List<Map<String, String>> ret = new ArrayList<Map<String, String>>();
            if (gridRegionList.size() > 0) {
                gridRegionList.forEach(gridRegion -> {
                    Map<String, String> map = new HashMap<>();
                    map.put("id", gridRegion.getId());
                    map.put("wgCode", gridRegion.getWgCode());
                    map.put("wgName", gridRegion.getWgName());
                    map.put("level", gridRegion.getLevel());
                    ret.add(map);
                });
            }
            result.buildSuccess("success", ret);
            return JSON.toJSONString(result);
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.error(500, "服务器内部错误"));
        }
    }


    @RequestMapping(value = "/getAreaList", method = RequestMethod.GET)
    @ResponseBody
    public String getAreaList(@RequestParam(value = "wgName", required = false) String wgName,
                              @RequestParam(value = "wgCode", required = false) String wgCode,
                              @RequestParam(value = "pageNum", required = false) Integer pageNum,
                              @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        try {
            AjaxResult result = new AjaxResult();
            gridRegionFacadeService.getAreaList(wgName, wgCode, pageNum, pageSize, result);
            return JSON.toJSONString(result);
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.error(500, "服务器内部错误"));
        }
    }

    /**
     * 根据地块获取网格列表
     *
     * @param wgdxbVO
     * @return
     */
    @RequestMapping(value = "/getThirdWgList", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult getThirdWgList(@RequestBody GridDxbVO wgdxbVO) {
        List<Map<String, String>> result = gridRegionFacadeService.getThirdWgList(wgdxbVO.getWgCodeList());
        return AjaxResult.success(result);
    }

    /**
     * 获取对象-安全生产走访
     *
     * @param wgdxbVO
     * @return
     */
    @RequestMapping(value = "/getObjList", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult getObjList(@RequestBody GridDxbVO wgdxbVO) {
        PageInfo<Map<String, Object>> result = gridRegionFacadeService.getObjList(wgdxbVO);
        return AjaxResult.success(result);
    }


    /**
     * 获取对象-网格员入户走访
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/getHouseObjList", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult getHouseObjList(@RequestBody GridDxbVO wgdxbVO) {
        PageInfo<Map<String, Object>> result = gridRegionFacadeService.getHouseObjList(wgdxbVO);
        return AjaxResult.success(result);
    }


    @RequestMapping(value = "/getZsWgInfoList", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult getZsWgInfoList() {
        GridRegionExample example = new GridRegionExample();
        example.createCriteria().andIsValidEqualTo("1").andYlzd2EqualTo("1");
        List<GridRegion> gridRegionList = gridRegionMapper.selectByExample(example);
        List<Map<String, String>> result = new ArrayList<>();
        gridRegionList.forEach(gridRegion -> {
            Map<String, String> map = new HashMap<>();
            map.put("wgName", gridRegion.getWgName());
            map.put("wgCode", gridRegion.getWgCode());
            map.put("id", gridRegion.getId());
            result.add(map);
        });
        return AjaxResult.success(result);
    }

    @RequestMapping(value = "/getThirdRegion",method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult getThirdRegion(@RequestParam(value = "wgType", required = false) String wgType,
                                     @RequestParam(value = "wgCode", required = false) String wgCode,
                                     @RequestParam(value = "pageNum", required = false) Integer pageNum,
                                     @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                     @RequestParam(value = "name", required = false) String name
                                     ){
        List<String> wgCodeLikes = new ArrayList<>();
        if(!StringUtils.isBlank(wgCode)){
            wgCodeLikes = Arrays.asList(wgCode.split(","));
        }
        List<GridTreeNode> treeNodeList = new ArrayList<>();
        List<GridRegion> gridRegionList = gridRegionMapper.getSecondOrThirdRegion(wgType,wgCodeLikes,null,"2");
        for(GridRegion gridRegion : gridRegionList){
            List<String> parent = new ArrayList<>();
            parent.add(gridRegion.getWgCode());
            List<GridRegion> children = gridRegionMapper.getSecondOrThirdRegion(wgType,parent,name,"3");
            GridTreeNode treeNode = new GridTreeNode();
            BeanUtils.copyProperties(gridRegion,treeNode);
            treeNode.setName(gridRegion.getWgName());
            treeNode.setId(gridRegion.getId());
            treeNode.setCode(gridRegion.getWgCode());
            treeNode.setParentId(gridRegion.getWgParentId());
            for(GridRegion child : children){
                GridTreeNode childTreeNode = new GridTreeNode();
                BeanUtils.copyProperties(child,childTreeNode);
                childTreeNode.setName(child.getWgName());
                childTreeNode.setId(child.getId());
                childTreeNode.setCode(child.getWgCode());
                childTreeNode.setParentId(child.getWgParentId());
                treeNode.getChild().add(childTreeNode);
            }
            treeNodeList.add(treeNode);
        }
        return AjaxResult.success(treeNodeList);
    }

    @RequestMapping(value = "/getOneOrTwoRegion",method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult getOneOrTwoRegion(@RequestParam(value = "level", required = false) String level,
                                     @RequestParam(value = "pageNum", required = false) Integer pageNum,
                                     @RequestParam(value = "pageSize", required = false) Integer pageSize
    ){
        if(level.equals("1")){
            GridRegionExample example = new GridRegionExample();
            GridRegionExample.Criteria criteria = example.createCriteria();
            criteria.andIsValidEqualTo("1");
            criteria.andLevelEqualTo("1");
            criteria.andWgTypeEqualTo("1");

            List<GridRegion> gridRegionList = gridRegionMapper.selectByExample(example);
            return AjaxResult.success(gridRegionList);
        }
        SysUser user = SecurityUtils.getLoginUser().getUser();
        //网格
        GridRegionUserExample example = new GridRegionUserExample();
        GridRegionUserExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(user.getUserId());

//                criteria.andUserIdEqualTo("8c48c6cab96e462a9632492762c4cfaa");

        criteria.andIsValidEqualTo("1");
        List<GridRegionUser> relationship = gridRegionUserService.selectByExample(example);
        String region = relationship.stream().map(GridRegionUser::getWgId).collect(Collectors.joining(","));
        List<String> regions = Arrays.asList(region.split(","));
        List<String> regionList = new ArrayList<>(regions);
        if(regionList.size()==1 && regionList.get(0).equals("320282001")){
            return AjaxResult.success(gridRegionMapper.getAllLevelTwoByType(null));
        }

        return AjaxResult.success(gridRegionMapper.getAllLevelTwoByType(regionList));
    }

    @RequestMapping(value = "/getTwoThreeRegion",method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult getTwoThreeRegion(@RequestParam(value = "wgType", required = false) String wgType,
                                        @RequestParam(value = "wgCode", required = false) String wgCode,
                                        @RequestParam(value = "pageNum", required = false) Integer pageNum,
                                        @RequestParam(value = "pageSize", required = false) Integer pageSize
    ){
        GridRegionExample example = new GridRegionExample();
        GridRegionExample.Criteria criteria = example.createCriteria();

        criteria.andIsValidEqualTo("1");
//        criteria.andLevelEqualTo(level);
        criteria.andWgTypeEqualTo(wgType);
        criteria.andWgCodeEqualTo(wgCode);

        List<GridRegion> gridRegionList = gridRegionMapper.selectByExample(example);
        return AjaxResult.success(gridRegionList);
    }

//    @PreAuthorize("@ss.hasPermi('system:region:remove')")
    @RequestMapping(value = "/deleteTreeNode",method = RequestMethod.DELETE)
    @ResponseBody
    public AjaxResult deleteTreeNode(@RequestParam(value = "id", required = false) String id,
                                     @RequestParam(value = "wgCode", required = false) String wgCode
    ){
        GridRegionExample example1 = new GridRegionExample();
        GridRegionExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andIsValidEqualTo("1");
        criteria1.andWgParentIdEqualTo(wgCode);
//        long count = gridRegionMapper.countByExample(example1);
//        if(count>0){
//            throw new RuntimeException("当前菜单存在下级菜单，无法删除");
//        }
        if(gridRegionMapper.countByFourthCode(wgCode)>0){
            throw new RuntimeException("当前菜单存在房源，无法删除");
        }

        GridRegionExample example = new GridRegionExample();
        GridRegionExample.Criteria criteria = example.createCriteria();

        criteria.andIsValidEqualTo("1");
        criteria.andIdEqualTo(id);

        gridRegionMapper.deleteByExample(example);
        gridRegionMapper.deleteByExample(example1);

        return AjaxResult.success();
    }

//    @PreAuthorize("@ss.hasPermi('system:region:edit')")
    @RequestMapping(value = "/changeName",method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult changeName(@RequestParam(value = "id", required = false) String id,
                                 @RequestParam(value = "name", required = false) String name
    ){
        return AjaxResult.success(gridRegionMapper.changeTreeNodeName(id,name));
    }

    @RequestMapping(value = "/getFourByThreeId",method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult getFourByThreeId(@RequestParam(value = "id", required = false) String id,
                                       @RequestParam(value = "wgType", required = false) String wgType
    ){
        if(id==null || id.isEmpty()){
            return AjaxResult.success();
        }
        String code = gridRegionMapper.getWgCodeById(id);
        if(code == null){
            return AjaxResult.success("id不存在");
        }
        GridRegionExample example1 = new GridRegionExample();
        GridRegionExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andWgParentIdEqualTo(code);
        criteria1.andWgTypeEqualTo(wgType);
        return AjaxResult.success(gridRegionMapper.selectByExample(example1));
    }

    @RequestMapping(value = "/changeNameByCode",method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult changeNameByCode(@RequestParam(value = "id", required = false) String id,
                                 @RequestParam(value = "name", required = false) String name
    ){
        return AjaxResult.success(gridRegionMapper.changeTreeNodeNameByCode(id,name));
    }

    @RequestMapping(value = "/getRegion", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult getRegion(@RequestParam("wgCode") String wgCode) {
        Map<String,List<GridRegion>> res = new HashMap<>();
        List<GridRegion> type1 = gridRegionService.getGridRegionMapByWgCodeAndWgType(wgCode,"1");
        List<GridRegion> type4 = gridRegionService.getGridRegionMapByWgCodeAndWgType(wgCode,"4");
        List<GridRegion> type5 = gridRegionService.getGridRegionMapByWgCodeAndWgType(wgCode,"5");
        List<GridRegion> type6 = gridRegionService.getGridRegionMapByWgCodeAndWgType(wgCode,"6");
        List<GridRegion> type7 = gridRegionService.getGridRegionMapByWgCodeAndWgType(wgCode,"7");
        res.put("1",type1);
        res.put("4",type4);
        res.put("5",type5);
        res.put("6",type6);
        res.put("7",type7);
        return AjaxResult.success(res);
    }

    @RequestMapping(value = "/getRegionDetail", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult getRegionDetail(@RequestParam("id") String id) {
        return AjaxResult.success(gridRegionMapper.getRegionDetail(id));
    }

    @RequestMapping(value = "/updateRegionDetail", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult updateRegionDetail(@RequestBody GridRegionDetail gridRegionDetail) {
        return AjaxResult.success(gridRegionMapper.updateRegionDetail(gridRegionDetail.getId(),gridRegionDetail.getDetail()));
    }

    @RequestMapping(value = "/getRegionJzArea", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult getRegionJzArea(@RequestParam("id") String id) {
        return AjaxResult.success(gridRegionMapper.getRegionJzArea(id));
    }

    @RequestMapping(value = "/updateRegionJzArea", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult updateRegionJzArea(@RequestBody GridRegionDetail gridRegionDetail) {
        return AjaxResult.success(gridRegionMapper.updateRegionJzArea(gridRegionDetail.getId(),gridRegionDetail.getJzArea()));
    }

    @RequestMapping(value = "/getFourRegionList", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult getFourRegionList(@RequestParam("wgCode") String wgCode) {
        return AjaxResult.success(gridRegionMapper.getFourRegionList(wgCode));
    }

    @PostMapping("/position")
    public AjaxResult getVideoPosition(@RequestBody Position position) {
        List<String> list = Arrays.asList(position.getIds());

        //需要两个数组，index_now记录当前传入数组的channelId在数据库中的position
        //此处为了考虑按照类型分类后产生的不完整排序
        int[] index_now = new int[list.size()];

        for(int i = 0; i < list.size(); i++){
            String channelId = list.get(i);
            int position_now = gridRegionMapper.positionById(channelId);
            index_now[i] = position_now;
        }
        Arrays.sort(index_now);

        for(int i = 0;i<list.size();i++){
            gridRegionMapper.position(list.get(i),index_now[i]);
        }

        return AjaxResult.success();
    }

    @RequestMapping(value = "/exchangePosition", method = RequestMethod.GET)
    @ResponseBody
    public void exchangePosition() {
//        用来更新position的接口，重置所有排序
        List<String> wgCode = gridRegionMapper.getAllWgCode();
//        List<String> wgCode = Arrays.asList("320282001001DL005");
        for(String code : wgCode){
            gridRegionMapper.initPositionVariable();
            gridRegionMapper.updatePositionByWgCodes(code);
        }
    }

    @RequestMapping(value = "/addRegion", method = RequestMethod.POST)
    @ResponseBody
    public String addRegion(@RequestBody GridRegion body) {
        try {
            // 获取当前日期和时间
            LocalDateTime now = LocalDateTime.now();
            // 定义日期时间格式，去掉特殊符号
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
            // 格式化日期时间
            String date = now.format(formatter);

            body.setWgCode(body.getWgParentId()+date);

            String level = body.getLevel();
            if(level.equals("1")||level.equals("2")){
                body.setStatus("1");
            }else {
                body.setStatus(level);
            }
            body.setPosition(gridRegionMapper.selectMaxPosition()+1);
            return gridRegionFacadeService.commit(body, "insert");
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(AjaxResult.error(500, "服务器内部错误"));
        }
    }

    @RequestMapping(value = "/getThreeByUser", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult getThreeByUser(@RequestParam(value = "wgType", required = false) String wgType,
                                     @RequestParam(value = "wgName", required = false) String wgName,
                                     @RequestParam(value = "wgCode", required = false) String wgCode,
                                     @RequestParam("pageNum") Integer pageNum,
                                     @RequestParam("pageSize") Integer pageSize) {
        AjaxResult result = new AjaxResult();
        if(wgCode ==null){
            SysUser user = SecurityUtils.getLoginUser().getUser();
            //网格
            GridRegionUserExample example = new GridRegionUserExample();
            GridRegionUserExample.Criteria criteria = example.createCriteria();
            criteria.andUserIdEqualTo(user.getUserId());
            criteria.andIsValidEqualTo("1");

            List<GridRegionUser> relationship = gridRegionUserService.selectByExample(example);
            String region = relationship.stream().map(GridRegionUser::getWgId).collect(Collectors.joining(","));
            List<String> regions = Arrays.asList(region.split(","));
            List<String> regionList = new ArrayList<>();

            List<GridRegion> gridRegions = new ArrayList<>();
            PageHelper.startPage(pageNum, pageSize);
            //3.20权限bug
            if(regions.get(0).equals("320282001")){
//            regionList.add("320282001");
                gridRegions = gridRegionMapper.getAllLevelThree(null,wgType,wgName);
            }else{
                regionList.addAll(regions);
                gridRegions = gridRegionMapper.getAllLevelThree(regionList,wgType,wgName);
            }
            for(GridRegion gridRegion : gridRegions){
                gridRegion.setWgParentName(gridRegionMapper.getWgNameByCode(gridRegion.getWgParentId()));
            }
            PageInfo<GridRegion> pageInfo = new PageInfo<>(gridRegions);
            return AjaxResult.success(pageInfo);
        }else{
            List<String> regions = new ArrayList<>();
            regions.add(wgCode);
            List<String> regionList = new ArrayList<>();
            regionList.addAll(regions);
            List<GridRegion> gridRegions = new ArrayList<>();
            gridRegions = gridRegionMapper.getAllLevelThree(regions,wgType,wgName);
            for(GridRegion gridRegion : gridRegions){
                gridRegion.setWgParentName(gridRegionMapper.getWgNameByCode(gridRegion.getWgParentId()));
            }
            PageInfo<GridRegion> pageInfo = new PageInfo<>(gridRegions);
            return AjaxResult.success(pageInfo);
        }
    }

    @RequestMapping(value = "/getAllTwoRegion",method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult getAllTwoRegion(){
        GridRegionExample example = new GridRegionExample();
        GridRegionExample.Criteria criteria = example.createCriteria();

        criteria.andIsValidEqualTo("1");
        criteria.andLevelEqualTo("2");
        criteria.andWgTypeEqualTo("1");

        List<GridRegion> gridRegionList = gridRegionMapper.selectByExample(example);
        return AjaxResult.success(gridRegionList);
    }

}
