package com.scpyun.platform.jilinsscgsdp.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.scpyun.base.bean.Page;
import com.scpyun.base.core.annotation.Api;
import com.scpyun.base.core.annotation.ApiOperation;
import com.scpyun.base.core.exception.CustomException;
import com.scpyun.base.core.utils.DataSourceSwitcher;
import com.scpyun.base.core.utils.StringUtils;
import com.scpyun.base.core.utils.UnifyLogger;
import com.scpyun.base.db.service.CommonService;

import cn.hutool.core.util.IdcardUtil;


@Api("查询网格层级关系")
@Service("gridLevelService")
public class GridLevelServiceImpl {
    @Autowired
    private CommonService commonService;
    // 3 区  4街道  5 社区  6 小区  7 楼   8 单元  9 层  10 户
    private String namespace = "com.scpyun.platform.standard.jilinsscgsdp.gridLevel.";
    private String namespaceUserGrid = "com.scpyun.platform.standard.jilinsscgsdp.userGrid.";
    private static String namespaceUser = "com.scpyun.platform.standard.jilinsscgsdp.user.";
    private String namespaceOffice = "com.scpyun.platform.standard.jilinsscgsdp.sysOfficeinfo.";

    @ApiOperation(value = "select版本搜索区街道社区", desc = "select版本搜索区街道社区")
    public Map<String, Object> findSelectOfficList(Map<String, Object> map) {
        DataSourceSwitcher.setSharding("sc");
        DataSourceSwitcher.setSlave();
        Map<String, Object> _userMap = (Map<String, Object>) map.get("_user");
        Map<String, Object> resultMap = new HashMap<String, Object>();
        switch (StringUtils.toString(_userMap.get("company_grade"))) {
            case "2":
                resultMap.put("areaList", this.findAreaList(map));
                resultMap.put("streetList", this.findStreetList(map));
                resultMap.put("communityList", this.findcommunityList(map));
                break;
            case "3":
                resultMap.put("areaList", this.findAreaList(map));
                map.put("parent_id", _userMap.get("company_id"));
                resultMap.put("streetList", this.findStreetList(map));
                Map<String, Object> rMap = new HashMap<String, Object>();
                rMap.put("parent_ids", _userMap.get("company_id"));
                resultMap.put("communityList", this.findcommunityList(rMap));
                resultMap.put("area_id", _userMap.get("company_id"));
                break;
            case "4":
                resultMap.put("areaList", this.findAreaList(map));
                resultMap.put("streetList", this.findStreetList(map));
                map.put("parent_id", _userMap.get("company_id"));
                resultMap.put("communityList", this.findcommunityList(map));
                resultMap.put("area_id", _userMap.get("parent_id"));
                resultMap.put("street_id", _userMap.get("company_id"));
                break;
            case "5":
                resultMap.put("area_id", _userMap.get("parent_ids").toString().split(",")[3]);
                resultMap.put("street_id", _userMap.get("parent_id"));
                resultMap.put("community_id", _userMap.get("company_id"));
                resultMap.put("areaList", this.findAreaList(map));
                resultMap.put("streetList", this.findStreetList(map));
                resultMap.put("communityList", this.findcommunityList(map));
                break;
            default:
        }
        return resultMap;
    }

    @ApiOperation(value = "select版本搜索区街道社区", desc = "select版本搜索区街道社区")
    public Map<String, Object> findNewSelectOfficList(Map<String, Object> map) {
        DataSourceSwitcher.setSharding("sc");
        DataSourceSwitcher.setSlave();
        Map<String, Object> resultMap = new HashMap<String, Object>();
        if (StringUtils.isEmpty(map.get("source_type"))) {
            resultMap.put("areaList", this.findAreaList(map));
            resultMap.put("streetList", this.findStreetList(map));
            resultMap.put("communityList", this.findcommunityList(map));
        } else {
            resultMap.put("communityList", this.findcommunityList(map));
        }
        return resultMap;
    }

    public List<Map<String, Object>> findAreaList(Map<String, Object> map) {
        map.put("grade", "3");
        return commonService.findList(namespace + "findOfficeInfoList", map);
    }

    public List<Map<String, Object>> findStreetList(Map<String, Object> map) {
        map.put("grade", "4");
        return commonService.findList(namespace + "findOfficeInfoList", map);
    }

    public List<Map<String, Object>> findcommunityList(Map<String, Object> map) {
        map.put("grade", "5");
        return commonService.findList(namespace + "findOfficeInfoList", map);
    }

    @ApiOperation(value = "查询所有网格部分数据", desc = "查询所有网格部分数据")
    public Map<String, Object> findGridAllList(Map<String, Object> map) {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        returnMap.put("gardenList", commonService.findList(namespace + "findAllGardenList", map));
        returnMap.put("buildingList", commonService.findList(namespace + "findAllBuildingList", map));
        return returnMap;
    }

    @ApiOperation(value = "查询上级", desc = "查询上级")
    public Map<String, Object> getSuperior(Map<String, Object> map) {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        if (StringUtils.toInteger(map.get("grade")) < 6) {
            DataSourceSwitcher.setSlave();
            DataSourceSwitcher.setSharding("sc");
            Map<String, Object> aMap = commonService.getObject(namespace + "getSuperior", map);
            if (aMap == null) {
                throw new CustomException("未查询到数据！");
            }
            String x = StringUtils.toString(aMap.get("parent_ids"));
            Map<String, Object> bMap = new HashMap<String, Object>();
            switch (StringUtils.toInteger(map.get("grade"))) {
                case 4:
                    bMap.put("id", x.split(",")[3]);
                    returnMap.put("select1", commonService.getObject(namespace + "getSuperior", bMap));
                    break;
                case 5:
                    bMap.put("id", x.split(",")[3]);
                    returnMap.put("select1", commonService.getObject(namespace + "getSuperior", bMap));
                    bMap.put("id", x.split(",")[4]);
                    returnMap.put("select2", commonService.getObject(namespace + "getSuperior", bMap));
                    break;
                default:
            }
        } else {
            switch (StringUtils.toInteger(map.get("grade"))) {
                case 6:
                    map.put("garden_id", map.get("id"));
                    returnMap = commonService.getObject(namespaceOffice + "getGridGardenById", map);
                    break;
                case 7:
                    map.put("building_id", map.get("id"));
                    returnMap = commonService.getObject(namespaceOffice + "findBuildingById", map);
                    break;
                default:
            }
            if (returnMap == null) {
                throw new CustomException("未查询到数据！");
            }
        }
        return returnMap;
    }

    @ApiOperation(value = "添加", desc = "添加")
    public Map<String, Object> addUser(Map<String, Object> map) {
        Map<String, Object> userMap = (Map<String, Object>) map.get("_user");
        if (StringUtils.isEmpty(map.get("cardno"))) {
            throw new CustomException("缺少参数，身份证号！");
        }
        String cardno = StringUtils.toString(map.get("cardno"));
        if (!IdcardUtil.isValidCard(cardno)) {
            throw new CustomException("身份证号码不合法！");
        }
        map.put("cardno", cardno.replace("x", "X"));
        Map<String, Object> resultMap = commonService.getObject(namespaceUser + "getuserinfobycardno", map);
        return resultMap;
    }

    @ApiOperation(value = "根据id查询各级信息", desc = "根据id查询各级信息")
    public Map<String, Object> getGridInfo(Map<String, Object> map) {
        int grade = StringUtils.toInteger(map.get("grade"));
        Map<String, Object> reMap = new HashMap<String, Object>();
        if (grade < 6) {
            DataSourceSwitcher.setSlave();
            DataSourceSwitcher.setSharding("sc");
            reMap = commonService.getObject(namespace + "getSuperior", map);
        } else if (grade == 6) {
            map.put("garden_id", map.get("id"));
            reMap = commonService.getObject(namespaceOffice + "getGridGardenById", map);
        } else if (grade == 7) {
            map.put("building_id", map.get("id"));
            reMap = commonService.getObject(namespaceOffice + "findBuildingById", map);
        }
        return reMap;
    }

    @ApiOperation(value = "新增地图场所", desc = "新增地图场所")
    public Map<String, Object> addPlace(Map<String, Object> map) {
//		GridSwitch(map);
        Map<String, Object> placeInfo = (Map<String, Object>) map.get("placeInfo");
        Map<String, Object> pickInfo = (Map<String, Object>) map.get("pickInfo");
        if (StringUtils.isEmpty(placeInfo.get("name"))) {
            throw new CustomException("缺少参数：name");
        }
        if (StringUtils.isEmpty(placeInfo.get("merchant_type"))) {
            throw new CustomException("缺少参数：merchant_type");
        }
        String merchant_type = StringUtils.toString(placeInfo.get("merchant_type"));
        if (!("Z0001".equals(merchant_type))) {
            if ("HT".equals(placeInfo.get("mapType"))) {
                if (StringUtils.isEmpty(placeInfo.get("csc_mapjson_ht"))) {
                    throw new CustomException("缺少参数：csc_mapjson_ht");
                }
            }
            if ("GD".equals(placeInfo.get("mapType"))) {
                if (StringUtils.isEmpty(placeInfo.get("csc_mapjson"))) {
                    throw new CustomException("缺少参数：csc_mapjson");
                }
            }
        }
        if (StringUtils.isEmpty(placeInfo.get("id"))) {
            // 新增
            Map<String, Object> resultMap = commonService.getObject(namespace + "getGridGardenById", pickInfo);
            if (resultMap == null) {
                throw new CustomException("查询上级失败！");
            }
            placeInfo.put("company_code", resultMap.get("company_code"));
            placeInfo.put("city_id", resultMap.get("city_id"));
            placeInfo.put("area_id", resultMap.get("area_id"));
            placeInfo.put("street_id", resultMap.get("street_id"));
            placeInfo.put("community_id", resultMap.get("community_id"));
            placeInfo.put("garden_id", resultMap.get("id"));
            if (commonService.insert(namespace + "insertPlace", placeInfo) != 1) {
                throw new CustomException("新增失败！");
            }
        } else {
            // 修改
            if (commonService.update(namespace + "updatePlace", placeInfo) != 1) {
                throw new CustomException("修改失败！");
            }
        }
        return placeInfo;
    }

    @Deprecated
    @ApiOperation(value = "新增地图社会组织", desc = "新增地图社会组织")
    public Map<String, Object> addSociety(Map<String, Object> map) {
//		GridSwitch(map);
        Map<String, Object> societyInfo = (Map<String, Object>) map.get("societyInfo");
        Map<String, Object> pickInfo = (Map<String, Object>) map.get("pickInfo");
        if (StringUtils.isEmpty(societyInfo.get("name"))) {
            throw new CustomException("缺少参数：name");
        }
        if (StringUtils.isEmpty(societyInfo.get("mapType"))) {
            throw new CustomException("缺少参数：mapType");
        }
        if ("HT".equals(societyInfo.get("mapType"))) {
            if (StringUtils.isEmpty(societyInfo.get("csc_mapjson_ht"))) {
                throw new CustomException("缺少参数：csc_mapjson_ht");
            }
        }
        if ("GD".equals(societyInfo.get("mapType"))) {
            if (StringUtils.isEmpty(societyInfo.get("csc_mapjson"))) {
                throw new CustomException("缺少参数：csc_mapjson");
            }
        }
        

        if (StringUtils.isEmpty(societyInfo.get("id"))) {
            // 新增
            Map<String, Object> resultMap = commonService.getObject(namespace + "getGridGardenById", pickInfo);
            if (resultMap == null) {
                throw new CustomException("查询上级失败！");
            }
            societyInfo.put("company_code", resultMap.get("company_code"));
            societyInfo.put("area_id", resultMap.get("area_id"));
            societyInfo.put("street_id", resultMap.get("street_id"));
            societyInfo.put("community_id", resultMap.get("community_id"));
            societyInfo.put("garden_id", resultMap.get("id"));
            if (commonService.insert(namespace + "insertSociety", societyInfo) != 1) {
                throw new CustomException("新增失败！");
            }
        } else {
            // 修改
            if (commonService.update(namespace + "updateSociety", societyInfo) != 1) {
                throw new CustomException("修改失败！");
            }
        }
        return societyInfo;
    }

    @ApiOperation(value = "查询管理员（网格，楼，单元）", desc = "查询管理员（网格，楼，单元）")
    public List<Map<String, Object>> findManagerList(Map<String, Object> map) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        UnifyLogger.parent("findManagerList + " + map.get("grade"), UnifyLogger.Level.INFO);
        switch (StringUtils.toString(map.get("grade"))) {
            case "5.5":
                UnifyLogger.parent("findManagerList + ", UnifyLogger.Level.INFO);
                list = commonService.findList(namespace + "findGradenManagerList", map);
                break;
            case "6":
                list = commonService.findList(namespace + "findBuildingManagerList", map);
                break;
            case "7":
                list = commonService.findList(namespace + "findUnitManagerList", map);
                break;
            default:
        }
        return list;
    }

    @ApiOperation(value = "添加管理员（网格，楼，单元）", desc = "添加管理员（网格，楼，单元）")
    public Map<String, Object> saveManager(Map<String, Object> map) {
        switch (StringUtils.toInteger(map.get("grade"))) {
            case 6:
                if (commonService.update(namespace + "updateGradenManager", map) != 1) {
                    throw new CustomException("处理失败！");
                }
                break;
            case 7:
                if (commonService.update(namespace + "updateBuildingManager", map) != 1) {
                    throw new CustomException("处理失败！");
                }
                break;
            case 8:
                if (commonService.update(namespace + "updateUnitManager", map) != 1) {
                    throw new CustomException("处理失败！");
                }
                break;
            default:
        }
        return map;
    }

    @ApiOperation(value = "绑定，解除绑定", desc = "绑定，解除绑定")
    public String updateBinding(Map<String, Object> map) {
        if (StringUtils.isEmpty(map.get("czType"))) {
            throw new CustomException("缺少操作类型！");
        }
        if (StringUtils.isEmpty(map.get("binding"))) {
            throw new CustomException("缺少参数：binding！");
        }
        Map<String, Object> resultMap = commonService.getObject(namespace + "getGardenByID", map);
        if (resultMap == null) {
            throw new CustomException("未查询到数据！");
        }
        String type = StringUtils.toString(map.get("czType"));
        if ("1".equals(type)) {
            if (StringUtils.isEmpty(resultMap.get("binding"))) {
                map.put("newbinding", StringUtils.toString(map.get("binding")) + ",");
            } else {
                if (StringUtils.toString(resultMap.get("binding")).contains(StringUtils.toString(map.get("binding")))) {
                    throw new CustomException("请勿重复绑定！");
                }
                map.put("newbinding", StringUtils.toString(resultMap.get("binding")) + StringUtils.toString(map.get("binding")) + ",");
            }
        } else if ("2".equals(type)) {
            // 解除绑定
            map.put("newbinding", StringUtils.toString(resultMap.get("binding")).replace(StringUtils.toString(map.get("binding")) + ",", ""));
        } else {
            throw new CustomException("操作类型错误！");
        }
        if (commonService.update(namespace + "updateBinding", map) != 1) {
            throw new CustomException("操作失败！");
        }
        return "success";
    }

    @ApiOperation(value = "查询绑定列表", desc = "查询绑定列表")
    public List<Map<String, Object>> findBindingList(Map<String, Object> map) {
        List<Map<String, Object>> returnList = new ArrayList<Map<String, Object>>();
        Map<String, Object> resultMap = commonService.getObject(namespace + "getGardenByID", map);
        if (resultMap != null) {
            if (!StringUtils.isEmpty(resultMap.get("binding"))) {
                String binding = StringUtils.toString(resultMap.get("binding"));
                String x[] = binding.split(",");
                if (x.length != 0) {
                    map.put("bindingList", x);
                    returnList = commonService.findList(namespace + "findbdxqList", map);
                }
            }
        } else {
            throw new CustomException("查询失败！");
        }
        return returnList;
    }

    @ApiOperation(desc = "添加小区", value = "添加小区")
    public String savexqInfo(Map<String, Object> map) {
        if (StringUtils.isEmpty(map.get("id"))) {
            List<Map<String, Object>> list = commonService.findList(namespace + "findxiaoquList", map);
            if (list.size() > 0) {
                throw new CustomException("当前添加小区名称重复！");
            }
        }
        if (commonService.insert(namespace + "savexqInfo", map) != 1) {
            throw new CustomException("添加失败！");
        }
        return "success";
    }

    @ApiOperation(value = "", desc = "")
    public String addDoorplateRemarks(Map<String, Object> map) {
        if (StringUtils.isEmpty(map.get("doorplate_id"))) {
            throw new CustomException("缺少参数！");
        }
        Map<String, Object> doorplateMap = commonService.getObject(namespace + "getDoorplateByID", map);
        doorplateMap.put("doorplate_id", doorplateMap.get("id"));
        if (doorplateMap == null) {
            throw new CustomException("户信息异常！");
        }
        Map<String, Object> peopleMap = commonService.getObject(namespace + "getPeopleNumByDoorplate", map);
        if (7 > StringUtils.toInteger(peopleMap.get("num"))) {
            throw new CustomException("该户人员数量为" + StringUtils.toInteger(peopleMap.get("num")) + ",无需添加备注！");
        }
        doorplateMap.put("remarks", map.get("remarks"));
        if (commonService.insert(namespace + "saveDoorplateRemarks", doorplateMap) != 1) {
            throw new CustomException("保存失败！");
        }
        return "success";
    }

    @ApiOperation(value = "", desc = "")
    public Page findMerchantPageList(Page page) {
        return commonService.findPage(namespace + "findMerchantPageSList", page);
    }
}
