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


import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
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.StringUtils;
import com.scpyun.base.core.utils.UUIDUtil;
import com.scpyun.base.db.service.CommonService;
import com.scpyun.base.utils.UUID;
import com.scpyun.platform.jilinsscgsdp.bean.bo.UserInfoBo;
import com.scpyun.platform.jilinsscgsdp.bean.entity.JlGridGardenUser;
import com.scpyun.platform.jilinsscgsdp.enums.PatrolStatusEnum;
import com.scpyun.platform.jilinsscgsdp.enums.UserGradeEnum;
import com.scpyun.platform.jilinsscgsdp.utils.ValidatorUtil;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdcardUtil;

/**
 * @version V1.0.0
 * @Title: JlGridGardenUserImpl
 * @Package JlGridGardenUserImpl.java
 * @Description: 网格管理员接口
 * @author: guojiucoder
 * @date: 2024/9/2 14:45
 */
@Api("新层级查询")
@Service("jlGridGardenUser")
public class JlGridGardenUserImpl {
	
	@Autowired
	AppServiceImpl appService;

    @Autowired
    CommonService commonService;

    private String nameSpace = "com.scpyun.platform.standard.jilinsscgsdp.jlgridgarden.";
    
    private String nameSpaceGrid = "com.scpyun.platform.standard.jilinsscgsdp.gridLevel.";
    
	/**
	 * 中文数字
	 */
	private static final String[] CN_NUM = { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九" };

	/**
	 * 中文数字单位
	 */
	private static final String[] CN_UNIT = { "", "十", "百", "千", "万", "十", "百", "千", "亿", "十", "百", "千" };
	
	/**
	 * 特殊字符：负
	 */
	private static final String CN_NEGATIVE = "负";
	
	SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd ");


    @ApiOperation(value = "查询网格管理员", desc = "查询网格管理员")
    public JlGridGardenUser getJlGridGardenUser(JlGridGardenUser param) {
        if (StringUtils.isEmpty(param.getId())) {
            throw new CustomException("缺少参数！");
        }
        JlGridGardenUser retMap = commonService.getObject(nameSpace + "selectByPrimaryKey", param);
        if (retMap == null) {
            throw new CustomException("未查询到机构信息！");
        }
        return retMap;
    }


    @ApiOperation(value = "定人，查询网格管理员列表", desc = "定人，查询网格管理员列表")
    public Page<Map<String,Object>> findJlGridGardenUserList(Page param) {
    	Map<String, String> officeMapCache = appService.getOfficeMapCache();
        Page<Map<String,Object>> res = commonService.findPage(nameSpace + "findJlGridGardenUserList", param);
        for(Map<String, Object> map:res.getResults()) {
        	map.put("cityName", officeMapCache.get(map.get("cityId")));
        	map.put("areaName", officeMapCache.get(map.get("areaId")));
        	map.put("streetName", officeMapCache.get(map.get("streetId")));
        	map.put("communityName", officeMapCache.get(map.get("communityId")));
        }
        return res;
    }

    @ApiOperation(value = "定人，新增网格管理员", desc = "定人，新增网格管理员")
    public String addJlGridGardenUser(JlGridGardenUser param,Map map) {
    	UserInfoBo userInfo = UserInfoBo.getUserInfo(map);
        UserGradeEnum.checkUserPermission(userInfo.getCompany_grade(),UserGradeEnum.COMMUNITY);
        param.set_user(userInfo);
        ValidatorUtil.validate(param,Insert.class);
        if(!IdcardUtil.isValidCard(param.getCardno())) {
        	throw new CustomException("身份证格式不合法");
        }
        Map<String, Object> gardenMap = commonService.getObject(nameSpaceGrid + "getGridGardenById", param.getGardenId());
        if(gardenMap==null) {
        	throw new CustomException("网格信息异常！");
        }
        param.setCityId(MapUtil.getStr(gardenMap, "city_id"));
        param.setAreaId(MapUtil.getStr(gardenMap, "area_id"));
        param.setStreetId(MapUtil.getStr(gardenMap, "street_id"));
        param.setId(UUIDUtil.getUUID());
        if (commonService.insert(nameSpace + "insertSelective", param) != 1) {
            throw new CustomException("操作失败！");
        }
        return "success";
    }

    @ApiOperation(value = "定人，修改网格管理员", desc = "定人，修改网格管理员")
    public String updateJlGridGardenUser(JlGridGardenUser param,Map map) {
    	UserInfoBo userInfo = UserInfoBo.getUserInfo(map);
        UserGradeEnum.checkUserPermission(userInfo.getCompany_grade(),UserGradeEnum.COMMUNITY);
        param.set_user(userInfo);
        ValidatorUtil.validate(param,Update.class);
        if(!IdcardUtil.isValidCard(param.getCardno())) {
        	throw new CustomException("身份证格式不合法");
        }
        if (commonService.update(nameSpace + "updateByPrimaryKeySelective", param) != 1) {
            throw new CustomException("操作失败！");
        }
        return "success";
    }

    @ApiOperation(value = "定人，删除网格管理员", desc = "定人，删除网格管理员")
    public String deleteJlGridGardenUser(JlGridGardenUser param,Map map) {
    	UserInfoBo userInfo = UserInfoBo.getUserInfo(map);
        UserGradeEnum.checkUserPermission(userInfo.getCompany_grade(),UserGradeEnum.COMMUNITY);
        if(param.getId()==null) {
        	throw new CustomException("数据主键未传入");
        }
        commonService.delete(nameSpace + "deleteByPrimaryKey", param.getId());
        return "success";
    }
    
	/**
	 * findTimeList
	 * @param page page
	 * @return Page<Map<String,Object>>
	 */
	@ApiOperation(desc = "定时,查询列表",value = "定时查询列表")
	public Page<Map<String,Object>> findTimeList(Page page){
		return commonService.findPage(nameSpace + "findTimeList",page);
	}
	
	/**
	 * @param map
	 * @return
	 * @throws IOException
	 */
	@ApiOperation(desc = "定时,更新数据",value = "定时,更新数据")
	public String updateGardenTimeConfig(Map<String,Object> map) {
    	UserInfoBo userInfo = UserInfoBo.getUserInfo(map);
        UserGradeEnum.checkUserPermission(userInfo.getCompany_grade(),UserGradeEnum.COMMUNITY);
		if (StringUtils.isEmpty(map.get("id"))) {
			throw new CustomException("数据主键未传");
		}

		if (StringUtils.isEmpty(map.get("time"))) {
			throw new CustomException("巡查配置必填");
		}

		if (StringUtils.isEmpty(map.get("count"))) {
			throw new CustomException("巡查次数必填");
		}
		Map<String,Object> paramMap = new HashMap<>(16);
		paramMap.put("garden_id",MapUtil.getStr(map, "id"));
		paramMap.put("time",MapUtil.getStr(map, "time"));
		paramMap.put("grid_type","1");
		try {
			insertPatrolTaskTime(paramMap);
			commonService.update(nameSpace + "updateGardenTimeConfig",map);
		} catch (Exception e) {
			e.printStackTrace();
			throw new CustomException("网格定时配置异常");
		}
		
		return "success";
	}
	
	public String insertPatrolTaskTime(Map<String,Object> param) {
		int num = commonService.getObject(nameSpace + "getPatrolTimeNum", param);
		if(num>0) {
			throw new CustomException("有进行中的巡查任务，无法操作");
		}
		if(num==0) {
			commonService.delete(nameSpace + "deletePatrolTime", param);
		}
		String jsonStr = param.get("time").toString();
		List<Map<String, Object>> timeList = JSON.parseObject(jsonStr, List.class);
		int count = 0;
		for (Map<String, Object> map : timeList) {
			if(map != null && !map.isEmpty()){
				count++;
				Calendar cl = Calendar.getInstance();
				cl.add(Calendar.DATE,0);
				Calendar cl1 = Calendar.getInstance();
				cl1.add(Calendar.DATE,1);
				Date begin_date = new Date();
				Date end_date = new Date();
				if (map.get("time_begin").toString().compareTo(map.get("time_end").toString())>0){
					try {
						begin_date = sf.parse(sdf.format(cl.getTime())+map.get("time_begin").toString());
						end_date = sf.parse(sdf.format(cl1.getTime())+map.get("time_end").toString());
					} catch (ParseException e) {
						e.printStackTrace();
					}
				}else {
					try {
						begin_date = sf.parse(sdf.format(cl.getTime())+map.get("time_begin").toString());
						end_date = sf.parse(sdf.format(cl.getTime())+map.get("time_end").toString());
					} catch (ParseException e) {
						e.printStackTrace();
					}
				}
				long duration = (end_date.getTime()-begin_date.getTime())/60/1000;
				Map<String, Object> timeMap = new HashMap<String, Object>();
				timeMap.put("id", UUID.getUUID());
				timeMap.put("garden_id", param.get("garden_id"));
				timeMap.put("name", "第"+intchineseNum(count)+"次巡查");
				timeMap.put("statr_time", begin_date);
				timeMap.put("end_time", end_date);
				timeMap.put("duration", duration);
				timeMap.put("patrol_status", PatrolStatusEnum.beforeStart.getVal());
				commonService.insert(nameSpace + "insertPatrolTime", timeMap);
			}
		}
		return "success";
	}
	
	private static String intchineseNum(int intNum) {
		StringBuffer sb = new StringBuffer();
		boolean isNegative = false;
		if (intNum < 0) {
			isNegative = true;
			intNum *= -1;
		}
		int count = 0;
		while (intNum > 0) {
			sb.insert(0, CN_NUM[intNum % 10] + CN_UNIT[count]);
			intNum = intNum / 10;
			count++;
		}

		if (isNegative)
			sb.insert(0, CN_NEGATIVE);

		return sb.toString().replaceAll("零[千百十]", "零").replaceAll("零+万", "万").replaceAll("零+亿", "亿")
				.replaceAll("亿万", "亿零").replaceAll("零+", "零").replaceAll("零$", "");
	}
	
	@ApiOperation(desc = "定线,新增数据",value = "定时,新增数据")
	public String insertSubstance(Map<String,Object> map) {
    	UserInfoBo userInfo = UserInfoBo.getUserInfo(map);
        UserGradeEnum.checkUserPermission(userInfo.getCompany_grade(),UserGradeEnum.COMMUNITY);
		if (StringUtils.isEmpty(map.get("name"))) {
			throw new CustomException("巡查点名称必填");
		}
		if (StringUtils.isEmpty(map.get("remark"))) {
			throw new CustomException("巡查点备注必填");
		}
		if (StringUtils.isEmpty(map.get("wj_address"))) {
			throw new CustomException("巡查点地址必填");
		}
		if (StringUtils.isEmpty(map.get("csc_mapjson_ht"))) {
			throw new CustomException("巡查点坐标必填");
		}
		if (StringUtils.isEmpty(map.get("city_id"))) {
            // 新增
            Map<String, Object> resultMap = commonService.getObject(nameSpaceGrid+"getGridGardenById", map.get("garden_id"));
            if (resultMap == null) {
                throw new CustomException("查询上级失败！");
            }
            map.put("city_id", resultMap.get("city_id"));
        }
		if(commonService.insert(nameSpaceGrid + "insertSubstance", map)!=1) {
			throw new CustomException("定线新增巡查点异常");
		}
		return "success";
	}
	
	@ApiOperation(desc = "定线,更新数据",value = "定时,更新数据")
	public String updateSubstance(Map<String,Object> map) {
    	UserInfoBo userInfo = UserInfoBo.getUserInfo(map);
        UserGradeEnum.checkUserPermission(userInfo.getCompany_grade(),UserGradeEnum.COMMUNITY);
		if (StringUtils.isEmpty(map.get("id"))) {
			throw new CustomException("数据主键未传");
		}
		if (StringUtils.isEmpty(map.get("name"))) {
			throw new CustomException("巡查点名称必填");
		}
		if (StringUtils.isEmpty(map.get("remark"))) {
			throw new CustomException("巡查点备注必填");
		}
		if (StringUtils.isEmpty(map.get("wj_address"))) {
			throw new CustomException("巡查点地址必填");
		}
		if (StringUtils.isEmpty(map.get("csc_mapjson_ht"))) {
			throw new CustomException("巡查点坐标必填");
		}
		if(commonService.update(nameSpaceGrid + "updateSubstance", map)!=1) {
			throw new CustomException("定线更新巡查点异常");
		}
		return "success";
	}
	
	@ApiOperation(desc = "定线,删除数据",value = "定时,删除数据")
	public String deleteSubstance(Map<String,Object> map) {
    	UserInfoBo userInfo = UserInfoBo.getUserInfo(map);
        UserGradeEnum.checkUserPermission(userInfo.getCompany_grade(),UserGradeEnum.COMMUNITY);
		if (StringUtils.isEmpty(map.get("id"))) {
			throw new CustomException("数据主键未传");
		}
        commonService.update(nameSpaceGrid + "deleteSubstance", map);
        return "success";
	}

}
