package com.ruoyi.system.service.grid;

import com.alibaba.fastjson2.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.bean.BeanCopyUtil;
import com.ruoyi.common.zqt.ZQTPageModel;
import com.ruoyi.common.zqt.ZQTPageUtil;
import com.ruoyi.system.domain.grid.*;
import com.ruoyi.system.domain.grid.enums.GridRegionSearchParam;
import com.ruoyi.system.domain.grid.ext.GridRegionExt;
import com.ruoyi.system.domain.grid.ext.GridRegionWithCompanyItem;
import com.ruoyi.system.domain.grid.vo.GridDxbVO;
import com.ruoyi.system.domain.grid.vo.GridLevelTreeNode;
import com.ruoyi.system.domain.grid.vo.GridTreeNode;
import com.ruoyi.system.domain.grid.vo.SimpleWgItem;
import com.ruoyi.system.domain.other.BsCommon;
import com.ruoyi.system.domain.visit.VisitPlanTaskExample;
import com.ruoyi.system.mapper.grid.*;
import com.ruoyi.system.mapper.visit.VisitPlanTaskMapper;
import com.ruoyi.system.service.other.BsCommonService;
import com.ruoyi.system.service.system.ISysRoleService;
import com.ruoyi.system.service.system.ISysUserService;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Auther: hxc
 * @Date: 2019/2/28 0028 16:04
 * @Description: 网格信息表
 */
@Component
public class GridRegionFacadeService {

    @Autowired
    private GridRegionService gridRegionService;

    @Autowired
    private ISysRoleService sysRoleService;

    // 2024.05.10 sufeng:企业信息表 上面说的废弃了，而且没有数据了，这里就不再接入了
    //    @Autowired
//    private BsWgdxbService bsWgdxbService;

    @Autowired
    private GridRegionUserMapper bsRegionUserMapper;
    @Autowired
    private GridRegionMapper gridRegionMapper;

    @Autowired
    private GridHouseService wsHouseService;
    @Autowired
    private GridPeopleService gridPeopleService;
    @Autowired
    private GridCompanyService gridCompanyService;
    @Autowired
    private GridShopService gridShopService;
    @Autowired
    private GridRegionExtMapper gridRegionExtMapper;

    @Autowired
    private GridCompanyMapper gridCompanyMapper;
    @Autowired
    private GridShopMapper gridShopMapper;
    @Autowired
    private GridItemDailyMapper gridItemDailyMapper;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private VisitPlanTaskMapper visitPlanTaskMapper;

    @Autowired
    private BsCommonService bsCommonService;

    @Autowired
    private GridCompanyLandService companyLandService;

    private static final String baseCode = "320282105";
    private static final String defaultBaseId = "dd2af95a-06b3-4314-a3d6-5ff606d6b930";//徐舍镇

    public String commit(GridRegion body, String method) {
        try {
            AjaxResult result = new AjaxResult();

            Method methodCheck = null;
            try {
                methodCheck = this.getClass().getMethod(method + "Pre", body.getClass(), result.getClass());
            } catch (Exception e) {
                methodCheck = null;
            }
            if (null != methodCheck) {
                Object ret = methodCheck.invoke(this, body, result);
                if ((ret instanceof Boolean) && !(boolean) ret) {
                    return JSON.toJSONString(result);
                }
            }

            Method methodCommit = null;
            try {
                methodCommit = this.getClass().getMethod(method, body.getClass(), result.getClass());
            } catch (Exception e) {
                methodCommit = null;
            }
            if (null == methodCommit) {
                return JSON.toJSONString(AjaxResult.error(600, "方法未找到:" + method));
            }

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

    public boolean insertPre(GridRegion body, AjaxResult result) {
        if (null == body) {
            result.buildError(400, "body为空");
            return false;
        }
        GridRegionExample example = new GridRegionExample();
        GridRegionExample.Criteria criteria = example.createCriteria();
        //基础网格只能有一个一级网格
        if (!StringUtils.isNotEmpty(body.getWgParentId()) && body.getWgType().equals("1")) {
            criteria.andWgParentIdIsNull().andWgTypeEqualTo(body.getWgType());
            int count1 = gridRegionService.countByExample(example);
            if (count1 > 0) {
                result.buildError(600, "只能存在一个一级网格");
                return false;
            }
        }
        //判断记录是否存在
        if (StringUtils.isNotEmpty(body.getWgParentId())) {
            criteria.andWgParentIdEqualTo(body.getWgParentId());
        }
//        criteria.andWgCodeEqualTo(body.getWgCode()).andWgTypeEqualTo(body.getWgType());

        GridRegionExample example2 = new GridRegionExample();
        GridRegionExample.Criteria criteria2 = example2.createCriteria();
        criteria2.andWgCodeEqualTo(body.getWgCode());
        criteria2.andIsValidEqualTo("1");
        int count = gridRegionService.countByExample(example2);
        if (count > 0) {
            result.buildError(600, "网格编码已存在");
            return false;
        }

        GridRegionExample example1 = new GridRegionExample();
        GridRegionExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andWgNameEqualTo(body.getWgName());
        criteria1.andIsValidEqualTo("1");
        int count1 = gridRegionService.countByExample(example1);
        if (count1 > 0) {
            result.buildError(600, "网格名称已存在");
            return false;
        }
        return true;
    }

    public void insert(GridRegion body, AjaxResult result) {
        String id = UUID.randomUUID().toString();

        GridRegion gridRegion = new GridRegion();
        gridRegion.setId(id);
        gridRegion.setLevel(body.getLevel());
        gridRegion.setCreateBy(body.getCreateBy());
        gridRegion.setCreateTime(body.getCreateTime());
        gridRegion.setIsValid(body.getIsValid());
        gridRegion.setUpdateBy(body.getUpdateBy());
        gridRegion.setUpdateTime(body.getUpdateTime());
        gridRegion.setWgArea(body.getWgArea());
        gridRegion.setWgType(body.getWgType());
        gridRegion.setWgCentreCoordinate(body.getWgCentreCoordinate());
        gridRegion.setWgCoordinate(body.getWgCoordinate());
        gridRegion.setWgCode(body.getWgCode());
        gridRegion.setWgName(body.getWgName());
        gridRegion.setWgParentId(body.getWgParentId());
        gridRegion.setWgPrincipal(body.getWgPrincipal());
        gridRegion.setIsValid(body.getIsValid());//默认有效
        gridRegion.setWgPurpose(body.getWgPurpose());

        int ret = gridRegionService.insertSelective(gridRegion);
        if (ret > 0) {
            result.buildSuccess("success", id);
        } else {
            result.buildError(600, "新增失败");
        }
        return;
    }

    public boolean updatePre(GridRegion body, AjaxResult result) {
        if (null == body) {
            result.buildError(400, "body为空");
            return false;
        }

        return true;
    }

    public void update(GridRegion body, AjaxResult result) {
        String id = body.getId();
        GridRegion bean = get(id, null);
        if (null == bean) {
            result.buildError(400, "找不到待更新项");
            return;
        }

        int ret = gridRegionService.updateByPrimaryKeySelective(body);
        if (ret > 0) {
            result.buildSuccess("success", "1");
        } else {
            result.buildError(600, "更新失败");
        }
        return;
    }

    public boolean getPre(String id, AjaxResult result) {
        if (!itemIsUUID(id)) {
            result.buildError(400, "query参数id为空或非法");
            return false;
        }
        return true;
    }

    public GridRegion get(String id, GridRegion gridRegion) {
        if (null == gridRegion) {
            if (StringUtils.isNotEmpty(id)) {
                gridRegion = gridRegionService.selectByPrimaryKey(id);
            }
            if (null == gridRegion) {
                return null;
            }
        }

        return gridRegion;
    }

    public void getRoles(String wgName, String wgCode, String wgType, String level, String purpose, Integer pageNum, Integer pageSize, AjaxResult result, List<String> regions) {
//public void getRoles(String wgName, String wgCode, String wgType, String level, String purpose, Integer pageNum, Integer pageSize, AjaxResult result) {
        if (null == pageNum || pageNum <= 0) {
            pageNum = 1;
        }
        if (null == pageSize || pageSize <= 0) {
            pageSize = 10;
        }

        ZQTPageModel<GridRegionWithCompanyItem> appPageModel = new ZQTPageModel<>();
        appPageModel.setRecordCount(0);
        appPageModel.setPageCount(0);
        appPageModel.setCurPage(pageNum);
        appPageModel.setItemList(new ArrayList<>());

        GridRegionExample example = new GridRegionExample();
        GridRegionExample.Criteria criteria = example.createCriteria();
        criteria.andIsValidEqualTo("1");
        if (StringUtils.isNotEmpty(wgName)) {
            criteria.andWgNameLike("%" + wgName + "%");
        }
        if (StringUtils.isNotEmpty(wgType)) {
            criteria.andWgTypeEqualTo(wgType);
        }
        if (StringUtils.isNotEmpty(level)) {
            criteria.andLevelEqualTo(level);
        }
        if (StringUtils.isNotBlank(purpose)) {
            criteria.andWgPurposeEqualTo(purpose);
        }
        if (StringUtils.isNotEmpty(wgCode)) {
            if ("zswg".equals(wgCode)) {
                criteria.andWgTypeEqualTo("2");//查询所有专属网格
            } else {
                criteria.andWgParentIdEqualTo(wgCode);
            }
        }

        int count = gridRegionService.countByExample(example);
        if (count <= 0) {
            result.buildSuccess("success", appPageModel);
            return;
        }
        example.setOrderByClause(" wg_code");
        List<GridRegion> roles = gridRegionService.selectByExampleWithBLOBsForStartPage(example, pageNum, pageSize);
        if (null == roles || roles.isEmpty()) {
            result.buildSuccess("success", appPageModel);
            return;
        }
//        List<GridRegion> res = new ArrayList<>();
//        if(!(regions.size()==1 && regions.get(0).equals("320282001"))){
//            Map<String,Integer> map = new HashMap<>();
//            for(String region: regions){
//                map.put(region, 1);
//            }
//            for(GridRegion region: roles){
//                if(map.containsKey(region.getWgCode())){
//                    res.add(region);
//                }
//            }
//        }else{
//            res = roles;
//        }


        appPageModel.setCurPage(pageNum);
//        appPageModel.setRecordCount(res.size());
        appPageModel.setRecordCount(count);
        appPageModel.setPageCount((long) Math.ceil(1.0 * count / pageSize));
        if(level!=null && level.equals("3")){
            for(GridRegion role : roles) {
                String type = role.getWgType();
                String code = role.getWgParentId();
                List<GridRegion> twoLevel = gridRegionMapper.selectAllByIdAndWgType(type,code);
                if(twoLevel != null && !twoLevel.isEmpty()) {
                    role.setpId(twoLevel.get(0).getId());
                    role.setpName(twoLevel.get(0).getWgName());
                }
            }
        }
//        List<GridRegionWithCompanyItem> itemList = BeanCopyUtil.bathToBean(res, GridRegionWithCompanyItem.class);
    List<GridRegionWithCompanyItem> itemList = BeanCopyUtil.bathToBean(roles, GridRegionWithCompanyItem.class);
        itemList.forEach( e -> {
            GridCompanyLandExample gridCompanyLandExample = new GridCompanyLandExample();
            GridCompanyLandExample.Criteria gridCompanyLandExampleCriteria = gridCompanyLandExample.createCriteria();
            gridCompanyLandExampleCriteria.andLandIdEqualTo(e.getId());
            gridCompanyLandExampleCriteria.andIsValidEqualTo("1");
            e.setCompanyCount(companyLandService.countByExample(gridCompanyLandExample));
        });
        appPageModel.setItemList(itemList);
        result.buildSuccess("success", appPageModel);
    }

    public List<GridRegion> getRolesForExample(String wgType, String wgCode) {
        GridRegionExample example = new GridRegionExample();
        GridRegionExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotEmpty(wgType)) {
            criteria.andWgTypeEqualTo(wgType);
        }
        if (StringUtils.isNotEmpty(wgCode)) {
            criteria.andWgCodeEqualTo(wgCode);
        }
        List<GridRegion> roles = gridRegionService.selectByExampleWithBLOBs(example);
        return roles;
    }

    public GridTreeNode getTreeNode(String wgName, String wgType, String isShow) {
        GridRegionExample example = new GridRegionExample();
        GridRegionExample.Criteria criteria = example.createCriteria();
        criteria.andIsValidEqualTo("1");
        if (StringUtils.isNotEmpty(wgName)) {
            criteria.andWgNameLike("%" + wgName + "%");
        }
        if (StringUtils.isNotEmpty(wgType)) {
            criteria.andWgTypeEqualTo(wgType);
        }
        if(StringUtils.isNotBlank(isShow) && isShow.equals("false")){
            criteria.andLevelNotEqualTo("4");
        }
        example.setOrderByClause("wg_code asc ");
        List<GridRegion> gridRegionList = gridRegionService.selectByExample(example);
        GridTreeNode treeNodes = new GridTreeNode();
        if ("2".equals(wgType)) {
            List<GridTreeNode> myChildrens = new ArrayList<GridTreeNode>();
            for (GridRegion gridRegion : gridRegionList) {
                GridTreeNode secondNode = new GridTreeNode();
                secondNode.setId(gridRegion.getId());
                secondNode.setCode(gridRegion.getWgCode());
                secondNode.setName(gridRegion.getWgName());
                secondNode.setParentId("zswg");
                myChildrens.add(secondNode);
            }
            treeNodes.setChild(myChildrens);
            treeNodes.setId("zswg");
            treeNodes.setCode("zswg");
            treeNodes.setName("专属网格");
        } else if ("3".equals(wgType)) {
            List<GridTreeNode> myChildrens = new ArrayList<GridTreeNode>();
            SysRole roleParam = new SysRole();
            roleParam.setStatus("0");
            List<SysRole> roles = sysRoleService.selectRoleList(roleParam);
            for (SysRole role : roles) {
                GridTreeNode secondNode = new GridTreeNode();
                secondNode.setId(role.getRoleId().toString());
                secondNode.setCode(role.getRoleKey());
                secondNode.setName(role.getRoleName());
                secondNode.setParentId("roleNode");
                myChildrens.add(secondNode);
            }
            treeNodes.setChild(myChildrens);
            treeNodes.setId("roleNode");
            treeNodes.setCode("roleNode");
            treeNodes.setName("网格角色");
        } else {
            treeNodes = listToTree(gridRegionList);

        }
        return treeNodes;
    }

    public GridTreeNode listToTree(List<GridRegion> dicList) {
        List<GridTreeNode> rootTrees = new ArrayList<GridTreeNode>();
        GridTreeNode rootNode = new GridTreeNode();
        for (GridRegion dicTree : dicList) {
            if ("1".equals(dicTree.getLevel())) {
                rootNode.setName(dicTree.getWgName());
                rootNode.setId(dicTree.getId());
                rootNode.setCode(dicTree.getWgCode());
                rootNode.setWgArea(dicTree.getWgArea());
                rootNode.setLevel(dicTree.getLevel());
//                rootNode.setWgCentreCoordinate(dicTree.getWgCentreCoordinate());
//                rootNode.setWgCoordinate(dicTree.getWgCoordinate());
            }
            //二级网格
            if ("2".equals(dicTree.getLevel())) {
                GridTreeNode treeNode = new GridTreeNode();
                treeNode.setId(dicTree.getId());
                treeNode.setCode(dicTree.getWgCode());
                treeNode.setName(dicTree.getWgName());
                treeNode.setWgArea(dicTree.getWgArea());
                treeNode.setLevel(dicTree.getLevel());
//                treeNode.setWgCentreCoordinate(dicTree.getWgCentreCoordinate());
//                treeNode.setWgCoordinate(dicTree.getWgCoordinate());
                rootTrees.add(treeNode);
            }
        }
        for (GridTreeNode treeNode : rootTrees) {
            List<GridTreeNode> myChildrens = new ArrayList<GridTreeNode>();
            for (GridRegion gridRegion : dicList) {
                if (treeNode.getCode().equals(gridRegion.getWgParentId())) {
                    GridTreeNode secondNode = new GridTreeNode();
                    secondNode.setId(gridRegion.getId());
                    secondNode.setCode(gridRegion.getWgCode());
                    secondNode.setName(gridRegion.getWgName());
                    secondNode.setParentId(treeNode.getId());
                    secondNode.setWgArea(gridRegion.getWgArea());
                    secondNode.setLevel(gridRegion.getLevel());
//                    secondNode.setWgCentreCoordinate(gridRegion.getWgCentreCoordinate());
//                    secondNode.setWgCoordinate(gridRegion.getWgCoordinate());
                    myChildrens.add(secondNode);

                }
            }

            treeNode.setChild(myChildrens);
            if (myChildrens.size() > 0) {
                for (GridTreeNode myChildren : myChildrens) {
                    List<GridTreeNode> thrdChildrens = new ArrayList<GridTreeNode>();
                    for (GridRegion gridRegion : dicList) {
                        if (myChildren.getCode().equals(gridRegion.getWgParentId())) {
                            GridTreeNode thrdNode = new GridTreeNode();
                            thrdNode.setId(gridRegion.getId());
                            thrdNode.setCode(gridRegion.getWgCode());
                            thrdNode.setName(gridRegion.getWgName());
                            thrdNode.setParentId(myChildren.getId());
                            thrdNode.setWgArea(gridRegion.getWgArea());
                            thrdNode.setLevel(gridRegion.getLevel());
                            thrdChildrens.add(thrdNode);

                        }
                    }
                    myChildren.setChild(thrdChildrens);
                }

            }
        }

        rootNode.setChild(rootTrees);

        return rootNode;
    }

    public boolean deletePre(GridRegion body, AjaxResult result) {
        if (null == body) {
            result.buildError(400, "body为空");
            return false;
        }

        if (!itemIsUUID(body.getId())) {
            result.buildError(400, "body里的id为空或非法");
            return false;
        }

        return true;
    }

    public void delete(GridRegion body, AjaxResult result) {
        GridRegion bean = get(body.getId(), null);
        if (null == bean) {
            result.buildError(400, "找不到该角色");
            return;
        }

        // 如果该网格下有子网格，则无法删除
        GridRegionExample gridRegionExample = new GridRegionExample();
        gridRegionExample.createCriteria().andIsValidEqualTo("1").andWgParentIdEqualTo(bean.getWgCode());
        int count = gridRegionService.countByExample(gridRegionExample);
        if (count > 0) {
            result.buildError(600, "该网格下有子网格，无法删除");
            return;
        }

        // 防止数据残留
        int ret = gridRegionService.deleteByStringPrimaryKey(body.getId());
        if (ret > 0) {
            result.buildSuccess("success", "1");
        } else {
            result.buildError(600, "删除失败");
        }

        return;
    }

    /**
     * 自动生成基础网格编码
     *
     * @return
     */
    public String autoGenerationWgcode(String parentCode) {
        GridRegionExample example = new GridRegionExample();
        String code = "";
        if (!StringUtils.isNotBlank(parentCode)) {
            example.createCriteria().andWgTypeEqualTo("1").andWgParentIdIsNull();
            int count = gridRegionService.countByExample(example);
            if (count <= 0) {
                code = baseCode;
            }
        } else {
            example.createCriteria().andWgTypeEqualTo("1").andWgParentIdEqualTo(parentCode);
            example.setOrderByClause("wg_code DESC");
            int count = gridRegionService.countByExample(example);
            if (count <= 0) {
                code = parentCode + "001";
            } else {
                List<GridRegion> gridRegionList = gridRegionService.selectByExample(example);
                GridRegion gridRegion = gridRegionList.get(0);//取最大的一个wg_code
                long wgcode = Long.valueOf(gridRegion.getWgCode()) + 1;
                code = String.valueOf(wgcode);
            }
        }


        return code;
    }


    private boolean itemIsUUID(String item) {
        if (StringUtils.isEmpty(item)) {
            return false;
        }
        return item.matches("(\\w{8}(-\\w{4}){3}-\\w{12}?)");
    }


    public GridTreeNode treeNode(String wgType, List<String> wgCodeList,String isShow) {
        GridRegionSearchParam param = new GridRegionSearchParam();
        if(!CollectionUtils.isEmpty(wgCodeList)){
            param.setWgCodeLikes(wgCodeList);
        }
        param.setWgType(wgType);
        if (StringUtils.isEmpty(isShow) || "false".equals(isShow)) {
            param.setShow(false);
        }
        List<GridRegion> gridRegionList = gridRegionMapper.getByParams(param);
        GridTreeNode treeNodes = new GridTreeNode();
        if ("2".equals(wgType)) {
            List<GridTreeNode> myChildrens = new ArrayList<GridTreeNode>();
            for (GridRegion gridRegion : gridRegionList) {
                GridTreeNode secondNode = new GridTreeNode();
                secondNode.setId(gridRegion.getId());
                secondNode.setCode(gridRegion.getWgCode());
                secondNode.setName(gridRegion.getWgName());
                secondNode.setWgArea(gridRegion.getWgArea());
//                secondNode.setWgCentreCoordinate(gridRegion.getWgCentreCoordinate());
//                secondNode.setWgCoordinate(gridRegion.getWgCoordinate());
                secondNode.setParentId("zswg");
                myChildrens.add(secondNode);
            }
            treeNodes.setChild(myChildrens);
            treeNodes.setId("zswg");
            treeNodes.setCode("zswg");
            treeNodes.setName("专属网格");
        } else {

            treeNodes = listToTree(gridRegionList);
        }
        return treeNodes;
    }


    public void getRegionListByExample(GridRegionExample example, AjaxResult result) {
        example.setOrderByClause(" update_time desc ");
        List<GridRegion> gridRegionList = gridRegionService.selectByExampleWithBLOBs(example);
        result.buildSuccess("success", gridRegionList);
    }

    public void getRegionByExample(GridRegionExample example, AjaxResult result) {
        example.setOrderByClause(" update_time desc ");
        List<GridRegion> gridRegionList = gridRegionService.selectByExampleWithBLOBs(example);
        GridRegion gridRegion = new GridRegion();
        if (!gridRegionList.isEmpty()) {
            gridRegion = gridRegionList.get(0);
        }
        result.buildSuccess("success", gridRegion);
    }

    public void getChildRegion(GridRegionExample example, String dxlx, String qylx, AjaxResult result) {
        example.setOrderByClause(" update_time desc ");
        List<GridRegion> gridRegionList = gridRegionService.selectByExampleWithBLOBs(example);
        for (GridRegion gridRegion : gridRegionList) {
//            BsWgdxbExample bsWgdxbExample = new BsWgdxbExample();
//            BsWgdxbExample.Criteria criteria = bsWgdxbExample.createCriteria();
//            if (StringUtils.isNotEmpty(qylx)) {
//                criteria.andQylxLike("%" + qylx + "%");
//            }
//            criteria.andBaseIdEqualTo(gridRegion.getBaseId()).andWgIdLike(gridRegion.getWgCode() + "%").andDxlxEqualTo(dxlx).andIsValidEqualTo("1");
//            int count = bsWgdxbService.countByExample(bsWgdxbExample);
//            gridRegion.setYlzd1(Integer.toString(count));
            gridRegion.setYlzd1("0");
        }
        result.buildSuccess("success", gridRegionList);
    }

    public void countRoleUserByWgcode(String wgCode, AjaxResult result) {
        List<GridRegionUser> twoGridUser = new ArrayList<>();
        GridRegion gridRegion = gridRegionMapper.getWgLevel(wgCode);
        String level = gridRegion.getLevel();
        if ("1".equals(level)) {
            List<GridRegionUser> bsRegionUsers = bsRegionUserMapper.selectOneGridUserByWgCode(wgCode);
            if (bsRegionUsers.size() > 0) twoGridUser.add(bsRegionUsers.get(0));

        } else if ("3".equals(level)) {
            List<GridRegionUser> bsRegionUsers = bsRegionUserMapper.selectParentGirdUserByWgCode(wgCode);
            if (bsRegionUsers.size() > 0) twoGridUser.add(bsRegionUsers.get(0));
        } else {
            twoGridUser = bsRegionUserMapper.selectTwoGridUserByWgCode(wgCode);
        }

        List<GridRegionUser> threeGirdUser = bsRegionUserMapper.selectThreeGirdUserByWgCode(wgCode);
        try {
            if (!twoGridUser.isEmpty()) {
                for (GridRegionUser bsRegionUser : twoGridUser) {
                    String ylzd4 = bsRegionUser.getYlzd4();//是否党员
                    bsRegionUser.setYlzd2(ylzd4);

                    SysUser sysUser = userService.selectUserById(bsRegionUser.getUserId());
                    bsRegionUser.setYlzd3(sysUser.getPhonenumber());
                    bsRegionUser.setYlzd5(sysUser.getAvatar());
                    bsRegionUser.setYlzd4(gridRegionMapper.getWgNameByCode(bsRegionUser.getWgId()));
                }
            }
            if (!threeGirdUser.isEmpty()) {
                for (GridRegionUser bsRegionUser : threeGirdUser) {
                    String ylzd4 = bsRegionUser.getYlzd4();//是否党员
                    bsRegionUser.setYlzd2(ylzd4);
                    SysUser sysUser = userService.selectUserById(bsRegionUser.getUserId());
                    bsRegionUser.setYlzd3(sysUser.getPhonenumber());
                    bsRegionUser.setYlzd5(sysUser.getAvatar());
                    bsRegionUser.setYlzd4(gridRegionMapper.getWgNameByCode(bsRegionUser.getWgId()));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        GridRegionExample example = new GridRegionExample();
        example.createCriteria().andWgParentIdEqualTo(wgCode).andIsValidEqualTo("1");
        int count = gridRegionService.countByExample(example);
        Map<Object, Object> map = new HashMap<>();
        map.put("twoGridUser", twoGridUser);
        map.put("threeGirdUser", threeGirdUser);
        map.put("count", count);
        result.buildSuccess("success", map);
        return;
    }

    public List<GridRegion> selectThirdGridByBaseId() {
        List<GridRegion> regions = gridRegionMapper.selectThirdGridByBaseId();
        return regions;
    }

    public void getRegionListByWgmj(GridRegionExample example, AjaxResult result) {
        List<GridRegion> gridRegionList = gridRegionService.selectByExampleWithBLOBs(example);
        double count = 0;
        for (int i = 0; i < gridRegionList.size(); i++) {
            if (StringUtils.isNotEmpty(gridRegionList.get(i).getWgArea())) {
                count = count + Double.parseDouble(gridRegionList.get(i).getWgArea());
            }
        }
        result.buildSuccess("success", count);
        return;
    }

    public void getRegionListForTreeNode(String wgCode, String wgType, AjaxResult result) {
        GridRegionExample regionExample = new GridRegionExample();
        GridRegionExample.Criteria criteria = regionExample.createCriteria();
        criteria.andIsValidEqualTo("1");
        if (StringUtils.isNotEmpty(wgCode)) {
            criteria.andWgCodeLike(wgCode + "%");
        }
        if (StringUtils.isNotEmpty(wgType)) {
            criteria.andWgTypeEqualTo(wgType);
        }
        List<GridRegion> regionList = gridRegionService.selectByExampleWithBLOBs(regionExample);
        List<Map<String, Object>> jsTreeModels = convertFromWgCode(regionList, wgCode);
        result.buildSuccess("success", jsTreeModels);
        return;
    }

    private List<Map<String, Object>> convertFromWgCode(List<GridRegion> regionList, String rootId) {
        List<Map<String, Object>> models = new ArrayList<>();

        if (!CollectionUtils.isEmpty(regionList)) {
            for (GridRegion region : regionList) {
                if (StringUtils.isNotEmpty(region.getWgCode()) && region.getWgCode().equals(rootId)) {
                    Map<String, Object> model = new HashMap<>();
                    model.put("id", region.getId());
                    model.put("code", region.getWgCode());
                    model.put("wgType", region.getWgType());
                    model.put("name", region.getWgName());
                    model.put("parentId", region.getWgParentId());
                    model.put("wgArea", region.getWgArea());
//                    model.put("wgCoordinate", region.getWgCoordinate());
//                    model.put("wgCentreCoordinate", region.getWgCentreCoordinate());
                    List<Map<String, Object>> childrenDocTypes = convertFromWgCodeByParent(regionList, region.getWgCode());
                    model.put("child", childrenDocTypes);
                    models.add(model);
                }
            }
        }
        return models;
    }

    private List<Map<String, Object>> convertFromWgCodeByParent(List<GridRegion> regionList, String parentId) {
        List<Map<String, Object>> models = new ArrayList<>();

        for (GridRegion region : regionList) {
            if (StringUtils.isNotEmpty(region.getWgCode()) && StringUtils.isNotEmpty(region.getWgParentId()) && region.getWgParentId().equals(parentId)) {
                Map<String, Object> model = new HashMap<>();
                model.put("id", region.getId());
                model.put("code", region.getWgCode());
                model.put("wgType", region.getWgType());
                model.put("name", region.getWgName());
                model.put("parentId", region.getWgParentId());
                model.put("wgArea", region.getWgArea());
//                model.put("wgCoordinate", region.getWgCoordinate());
//                model.put("wgCentreCoordinate", region.getWgCentreCoordinate());
                List<Map<String, Object>> childrenDocTypes = convertFromWgCodeByParent(regionList, region.getWgCode());
                model.put("child", childrenDocTypes);
                models.add(model);
            }
        }
        return models;
    }


    public void selectThirdGridNameByBaseId(AjaxResult result, Integer pageNum, Integer pageSize) {
        if (null == pageNum || pageNum <= 0) {
            pageNum = 1;
        }
        if (null == pageSize || pageSize <= 0) {
            pageSize = 10;
        }

        ZQTPageModel<GridRegion> appPageModel = new ZQTPageModel<>();
        appPageModel.setRecordCount(0);
        appPageModel.setPageCount(0);
        appPageModel.setCurPage(pageNum);
        appPageModel.setItemList(new ArrayList<>());

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

        int count = gridRegionService.countByExample(example);
        if (count <= 0) {
            result.buildSuccess("success", appPageModel);
            return;
        }
        PageHelper.startPage(pageNum, pageSize);
        List<GridRegion> gridRegionList = gridRegionMapper.selectThirdGridNameByBaseId();
        if (null == gridRegionList || gridRegionList.isEmpty()) {
            result.buildSuccess("success", appPageModel);
            return;
        }
        PageInfo page = new PageInfo(gridRegionList);
        appPageModel.setCurPage(page.getPageNum());
        appPageModel.setRecordCount(page.getTotal());
        appPageModel.setPageCount(page.getPages());
        appPageModel.setItemList(page.getList());
        result.buildSuccess("success", appPageModel);
        return;
    }

    public List<GridTreeNode> getWsTreeNode(String wgType, List<String> wgList, String isShow, List<String> regions) {
//public List<GridTreeNode> getWsTreeNode(String wgType, List<String> wgList, String isShow) {
        GridRegionSearchParam param = new GridRegionSearchParam();
        param.setWgType(wgType);
        if(!CollectionUtils.isEmpty(wgList)){
            param.setWgCodeLikes(wgList);
        }
        if (StringUtils.isEmpty(isShow) || "false".equals(isShow)) {
            param.setShow(false);
        }
        List<GridRegion> gridRegionList = gridRegionMapper.getByParams(param);
//        return convertFrRegion(gridRegionList, wgList);
        List<GridTreeNode> res = convertFrRegion(gridRegionList, wgList);
        List<GridTreeNode> degree_second = new ArrayList<>();
        if(!(regions.size()==1 && regions.get(0).equals("320282001"))){
            Map<String,Integer> map = new HashMap<>();
            for(String region: regions){
                map.put(region, 1);
            }
            for(GridTreeNode region: res.get(0).getChild()){
                if(map.containsKey(region.getCode())){
                    degree_second.add(region);
                }
            }
            res.get(0).setChild(degree_second);
        }
        return res;
    }

    private List<GridTreeNode> convertFrRegion(List<GridRegion> gridRegionList, List<String> wgCodes) {
        List<GridTreeNode> models = new ArrayList<>();

        if (gridRegionList.size() > 0) {
            for (GridRegion gridRegion : gridRegionList) {
                if (StringUtils.isNotEmpty(gridRegion.getWgParentId()) && wgCodes.contains(gridRegion.getWgCode())) {
                    GridTreeNode secondNode = new GridTreeNode();
                    secondNode.setId(gridRegion.getId());
                    secondNode.setCode(gridRegion.getWgCode());
                    secondNode.setName(gridRegion.getWgName());
                    secondNode.setWgArea(gridRegion.getWgArea());
                    secondNode.setLevel(gridRegion.getLevel());
                    secondNode.setStatus(gridRegion.getStatus());
                    List<GridTreeNode> childrenDocTypes = convertRegionFromWgCodeByParent(gridRegionList, gridRegion.getWgCode());
                    secondNode.setChild(childrenDocTypes);
                    models.add(secondNode);
                } else if (StringUtils.isEmpty(gridRegion.getWgParentId())) {
                    GridTreeNode secondNode = new GridTreeNode();
                    secondNode.setId(gridRegion.getId());
                    secondNode.setCode(gridRegion.getWgCode());
                    secondNode.setName(gridRegion.getWgName());
                    secondNode.setWgArea(gridRegion.getWgArea());
                    secondNode.setLevel(gridRegion.getLevel());
                    secondNode.setStatus(gridRegion.getStatus());
                    List<GridTreeNode> childrenDocTypes = convertRegionFromWgCodeByParent(gridRegionList, gridRegion.getWgCode());
                    secondNode.setChild(childrenDocTypes);
                    models.add(secondNode);
                    break;
                }
            }
        }
        return models;
    }


    private List<GridTreeNode> convertRegionFromWgCodeByParent(List<GridRegion> gridRegionList, String wgParentId) {
        List<GridTreeNode> models = new ArrayList<>();

        for (GridRegion gridRegion : gridRegionList) {
            if (StringUtils.isNotEmpty(gridRegion.getWgParentId()) && gridRegion.getWgParentId().equals(wgParentId)) {
                GridTreeNode secondNode = new GridTreeNode();
                secondNode.setId(gridRegion.getId());
                secondNode.setCode(gridRegion.getWgCode());
                secondNode.setName(gridRegion.getWgName());
                secondNode.setWgArea(gridRegion.getWgArea());
                secondNode.setLevel(gridRegion.getLevel());
                secondNode.setStatus(gridRegion.getStatus());
                List<GridTreeNode> childrenDocTypes = convertRegionFromWgCodeByParent(gridRegionList, gridRegion.getWgCode());
                secondNode.setChild(childrenDocTypes);
                models.add(secondNode);
            }
        }
        return models;
    }


    public void getAreaList(String wgName, String wgCode, Integer pageNum, Integer pageSize, AjaxResult result) {
        if (null == pageNum || pageNum <= 0) {
            pageNum = 1;
        }
        if (null == pageSize || pageSize <= 0) {
            pageSize = 10;
        }

        ZQTPageModel<GridRegionExt> appPageModel = new ZQTPageModel<>();
        appPageModel.setRecordCount(0);
        appPageModel.setPageCount(0);
        appPageModel.setCurPage(pageNum);
        appPageModel.setItemList(new ArrayList<>());

        GridRegionExample example = new GridRegionExample();
        GridRegionExample.Criteria criteria = example.createCriteria();
        criteria.andIsValidEqualTo("1");
        if (StringUtils.isNotEmpty(wgName)) {
            criteria.andWgNameLike("%" + wgName + "%");
        }
        if (StringUtils.isNotEmpty(wgCode)) {
//            criteria.andWgCodeLike(wgCode + "%").andLevelEqualTo("4");
            criteria.andWgCodeLike(wgCode + "%").andLevelEqualTo("2").andWgTypeEqualTo("1");
        }
        try {
            int count = gridRegionService.countByExample(example);
            if (count <= 0) {
                result.buildSuccess("success", appPageModel);
                return;
            }
            example.setOrderByClause(" wg_code");
            List<GridRegion> roles = gridRegionService.selectByExampleWithBLOBsForStartPage(example, pageNum, pageSize);
            if (null == roles || roles.isEmpty()) {
                result.buildSuccess("success", appPageModel);
                return;
            }
            List<GridRegionExt> resultList = new ArrayList<GridRegionExt>();
            for (GridRegion gridRegion : roles) {
                GridRegionExt regionExt = new GridRegionExt();
                PropertyUtils.copyProperties(regionExt, gridRegion);
                GridHouseExample houseExample = new GridHouseExample();
                GridPeopleExample peopleExample = new GridPeopleExample();
                GridCompanyExample companyExample = new GridCompanyExample();
                GridShopExample shopExample = new GridShopExample();
                houseExample.createCriteria().andWgCodeLike(regionExt.getWgCode() + "%");
                peopleExample.createCriteria().andWgCodeLike(regionExt.getWgCode() + "%");
                companyExample.createCriteria().andWgCodeLike(regionExt.getWgCode() + "%");
                shopExample.createCriteria().andWgCodeLike(regionExt.getWgCode() + "%");

                int houseCount = wsHouseService.countByExample(houseExample);
                int peopleCount = gridPeopleService.countByExample(peopleExample);
                int companyCount = (int) gridCompanyMapper.countByExample(companyExample);
                int shopCount = (int) gridShopMapper.countByExample(shopExample);
                regionExt.setHouseCount(houseCount);
                regionExt.setPersonCount(peopleCount);
                regionExt.setCompanyCount(companyCount);
                regionExt.setShopCount(shopCount);

                GridRegionExample regionExample = new GridRegionExample();
                regionExample.createCriteria().andWgCodeEqualTo(gridRegion.getWgParentId()).andIsValidEqualTo("1");
                List<GridRegion> gridRegionList = gridRegionMapper.selectByExample(regionExample);
                if (gridRegionList.size() > 0) regionExt.setParentName(gridRegionList.get(0).getWgName());//上级网格名

                resultList.add(regionExt);
            }
            appPageModel.setCurPage(pageNum);
            appPageModel.setRecordCount(count);
            appPageModel.setPageCount((long) Math.ceil(1.0 * count / pageSize));
            appPageModel.setItemList(resultList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.buildSuccess("success", appPageModel);
    }

    public void getWsParentRegionAndCount(String wgCode, AjaxResult result) {
        Map<String, Object> ret = new HashMap<String, Object>();
        //网格数
        GridRegionExample wgsExample = new GridRegionExample();
        wgsExample.createCriteria().andIsValidEqualTo("1").andWgTypeEqualTo("1").andWgCodeLike(wgCode + "%").andLevelEqualTo("3");
        long wgsCount = gridRegionMapper.countByExample(wgsExample);
        //网格员数
        GridRegionUserExample userExample = new GridRegionUserExample();
        GridRegionUserExample.Criteria userExampleCriteria = userExample.createCriteria();
        List<GridRegion> gridRegionList = gridRegionMapper.selectByExample(wgsExample);
        List<String> threeCodeList = gridRegionList.stream().map(GridRegion::getWgCode).collect(Collectors.toList());
        long wgUserCount = 0;
        if (threeCodeList.size() > 0) {
            userExampleCriteria.andIsValidEqualTo("1").andWgIdIn(threeCodeList);
            wgUserCount = bsRegionUserMapper.countByExample(userExample);
        }
        //地块数
        GridRegionExample dksExample = new GridRegionExample();
        dksExample.createCriteria().andIsValidEqualTo("1").andWgTypeEqualTo("1").andWgCodeLike(wgCode + "%").andLevelEqualTo("4");
        long dksCount = gridRegionMapper.countByExample(dksExample);

        //事项数
        GridItemDailyExample rcsxbExample = new GridItemDailyExample();
        rcsxbExample.createCriteria().andIsValidEqualTo("1").andSjflNotEqualTo("rcsx");
        long rcsxCount = gridItemDailyMapper.countByExample(rcsxbExample);

        //专属网格数
        GridRegionExample regionExample = new GridRegionExample();
        regionExample.createCriteria().andIsValidEqualTo("1").andWgTypeEqualTo("1")
                .andWgCodeLike(wgCode + "%").andLevelEqualTo("3").andYlzd2EqualTo("1");
        long zsCount = gridRegionMapper.countByExample(regionExample);

        ret.put("wgsCount", wgsCount);
        ret.put("wgUserCount", wgUserCount);
        ret.put("dksCount", dksCount);
        ret.put("rcsxCount", rcsxCount);
        ret.put("zsCount", zsCount);
        ret.put("jcCount", wgsCount - zsCount);
        result.buildSuccess("success", ret);
    }

    /**
     * 获取三级网格下的网格员
     * @param wgcodeList
     * @return
     */
    public List<GridRegionUser> getRegionUserListForList(List<String> wgcodeList) {
        GridRegionUserExample bsRegionUserExample = new GridRegionUserExample();
        GridRegionUserExample.Criteria criteria = bsRegionUserExample.createCriteria();
        criteria.andIsValidEqualTo("1").andWgIdIn(wgcodeList);
        return bsRegionUserMapper.selectByExample(bsRegionUserExample);
    }

    public List<Map<String, String>> getThirdWgList(String[] wgcodeList) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("wgcodeList", wgcodeList);
        List<GridRegion> gridRegionList = gridRegionExtMapper.getThirdWgList(map);
        ArrayList<Map<String, String>> result = new ArrayList<>();

        gridRegionList.forEach(gridRegion -> {
            HashMap<String, String> body = new HashMap<>();
            body.put("id", gridRegion.getId());
            body.put("wgCode", gridRegion.getWgCode());
            body.put("wgName", gridRegion.getWgName());
            body.put("level", gridRegion.getLevel());
            result.add(body);
        });
        return result;
    }

    public PageInfo<Map<String, Object>> getObjList(GridDxbVO wgdxbVO) {
        if ("1".equals(wgdxbVO.getOptionType())) wgdxbVO.setPageSize(wgdxbVO.getSuijiCount());//随机数
        PageHelper.startPage(wgdxbVO.getPageNum(), wgdxbVO.getPageSize());
        List<Map<String, Object>> result = new ArrayList<>();
        int count = 0;
        if ("qy".equals(wgdxbVO.getDxlx())) {
            //判断随机还是固定
            GridCompanyExample companyExample = new GridCompanyExample();
            GridCompanyExample.Criteria criteria = companyExample.createCriteria();
            criteria.andIsValidEqualTo(Byte.valueOf("1")).andWgCodeIn(Arrays.asList(wgdxbVO.getWgCodeList()));
            if (StringUtils.isNotEmpty(wgdxbVO.getName())) {
                criteria.andCompanyNameLike("%" + wgdxbVO.getName() + "%");
            }
            if(StringUtils.isNotBlank(wgdxbVO.getQylx())){
                List<String> qylxList = Arrays.asList(wgdxbVO.getQylx().split(","));
                criteria.andQylxCodeIn(qylxList);
            }
            if ("1".equals(wgdxbVO.getOptionType())) {//随机
                companyExample.setOrderByClause("RAND()");
            }
            List<GridCompany> wsCompanyList = gridCompanyMapper.selectByExample(companyExample);
            count = (int) gridCompanyMapper.countByExample(companyExample);
            wsCompanyList.forEach(wsCompany -> {
                HashMap<String, Object> map = new HashMap<>();
                map.put("obj_id", wsCompany.getId());
                map.put("obj_number", wsCompany.getCreditCode());
                map.put("obj_name", wsCompany.getCompanyName());
                map.put("obj_user_name", wsCompany.getLawPerson());
                map.put("obj_wg_code", wsCompany.getWgCode());
                result.add(map);
            });

        }
        if ("sh".equals(wgdxbVO.getDxlx())) {
            GridShopExample shopExample = new GridShopExample();
            GridShopExample.Criteria criteria = shopExample.createCriteria();
            criteria.andValidEqualTo(Byte.valueOf("1")).andWgCodeIn(Arrays.asList(wgdxbVO.getWgCodeList()));
            if (StringUtils.isNotEmpty(wgdxbVO.getName())) {
                criteria.andShopNameLike("%" + wgdxbVO.getName() + "%");
            }
            if(StringUtils.isNotBlank(wgdxbVO.getQylx())){
                List<String> qylxList = Arrays.asList(wgdxbVO.getQylx().split(","));
                criteria.andShopTypeIn(qylxList);
            }
            if ("1".equals(wgdxbVO.getOptionType())) {//随机
                shopExample.setOrderByClause("RAND()");
            }
            List<GridShop> shopList = gridShopMapper.selectByExample(shopExample);
            count = (int) gridShopMapper.countByExample(shopExample);
            shopList.forEach(wsShop -> {
                HashMap<String, Object> map = new HashMap<>();
                map.put("obj_id", wsShop.getId());
                map.put("obj_number", wsShop.getLicenseCode());
                map.put("obj_name", wsShop.getShopName());
                map.put("obj_user_name", wsShop.getShopOwner());
                map.put("obj_wg_code", wsShop.getWgCode());
                result.add(map);
            });
        }
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(result);
        return ZQTPageUtil.build(pageInfo, wgdxbVO.getPageNum(), wgdxbVO.getPageSize(), count);
    }

    public PageInfo<Map<String, Object>> getHouseObjList(GridDxbVO wgdxbVO) {
        if ("1".equals(wgdxbVO.getOptionType())) wgdxbVO.setPageSize(wgdxbVO.getSuijiCount());//随机数
        PageHelper.startPage(wgdxbVO.getPageNum(), wgdxbVO.getPageSize());
        List<Map<String, Object>> result = new ArrayList<>();

        GridHouseExample houseExample = new GridHouseExample();
        GridHouseExample.Criteria criteria = houseExample.createCriteria();
        criteria.andIsValidEqualTo(Byte.valueOf("1"))
                .andWgCodeIn(Arrays.asList(wgdxbVO.getWgCodeList())).andFwlxCodeIn(Arrays.asList(wgdxbVO.getFwlxCodeList()));
        if ("1".equals(wgdxbVO.getOptionType())) {//随机
            houseExample.setOrderByClause("RAND()");
        }

        List<GridHouse> wsHouseList = wsHouseService.selectByExample(houseExample);
        int count = wsHouseService.countByExample(houseExample);
        wsHouseList.forEach(wsShop -> {
            HashMap<String, Object> map = new HashMap<>();
            map.put("obj_id", wsShop.getId());
            map.put("obj_name", wsShop.getHouseName());
            map.put("obj_user_name", wsShop.getPersonName());
            map.put("obj_wg_code", wsShop.getWgCode());
            map.put("fwlxCode", wsShop.getFwlxCode());
            result.add(map);
        });
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(result);
        return ZQTPageUtil.build(pageInfo, wgdxbVO.getPageNum(), wgdxbVO.getPageSize(), count);
    }

    /**
     * 层级级联树，最外层包了一层type，基础、经济，闲置，农业，商业字段
     * @param commonCode
     * @return
     */
    public List<GridLevelTreeNode> getLevelTreeNode(String commonCode, String isShow){
        List<BsCommon> bsCommonList = bsCommonService.getWgdxList(commonCode);
        if(!CollectionUtils.isEmpty(bsCommonList)){
            List<GridLevelTreeNode> list = new ArrayList<>();
            for(BsCommon bsCommon : bsCommonList){
                GridLevelTreeNode gridLevelTreeNode = new GridLevelTreeNode();
                gridLevelTreeNode.setValue(bsCommon.getCode());
                gridLevelTreeNode.setLabel(bsCommon.getName());
                GridTreeNode gridTreeNode = this.getTreeNode("", bsCommon.getCode(), isShow);
                if(gridTreeNode != null){
                    GridLevelTreeNode treeNode = new GridLevelTreeNode();
                    treeNode.setValue(gridTreeNode.getCode());
                    treeNode.setLabel(gridTreeNode.getName());
                    List<GridLevelTreeNode> child = new ArrayList<>();
                    child.add(treeNode);
                    gridLevelTreeNode.setChildren(child);
                    setLevelTreeChildValue(gridTreeNode.getChild(), treeNode);
                }
                list.add(gridLevelTreeNode);
            }
            return list;
        }
        return new ArrayList<>();
    }

    private void setLevelTreeChildValue(List<GridTreeNode> treeNodes, GridLevelTreeNode levelTreeNode){
        if(!CollectionUtils.isEmpty(treeNodes)){
            List<GridLevelTreeNode> childList = new ArrayList<>();
            for(GridTreeNode gridTreeNode : treeNodes){
                GridLevelTreeNode treeNode = new GridLevelTreeNode();
                treeNode.setValue(gridTreeNode.getCode());
                treeNode.setLabel(gridTreeNode.getName());
                if(!CollectionUtils.isEmpty(gridTreeNode.getChild())){
                    setLevelTreeChildValue(gridTreeNode.getChild(), treeNode);
                }
                childList.add(treeNode);
            }
            levelTreeNode.setChildren(childList);
        }
    }

    public List<SimpleWgItem> getEconomyPointList(String perMuRangeStart,
                                                  String perMuRangeEnd,
                                                  String year) {
        List<SimpleWgItem> gridRegionList = gridRegionExtMapper.getEconomyPointList(perMuRangeStart, perMuRangeEnd, year);
        if(!CollectionUtils.isEmpty(gridRegionList)){
            gridRegionList.forEach(e ->{
                if(StringUtils.isNotBlank(e.getWgCoordinate())){
                    String point = "MULTILINESTRING((" + e.getWgCoordinate().replaceAll("\\|"," ")+"))";
                    e.setWgCoordinate(point);
                }
                if(StringUtils.isNotBlank(e.getWgCenterCoordinate())){
                    String point = e.getWgCenterCoordinate().replaceAll("\\|"," ");
                    e.setWgCenterCoordinate(point);
                }
            });
        }
        return gridRegionList;
    }

    public List<GridTreeNode> getWsTreeNodeIncludeTwoPointFive(String wgType, List<String> wgList, String isShow, List<String> regions) {
//public List<GridTreeNode> getWsTreeNodeIncludeTwoPointFive(String wgType, List<String> wgList, String isShow) {
        //获取一级树
        List<GridRegion> gridRegionList = gridRegionMapper.getRegionByTypeAndCode("1",new ArrayList<>(),"1");
        List<GridTreeNode> res = new ArrayList<>();
        GridTreeNode firstNode = new GridTreeNode();
        firstNode.setLevel("1");
        firstNode.setCode(gridRegionList.get(0).getWgCode());
        firstNode.setName(gridRegionList.get(0).getWgName());
        firstNode.setId(gridRegionList.get(0).getId());
        firstNode.setChild(new ArrayList<>());
        firstNode.setParentId("");
        firstNode.setWgArea(gridRegionList.get(0).getWgArea());
        firstNode.setWgCoordinate(gridRegionList.get(0).getWgCoordinate());
        firstNode.setWgCentreCoordinate(gridRegionList.get(0).getWgCentreCoordinate());
        res.add(firstNode);
        //获取二级树
        List<GridTreeNode> nowNodes = new ArrayList<>();
        String firstNodeCode = gridRegionList.get(0).getWgCode();
        List<String> wgCodeLike = new ArrayList<>();
        wgCodeLike.add(firstNodeCode);
        gridRegionList = gridRegionMapper.getRegionByTypeAndCode("1",wgCodeLike,"2");
        for(GridRegion gridRegion : gridRegionList){
            GridTreeNode treeNode = convertNodeToTree(gridRegion);
            nowNodes.add(treeNode);
        }
        firstNode.setChild(nowNodes);
        //获取2.5级树
        List<GridTreeNode> secondTree = firstNode.getChild();

        for(GridTreeNode gridTreeNode : secondTree){
            List<GridTreeNode> secondFiveTree = new ArrayList<>();
            GridTreeNode secondFiveTreeNode1 = new GridTreeNode();
            secondFiveTreeNode1.setId(UUID.randomUUID().toString());
            secondFiveTreeNode1.setName("楼宇");
            secondFiveTreeNode1.setChild(new ArrayList<>());
            secondFiveTreeNode1.setStatus("2");
            secondFiveTreeNode1.setLevel("2.5");
            GridTreeNode secondFiveTreeNode4 = new GridTreeNode();
            secondFiveTreeNode4.setId(UUID.randomUUID().toString());
            secondFiveTreeNode4.setName("道路");
            secondFiveTreeNode4.setChild(new ArrayList<>());
            secondFiveTreeNode4.setStatus("2");
            secondFiveTreeNode4.setLevel("2.5");
            GridTreeNode secondFiveTreeNode5 = new GridTreeNode();
            secondFiveTreeNode5.setId(UUID.randomUUID().toString());
            secondFiveTreeNode5.setName("街区");
            secondFiveTreeNode5.setChild(new ArrayList<>());
            secondFiveTreeNode5.setStatus("2");
            secondFiveTreeNode5.setLevel("2.5");
            GridTreeNode secondFiveTreeNode6 = new GridTreeNode();
            secondFiveTreeNode6.setId(UUID.randomUUID().toString());
            secondFiveTreeNode6.setName("综合体");
            secondFiveTreeNode6.setChild(new ArrayList<>());
            secondFiveTreeNode6.setStatus("2");
            secondFiveTreeNode6.setLevel("2.5");
            GridTreeNode secondFiveTreeNode7 = new GridTreeNode();
            secondFiveTreeNode7.setId(UUID.randomUUID().toString());
            secondFiveTreeNode7.setName("市场");
            secondFiveTreeNode7.setChild(new ArrayList<>());
            secondFiveTreeNode7.setStatus("2");
            secondFiveTreeNode7.setLevel("2.5");
            secondFiveTree.add(secondFiveTreeNode1);
            secondFiveTree.add(secondFiveTreeNode4);
            secondFiveTree.add(secondFiveTreeNode5);
            secondFiveTree.add(secondFiveTreeNode6);
            secondFiveTree.add(secondFiveTreeNode7);
            for(GridTreeNode gridTreeNode1 : secondFiveTree){
                gridTreeNode1.setCode(gridTreeNode.getCode());
                String type = null;
                if(gridTreeNode1.getName().equals("楼宇")){
                    type = "1";
                }else if(gridTreeNode1.getName().equals("道路")){
                    type = "4";
                }else if(gridTreeNode1.getName().equals("街区")){
                    type = "5";
                }else if(gridTreeNode1.getName().equals("综合体")){
                    type = "6";
                }else{
                    type = "7";
                }
                List<GridRegion> threeLevelNode = gridRegionMapper.getAllLevelThreeByType(type,gridTreeNode1.getCode());
                List<GridTreeNode> threeNodes = new ArrayList<>();
                for(GridRegion gridRegion : threeLevelNode){
                    GridTreeNode treeNode = convertNodeToTree(gridRegion);
                    List<GridRegion> fourLevelNode = gridRegionMapper.getAllLevelFourByType(type,treeNode.getCode());
                    List<GridTreeNode> fourNodes = new ArrayList<>();
                    for(GridRegion gridFourRegion : fourLevelNode){
                        GridTreeNode treeFourNode = convertNodeToTree(gridFourRegion);
                        fourNodes.add(treeFourNode);
                    }
                    treeNode.setChild(fourNodes);
                    threeNodes.add(treeNode);
                }
                gridTreeNode1.setChild(threeNodes);
            }
            gridTreeNode.setChild(secondFiveTree);
        }

        List<GridTreeNode> degree_second = new ArrayList<>();
        if(!(regions.size()==1 && regions.get(0).equals("320282001"))){
            Map<String,Integer> map = new HashMap<>();
            for(String region: regions){
                map.put(region, 1);
            }
            for(GridTreeNode region: res.get(0).getChild()){
                if(map.containsKey(region.getCode())){
                    degree_second.add(region);
                }
            }
            res.get(0).setChild(degree_second);
        }


        return res;
    }

    private GridTreeNode convertNodeToTree(GridRegion gridRegion){
        GridTreeNode firstNode = new GridTreeNode();
        firstNode.setLevel(gridRegion.getLevel());
        firstNode.setCode(gridRegion.getWgCode());
        firstNode.setName(gridRegion.getWgName());
        firstNode.setId(gridRegion.getId());
        firstNode.setChild(new ArrayList<>());
        firstNode.setParentId(gridRegion.getWgParentId());
        firstNode.setWgArea(gridRegion.getWgArea());
        firstNode.setWgCoordinate(gridRegion.getWgCoordinate());
        firstNode.setWgCentreCoordinate(gridRegion.getWgCentreCoordinate());
        firstNode.setStatus(gridRegion.getStatus());
        return firstNode;
    }

    public void getRolesWhereTypeZero(String wgName, String wgCode, String wgType, String level, String purpose, Integer pageNum, Integer pageSize, AjaxResult result) {
        if (null == pageNum || pageNum <= 0) {
            pageNum = 1;
        }
        if (null == pageSize || pageSize <= 0) {
            pageSize = 10;
        }

        ZQTPageModel<GridRegionWithCompanyItem> appPageModel = new ZQTPageModel<>();
        appPageModel.setRecordCount(0);
        appPageModel.setPageCount(0);
        appPageModel.setCurPage(pageNum);
        appPageModel.setItemList(new ArrayList<>());
//
//        GridRegionExample example = new GridRegionExample();
//        GridRegionExample.Criteria criteria = example.createCriteria();
//        criteria.andIsValidEqualTo("1");
//        if (StringUtils.isNotEmpty(wgName)) {
//            criteria.andWgNameLike("%" + wgName + "%");
//        }
////        if (StringUtils.isNotEmpty(wgType)) {
////            criteria.andWgTypeEqualTo(wgType);
////        }
//        if (StringUtils.isNotEmpty(level)) {
//            criteria.andLevelEqualTo(level);
//        }
//        if (StringUtils.isNotBlank(purpose)) {
//            criteria.andWgPurposeEqualTo(purpose);
//        }
//        if (StringUtils.isNotEmpty(wgCode)) {
//            if ("zswg".equals(wgCode)) {
//                criteria.andWgTypeEqualTo("2");//查询所有专属网格
//            } else {
//                criteria.andWgParentIdEqualTo(wgCode);
//            }
//        }
//
//        //加上2.5级的
//        int count = gridRegionService.countByExample(example);
//        if (count <= 0) {
//            result.buildSuccess("success", appPageModel);
//            return;
//        }
//        example.setOrderByClause(" wg_code");

        int count = 5;
        List<GridRegion> roles = new ArrayList<>();
        List<String> type = new ArrayList<>();
        type.add("1");
        type.add("4");
        type.add("5");
        type.add("6");
        type.add("7");
        List<String> name = new ArrayList<>();
        name.add("楼宇");
        name.add("道路");
        name.add("街区");
        name.add("综合体");
        name.add("市场");

        for(int i=0;i<5;i++){
                GridRegion gridRegion = new GridRegion();
                gridRegion.setWgCode(wgCode);
                gridRegion.setStatus("2");
                gridRegion.setId(UUID.randomUUID().toString());
                gridRegion.setWgType(type.get(i));
                gridRegion.setLevel("2.5");
                gridRegion.setWgName(name.get(i));
                gridRegion.setIsValid("1");
                roles.add(gridRegion);
        }


//        List<GridRegion> roles = gridRegionService.selectByExampleWithBLOBsForStartPage(example, pageNum, pageSize);
//        if (null == roles || roles.isEmpty()) {
//            result.buildSuccess("success", appPageModel);
//            return;
//        }

        appPageModel.setCurPage(pageNum);
        appPageModel.setRecordCount(count);
        appPageModel.setPageCount((long) Math.ceil(1.0 * count / pageSize));
        List<GridRegionWithCompanyItem> itemList = BeanCopyUtil.bathToBean(roles, GridRegionWithCompanyItem.class);
        itemList.forEach( e -> {
            GridCompanyLandExample gridCompanyLandExample = new GridCompanyLandExample();
            GridCompanyLandExample.Criteria gridCompanyLandExampleCriteria = gridCompanyLandExample.createCriteria();
            gridCompanyLandExampleCriteria.andLandIdEqualTo(e.getId());
            gridCompanyLandExampleCriteria.andIsValidEqualTo("1");
            e.setCompanyCount(companyLandService.countByExample(gridCompanyLandExample));
        });
        appPageModel.setItemList(itemList);
        result.buildSuccess("success", appPageModel);
    }


}
