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

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

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.db.service.CommonService;
import com.scpyun.platform.jilinsscgsdp.bean.bo.GridPeopleBo;

import cn.hutool.core.thread.ThreadUtil;


@Api("删除功能")
@Service("deleteGridService")
public class DeleteGridServiceImpl {
    @Autowired
    CommonService commonService;
    @Autowired
    CreateGridServiceImpl createGridService;

    @Autowired
    SwitchServiceImpl switchService;
    private final String nameSpace = "com.scpyun.platform.standard.jilinsscgsdp.deleteGrid.";
    private final String nameSpace_user = "com.scpyun.platform.standard.jilinsscgsdp.userGrid.";
    
    @ApiOperation(value = "删除功能", desc = "删除功能")
    public String shardingDeleteGridInfo(Map<String, Object> map) {
    	return deleteGridInfo(map);
    }
    
    @ApiOperation(value = "删除人员功能", desc = "删除人员功能")
    public String shardingDeleteUserGrid(Map<String, Object> map) {
    	if(StringUtils.isEmpty(map.get("note"))){
        	map.put("note", "网格化人员管理删除");
        }
        map.put("delete_type",1);
    	gridUserDeleteExecutor(map);
    	return "success";
    }

    /**
     * 删除功能（楼以下直接删除，其余判断）
     *
     * @param map
     * @return
     */
    @ApiOperation(value = "删除功能", desc = "删除功能")
    public String deleteGridInfo(Map<String, Object> map) {
        Map<String, Object> userMap = (Map<String, Object>) map.get("_user");
        if (!"6".equals(userMap.get("company_grade"))) {
            throw new CustomException("账号等级不是社区，无法操作！");
        }
        // 直接删
        if(StringUtils.isEmpty(map.get("grade"))){
            throw new CustomException("缺少参数！grade");
        }
        if(StringUtils.isEmpty(map.get("id"))){
            throw new CustomException("缺少参数！id");
        }
        String grade = StringUtils.toString(map.get("grade"));
        switch (grade) {
            case "6":        // 网格
                String garden_id = StringUtils.toString(map.get("id"));
                Map<String, Object> tMap = new HashMap<String, Object>();
                tMap.put("garden_id", garden_id);
                List<Map<String, Object>> list = commonService.findList(nameSpace + "findBuildingList", tMap);
                if (list.size() > 0) {
                    throw new CustomException("该网格下级包含楼，无法直接删除，请仔细确认操作！");
                } else {
                    Map<String,Object> retMap1 = commonService.getObject(nameSpace + "getGardenByID",map);
//                    if(retMap1 != null){
//                        createGridService.QYGarden(garden_id);
//
//                    }
                    commonService.delete(nameSpace + "deleteGarden", tMap);// 删网格

                    // 删除场所
                    commonService.delete(nameSpace + "deleteMerchant",tMap);
                    // 删除社会组织
                    commonService.delete(nameSpace + "deleteSociety",tMap);
                    // 删除物件
                    commonService.delete(nameSpace + "deleteSubstance",tMap);
                }
                break;
            case "7":        // 楼
                String building_id = StringUtils.toString(map.get("id"));
                Map<String, Object> tMap1 = new HashMap<String, Object>();
                tMap1.put("building_id", building_id);
                Map<String,Object> retMap2 = commonService.getObject(nameSpace + "getBuildingByID",map);
//                if(retMap2 != null){
//                    createGridService.QYGarden(StringUtils.toString(retMap2.get("garden_id")));
//                    createGridService.QYBuilding(building_id);
//
//                }
                tMap1.put("delete_type",2);
                tMap1.put("note",map.get("note"));
                gridUserDeleteExecutor(tMap1);
                //commonService.insert(nameSpace_user + "insertNoteDelete",tMap1); //添加删除表
                //commonService.delete(nameSpace + "deletePeopleByBuilding", tMap1);// 删人
                commonService.delete(nameSpace + "deleteDoorplateByBuilding", tMap1);// 删户
                commonService.delete(nameSpace + "deleteFloorByBuilding", tMap1);// 删层
                commonService.delete(nameSpace + "deleteUnitByBuilding", tMap1);// 删单元
                commonService.delete(nameSpace + "deleteBuilding", tMap1);// 删楼
                break;
            case "8":        // 单元
                String unit_id = StringUtils.toString(map.get("id"));
                Map<String, Object> tMap2 = new HashMap<String, Object>();
                tMap2.put("unit_id", unit_id);
                Map<String,Object> retMap3 = commonService.getObject(nameSpace + "getUnitByID",map);
//                if(retMap3 != null){
//                    createGridService.QYGarden(StringUtils.toString(retMap3.get("garden_id")));
//                    createGridService.QYBuilding(StringUtils.toString(retMap3.get("building_id")));
//                }
                tMap2.put("delete_type",3);
                tMap2.put("note",map.get("note"));
                gridUserDeleteExecutor(tMap2);
                //commonService.insert(nameSpace_user + "insertNoteDelete",tMap2); //添加删除表
                //commonService.delete(nameSpace + "deletePeopleByUnit", tMap2);// 删人
                commonService.delete(nameSpace + "deleteDoorplateByUnit", tMap2);// 删户
                commonService.delete(nameSpace + "deleteFloorByUnit", tMap2);// 删层
                commonService.delete(nameSpace + "deleteUnit", tMap2);// 删单元
                break;
            case "9":        // 层
                String floor_id = StringUtils.toString(map.get("id"));
                Map<String, Object> tMap3 = new HashMap<String, Object>();
                tMap3.put("floor_id", floor_id);
                Map<String,Object> retMap4 = commonService.getObject(nameSpace + "getFloorByID",map);
//                if(retMap4 != null){
//                    createGridService.QYGarden(StringUtils.toString(retMap4.get("garden_id")));
//                    createGridService.QYBuilding(StringUtils.toString(retMap4.get("building_id")));
//                }
                tMap3.put("delete_type",4);
                tMap3.put("note",map.get("note"));
                gridUserDeleteExecutor(tMap3);
                //commonService.insert(nameSpace_user + "insertNoteDelete",tMap3); //添加删除表
                //commonService.delete(nameSpace + "deletePeopleByFloor", tMap3);// 删人
                commonService.delete(nameSpace + "deleteDoorplateByFloor", tMap3);// 删户
                commonService.delete(nameSpace + "deleteFloor", tMap3);// 删层
                updateFloorSort(retMap4);
                break;
            case "10":        // 户
                String doorplate_id = StringUtils.toString(map.get("id"));
                Map<String, Object> tMap4 = new HashMap<String, Object>();
                tMap4.put("doorplate_id", doorplate_id);
                Map<String,Object> retMap5 = commonService.getObject(nameSpace + "getDoorplateByID",map);
//                if(retMap5 != null){
//                    createGridService.QYGarden(StringUtils.toString(retMap5.get("garden_id")));
//                    createGridService.QYBuilding(StringUtils.toString(retMap5.get("building_id")));
//                }
                tMap4.put("delete_type",5);
                tMap4.put("note",map.get("note"));
                gridUserDeleteExecutor(tMap4);
                //commonService.insert(nameSpace_user + "insertNoteDelete",tMap4); //添加删除表
                //commonService.delete(nameSpace + "deletePeopleByDoorplate", tMap4);// 删人
                commonService.delete(nameSpace + "deleteDoorplate", tMap4);// 删户
                break;
        }
        return "success";
    }

	/**
	 * 处理居民分表数据删除操作
	 * @param map
	 */
	public void gridUserDeleteExecutor(Map<String, Object> map) {
		List<GridPeopleBo> userList = commonService.findList(nameSpace_user + "getDeleteUserShardingData",map);
		if(!userList.isEmpty()) {
			commonService.insertBatch(nameSpace_user + "insertNoteDeleteByShardingUser",userList); 
			commonService.deleteBatch(nameSpace_user + "deleteUserGrid", userList);
			commonService.deleteBatch(nameSpace_user + "deleteUserFocusGroupByCardNo",userList);
		}
	}
	
	
	/**
	 * sharding执行此方法报错，切换回主数据源
	 * @param retMap4
	 */
	private void updateFloorSort(Map<String, Object> retMap4) {
		//TODO
		//Future<String> future = ThreadUtil.execAsync(() -> {
		//DataSourceSwitcher.setMaster();
		//DataSourceSwitcher.setSharding("all");
		createGridService.updateFloorSort(retMap4);
			//return "更新成功";
		//});
	}

    @ApiOperation(value = "删除日志展示")
    public Page findOperateLogList(Page page){
        Page retPage = commonService.findPage(nameSpace + "findOperateLogList",page);
        Map<String,Object> numMap = commonService.getObject(nameSpace + "findOperateLogNumList" ,new HashMap<>());
        retPage.setTotalRecord(StringUtils.toInteger(numMap.get("num")));
        return retPage;
    }
    @ApiOperation(value = "查询人数", desc = "查询人数")
    public Map<String,Object> findGridUserNum(Map<String, Object> map) {
        if(StringUtils.isEmpty(map.get("grade"))){
            throw new CustomException("缺少参数！grade");
        }
        if(StringUtils.isEmpty(map.get("id"))){
            throw new CustomException("缺少参数！id");
        }
        String grade = StringUtils.toString(map.get("grade"));
        Map<String,Object> params = new HashMap<>();
        switch (grade) {
            case "5.5":// 小区
                String residential_id = StringUtils.toString(map.get("id"));
                params.put("residential_id",residential_id);
                break;
            case "6":        // 网格
                String garden_id = StringUtils.toString(map.get("id"));
                params.put("garden_id", garden_id);
                break;
            case "7":        // 楼
                String building_id = StringUtils.toString(map.get("id"));
                params.put("building_id", building_id);
                break;
            case "8":        // 单元
                String unit_id = StringUtils.toString(map.get("id"));
                params.put("unit_id", unit_id);
                break;
            case "9":        // 层
                String floor_id = StringUtils.toString(map.get("id"));
                params.put("floor_id", floor_id);
                break;
            case "10":        // 户
                String doorplate_id = StringUtils.toString(map.get("id"));
                params.put("doorplate_id", doorplate_id);
                break;
        }
        return commonService.getObject(nameSpace + "findGridUserNum", params);
    }
}
