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

import java.util.*;
import java.util.regex.Pattern;

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.StringUtils;
import com.scpyun.base.core.utils.UnifyLogger;
import com.scpyun.base.db.service.CommonService;
import com.scpyun.platform.jilinsscgsdp.constant.NotesConstant;
import com.scpyun.platform.jilinsscgsdp.constant.NumberConstant;

import cn.hutool.core.util.IdcardUtil;

@Api("人员信息")
@Service("peopleInfoService")
public class PeopleInfoServiceImpl {
    @Autowired
    CommonService commonService;
    private String nameSpace = "com.scpyun.platform.standard.jilinsscgsdp.peopleInfo.";
    private String nameSpaceGrid = "com.scpyun.platform.standard.jilinsscgsdp.patrol.";

    public static final String mobile_exp = "^((13[0-9])|(14[5,7,9])|(15[0-3,5-9])|(16[6,7])|(17[0-9])|(18[0-9])|(19[1,3,5,8,9]))\\d{8}$";
    public static final String tel_yqh_exp = "^[0][1-9]{2,3}-[0-9]{5,10}$";
    public static final String tel_wqh_exp = "^[1-9]{1}[0-9]{5,8}$";

    @ApiOperation(value = "人员信息")
    public Page findPeopleInfoList(Page page) {
        Map<String, Object> paramsMap = page.getParams();
        /*
        2025_01_22
        兼容：此接口PC和移动端都会调用，这里新增一个针对社区网格员的判断
        PS：社区管理员 ==> 看的是社区    |    社区网格员 ==> 看的是网格
        */
        paramsMap.putAll(disposeOfficeCodeLevel(paramsMap));
        Map<String,Object> gardenInfo = commonService.getObject(nameSpaceGrid + "selectGardenUserByCardNo", paramsMap);
        if (StringUtils.isNotEmpty(gardenInfo)) {
            paramsMap.put("garden", gardenInfo);
        }
        page.setParams(paramsMap);
        Page retPage = commonService.findPage(nameSpace + "findPeopleInfoList", page);
        Map<String, Object> numMap = commonService.getObject(nameSpace + "getPeopleInfoNum", page.getParams());
        int num = StringUtils.toInteger(numMap.get("num"));
        retPage.setTotalRecord(num);
        return retPage;
    }
    /*
    @ApiOperation(value = "人员信息")
    public Page findPeopleInfoList(Page<Map<String,Object>> page) {
    	DataSourceSwitcher.setMaster();
    	//DataSourceSwitcher.setShardingSphere("ShardingDataSource");
        Map<String, Object> paramsMap = page.getParams();
        paramsMap.putAll(disposeOfficeCodeLevel(paramsMap));
        page.setParams(paramsMap);
        //Page retPage = commonService.findPage(nameSpace + "findPeopleInfoList", page);
        //Map<String, Object> numMap = commonService.getObject(nameSpace + "getPeopleInfoNum", page.getParams());
        //int num = StringUtils.toInteger(numMap.get("num"));
        //retPage.setTotalRecord(num);
        page = commonService.findPage(nameSpace + "findPeopleInfoListForSharding", page);
        List<Map<String,Object>> resultsList = page.getResults();
        if(!resultsList.isEmpty()) {
            List<String> encryptCardnoList = resultsList.stream().map(map->MapUtil.getStr(map, "encrypt_cardno")).collect(Collectors.toList());
            List<Map<String,Object>> peopleLabelStaticList=commonService.findList(nameSpace+"getPeopleLabelStaticCount",new HashMap(){{put("cardnoList",encryptCardnoList);}});
            List<Map<String,Object>> peopleEventStaticList=commonService.findList(nameSpace+"getPeopleEventStaticCount",new HashMap(){{put("cardnoList",encryptCardnoList);}});

            Map<Object, Map<String, Object>> peopleLabelStaticMap = peopleLabelStaticList.stream()
            		.collect(Collectors.toMap(map->map.get("encrypt_cardno"), Function.identity(),(v1,v2)->v1));
            Map<Object, Map<String, Object>> peopleEventStaticMap = peopleEventStaticList.stream()
            		.collect(Collectors.toMap(map->map.get("encrypt_cardno"), Function.identity(),(v1,v2)->v1));
            for(Map<String,Object> map:resultsList) {
            	String cardNo=MapUtil.getStr(map, "encrypt_cardno");
            	if(peopleLabelStaticMap!=null && peopleLabelStaticMap.containsKey(cardNo)) {
            		map.putAll(peopleLabelStaticMap.get(cardNo));
            	}
            	if(peopleEventStaticMap!=null && peopleEventStaticMap.containsKey(cardNo)) {
            		map.putAll(peopleEventStaticMap.get(cardNo));
            	}else {
            		map.put("cardNumber",0);
            		map.put("statusNumber",0);
            	}
            }
        }
        return page;
    }
    */


    @ApiOperation(value = "新增人员信息(分表)")
    public String shardingCreatePeopleInfo(Map<String, Object> map) {
        return createPeopleInfo(map);
    }

    @ApiOperation(value = "新增人员信息")
    public String createPeopleInfo(Map<String, Object> map) {
        if (StringUtils.isEmpty(map.get("user_name"))) {
            throw new CustomException("缺少参数！姓名");
        }
        if (StringUtils.isEmpty(map.get("cardno"))) {
            throw new CustomException("缺少参数！身份证号");
        }
        if (StringUtils.isEmpty(map.get("tel"))) {
            throw new CustomException("缺少参数！手机号");
        }
        if (!IdcardUtil.isValidCard(StringUtils.toString(map.get("cardno")))) {
            throw new CustomException("身份证号不合法！");
        }
        String tel = StringUtils.toString(map.get("tel"));
        if (!Pattern.compile(mobile_exp).matcher(tel).matches() && !Pattern.compile(tel_wqh_exp).matcher(tel).matches() && !Pattern.compile(tel_yqh_exp).matcher(tel).matches()) {
            throw new CustomException("电话号码不合法！");
        }
        map.putAll(disposeOfficeCodeLevel(map));
        if (commonService.insert(nameSpace + "createPeopleInfo", map) != 1) {
            throw new CustomException("新增人员信息！");
        }
        if (!StringUtils.isEmpty(map.get("label_id"))) {
            List<String> labelList = Arrays.asList(StringUtils.toString(map.get("label_id")).split(","));
            map.put("dis_label_id", labelList);
            commonService.insert(nameSpace + "createPeopleLabel", map);
        }
        return "success";
    }

    @ApiOperation(value = "修改人员信息(分表)")
    public String shardingUpdatePeopleInfo(Map<String, Object> map) {
        return updatePeopleInfo(map);
    }

    @ApiOperation(value = "修改人员信息")
    public String updatePeopleInfo(Map<String, Object> map) {
        if (StringUtils.isEmpty(map.get("user_name"))) {
            throw new CustomException("缺少参数！姓名");
        }
        if (StringUtils.isEmpty(map.get("cardno"))) {
            throw new CustomException("缺少参数！身份证号");
        }
        if (StringUtils.isEmpty(map.get("tel"))) {
            throw new CustomException("缺少参数！手机号");
        }
        String tel = StringUtils.toString(map.get("tel"));
        if (!Pattern.compile(mobile_exp).matcher(tel).matches() && !Pattern.compile(tel_wqh_exp).matcher(tel).matches() && !Pattern.compile(tel_yqh_exp).matcher(tel).matches()) {
            throw new CustomException("电话号码不合法！");
        }
        if (commonService.insert(nameSpace + "updatePeopleInfo", map) != 1) {
            throw new CustomException("修改人员信息！");
        }
        commonService.delete(nameSpace + "deletePeopleLabel", map);
        if (!StringUtils.isEmpty(map.get("label_id"))) {
            List<String> labelList = Arrays.asList(StringUtils.toString(map.get("label_id")).split(","));
            map.put("dis_label_id", labelList);
            commonService.insert(nameSpace + "createPeopleLabel", map);
        }
        return "success";
    }

    @ApiOperation(value = "根据身份证号查询个人信息")
    public Map<String, Object> getPeopleInfoByCardno(Map<String, Object> map) {
        if (StringUtils.isEmpty(map.get("cardno"))) {
            throw new CustomException("缺少参数！");
        }
        if (!IdcardUtil.isValidCard(StringUtils.toString(map.get("cardno")))) {
            throw new CustomException("身份证号不合法！");
        }
        return commonService.getObject(nameSpace + "getPeopleInfoByCardno", map);
    }

    @ApiOperation(value = "查询区划")
    public Map<String, Object> disposeOfficeCodeLevel(Map<String, Object> map) {
        Map<String, Object> areaMap = commonService.getObject(nameSpace + "disposeOfficeCodeLevel", map);
        Map<String, Object> retAreaMap = new HashMap<>();
        if (areaMap != null) {
            String PARENT_IDS = StringUtils.toString(areaMap.get("PARENT_IDS"));
            String x[] = PARENT_IDS.split(",");
            if (x.length > 2) {
                retAreaMap.put("city_id", x[2]);
            }
            if (x.length > 3) {
                retAreaMap.put("area_id", x[3]);
            }
            if (x.length > 4) {
                retAreaMap.put("street_id", x[4]);
            }
            retAreaMap.put("current_id", areaMap.get("ID"));
        }
        return retAreaMap;
    }

    @ApiOperation(value = "查询标签")
    public List<Map<String, Object>> findLabelList(Map<String, Object> map) {
        return commonService.findList(nameSpace + "findLabelList", map);
    }

    @ApiOperation(value = "查询民族")
    public List<Map<String, Object>> findMZList(Map<String, Object> map) {
        return commonService.findList(nameSpace + "findMZList", map);
    }

    @ApiOperation(value = "走访日志列表")
    public List<Map<String, Object>> findPeopleZFLogList(Map<String, Object> map) {
        if (StringUtils.isEmpty(map.get("id"))) {
            throw new CustomException("缺少参数！");
        }
        map.putAll(disposeOfficeCodeLevel(map));
        Map<String, Object> card = commonService.getObject(nameSpace + "getCardNoById", map);
        map.put("card_no", card.get("cardno"));
        UnifyLogger.parent("findPeopleZFLogList" + map, UnifyLogger.Level.INFO);
        return commonService.findList(nameSpace + "findPeopleZFLogList", map);
    }

    @ApiOperation(value = "走访日志列表2")
    public List<Map<String, Object>> findPeopleZFLogList2(Map<String, Object> map) {
        if (StringUtils.isEmpty(map.get("card_no"))) {
            throw new CustomException("缺少参数！");
        }
        map.putAll(disposeOfficeCodeLevel(map));
        return commonService.findList(nameSpace + "findPeopleZFLogList2", map);
    }

    @ApiOperation(value = "创建走访日志")
    public String createPeopleZFLog(Map<String, Object> map) {
        if (StringUtils.isEmpty(map.get("cardno"))) {
            throw new CustomException("缺少参数！");
        }
        if (StringUtils.isEmpty(map.get("visit_date"))) {
            throw new CustomException("缺少参数！");
        }
        map.putAll(disposeOfficeCodeLevel(map));
        if (commonService.insert(nameSpace + "createPeopleZFLog", map) != 1) {
            throw new CustomException("走访日志添加失败！");
        }
        return "success";
    }

    @ApiOperation(value = "更新走访日志")
    public String updatePeopleZFLog(Map<String, Object> map) {
        if (StringUtils.isEmpty(map.get("id"))) {
            throw new CustomException("缺少参数！");
        }
        //        map.putAll(disposeOfficeCodeLevel(map));
        if (commonService.update(nameSpace + "updatePeopleZFLog", map) != 1) {
            throw new CustomException("走访日志添加失败！");
        }
        return "success";
    }

    @ApiOperation(value = "走访日志删除")
    public String deletePeopleZFLog(Map<String, Object> map) {
        if (StringUtils.isEmpty(map.get("id"))) {
            throw new CustomException("缺少参数！");
        }
        if (commonService.delete(nameSpace + "deletePeopleZFLog", map) != 1) {
            throw new CustomException("删除失败！");
        }
        return "success";
    }

    @ApiOperation(value = "特殊人员添加家属关系", desc = "特殊人员添加家属关系")
    public String saveUserFamily(Map<String, Object> map) {
        List<Map<String, Object>> userFamily = (List<Map<String, Object>>) map.get("familyList");
        List<String> cardList = new ArrayList<>();
        for (Map<String, Object> user : userFamily) {
            cardList.add(StringUtils.toString(user.get("cardno")));
        }
        Set<String> cardSet = new HashSet<>(cardList);
        if (cardList.size() != cardSet.size()) {
            throw new CustomException(NotesConstant.CARD_Dis_EXCEPTION);
        }
        Map<String, Object> userMap = (Map<String, Object>) map.get("_user");
        for (Map<String, Object> user : userFamily) {
            if (StringUtils.isNotEmpty(user.get("cardno"))) {
                if (!IdcardUtil.isValidCard(StringUtils.toStr(user.get("cardno")))) {
                    throw new CustomException(NotesConstant.CARD_EXCEPTION);
                }
            } else {
                throw new CustomException(NotesConstant.CARD_EXCEPTION);
            }
            user.put("_user", userMap);
            if (commonService.insert(nameSpace + "saveUserFamily", user) != NumberConstant.ONE_INT) {
                throw new CustomException(NotesConstant.SAVE_EVENT_LOG_EXCEPTION);
            }
        }
        return NotesConstant.SAVE_SUCCESS;
    }
}
