package com.ruoyi.web.controller.grid;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
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.zqt.ZQTImportExcelUtil;
import com.ruoyi.system.domain.grid.GridRegion;
import com.ruoyi.system.domain.grid.GridRegionExample;
import com.ruoyi.system.domain.grid.GridRegionUser;
import com.ruoyi.system.domain.grid.vo.GridDxbVO;
import com.ruoyi.system.domain.grid.vo.GridTreeNode;
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.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
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();
            gridRegionFacadeService.getRoles(wgName, wgCode, wgType, level, wgPurpose, pageNum, pageSize, result);
            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 {
            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 sysUser = getLoginUser().getUser();
        List<String> wgCodeList = new ArrayList<>();
        if(StringUtils.isBlank(isAll) && wgType.equals("1")){
            //目前只有基础网格有权限
            List<GridRegionUser> list = gridRegionUserService.getPermissionWgCodes(sysUser.getUserId());
            if(CollectionUtils.isEmpty(list)) {
                return AjaxResult.success();
            }
            wgCodeList  = list.stream().map(GridRegionUser::getWgId).collect(Collectors.toList());
        }
        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
    ){
        GridRegionExample example = new GridRegionExample();
        GridRegionExample.Criteria criteria = example.createCriteria();
        criteria.andIsValidEqualTo("1");
        criteria.andLevelEqualTo(level);
        criteria.andWgTypeEqualTo("1");

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