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

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
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.core.utils.validator.IdcardUtil;
import com.scpyun.base.db.service.CommonService;
import com.scpyun.platform.jilinsscgsdp.bean.entity.JlHomicideCase;
import com.scpyun.platform.jilinsscgsdp.bean.entity.JlHomicideCaseNew;
import com.scpyun.platform.jilinsscgsdp.bean.entity.KeyPerson;
import com.scpyun.platform.jilinsscgsdp.bean.vo.RepeatTypeStatisticsVo;
import com.scpyun.platform.jilinsscgsdp.constant.NumberConstant;
import com.scpyun.platform.jilinsscgsdp.utils.CustomMergeStrategyWithTemplate;
import com.scpyun.platform.jilinsscgsdp.utils.DataScopeUtil;
import com.scpyun.platform.jilinsscgsdp.utils.DateUtil;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @description: 重点未成年人管理
 * @author: dushilong
 * @date: 2024-06-27 17:51
 */
@Api("重点未成年人管理")
@Service("keyPersonMinorService")
public class keyPersonMinorServiceImpl {
    @Autowired
    CommonService commonService;
    @Autowired
    PeopleInfoServiceImpl peopleInfoService;
    private final String nameSpace = "com.scpyun.platform.standard.jilinsscgsdp.keyPersonMinor.";
    private final String murderManagementNameSpace = "com.scpyun.platform.standard.jilinsscgsdp.murderManagement.";
    private static final Logger log = LoggerFactory.getLogger(keyPersonMinorServiceImpl.class);
    @ApiOperation(value = "查询登录人信息", desc = "")
    public Map<String,Object> getLoginUserAreaInfo(Page<Map<String,Object>> map) {
        Map<String, Object> user = (Map<String, Object>) map.getParams().get("_user");
        String company_id = user.get("company_id").toString();
        if (company_id.length() == 12) {
            return commonService.getObject(nameSpace + "getLoginUserAreaInfo", company_id);
        } else {
            Map<String, String> areaMap = DataScopeUtil.getPosition(user);
            String areaId = areaMap.get("area_id").toString();
            return commonService.getObject(nameSpace + "getLoginUserAreaInfo",areaId);
        }
    }


    @ApiOperation(value = "重点人员列表查询", desc = "")
    public Page<KeyPerson> findKeyPersonList(Page<KeyPerson> page) {
        Map<String, Object> user = (Map<String, Object>) page.getParams().get("_user");
        if (user != null) {
            Map<String, String> pos = DataScopeUtil.getPosition(user);

            Map<String, Object> setMap = new HashMap<>();
            setMap.put("scope_grade", pos.get("grade"));
            setMap.put("scope_area_id", pos.get("area_id"));
            page.getParams().put("_scope", setMap);
        }
        Page<KeyPerson> keyPersonList = commonService.findPage(nameSpace + "findKeyPersonList", page);
        for (KeyPerson keyPerson : keyPersonList.getResults()) {
            keyPerson.setKeyPersonHighlyConcernedRel(commonService.findList(nameSpace + "findKeyPersonHighlyConcernedRelListByKeyPersonId", keyPerson));
        }
        return keyPersonList;
    }

    @ApiOperation(value = "重点未成年人员数据导出", desc = "重点未成年人员数据导出")
    public void findKeyPersonListExport(KeyPerson keyPerson,HttpServletResponse response) throws IOException {
        List<KeyPerson> keyPersonList = commonService.findList(nameSpace + "findKeyPersonListExport", keyPerson);
        if(keyPersonList==null || keyPersonList.size()==0){
            throw new CustomException("暂无数据！");
        }
        String exportfileName="";
        String exportfilePath="";
        if(StringUtils.isEmpty(keyPerson.getSysType())){
            throw new CustomException("sysType不可为空！");
        }

        if(keyPerson.getSysType().equals("2")){
            exportfileName="刑满释放人员排查稳控登记表";
            exportfilePath="xingmanshifang.xlsx";
        }else if(keyPerson.getSysType().equals("3")){
            exportfileName="严重精神障碍患者排查稳控登记表";
            exportfilePath="yanzhongjingshenzhangai.xlsx";
        }else if(keyPerson.getSysType().equals("1")){
            exportfileName="“三失一偏”人员排查稳控登记表";
            exportfilePath="sanshiyipian.xlsx";
        }else if(keyPerson.getSysType().equals("4")){
            exportfileName="涉重点信访事项人员排查稳控登记表";
            exportfilePath="shezhongdianxinfang.xlsx";
        }else if(keyPerson.getSysType().equals("5")){
            exportfileName="涉重点涉法涉诉类矛盾人员排查稳控登记表";
            exportfilePath="shezhongdianshefashesu.xlsx";
        }else if(keyPerson.getSysType().equals("6")){
            exportfileName="重点未成年人排出稳控登记表";
            exportfilePath="shezhongdianweichengnian.xlsx";
        }

        // web环境下导出设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(exportfileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        String filePath = exportfilePath;
        Resource resource = new ClassPathResource(filePath);
        InputStream is = resource.getInputStream();

        EasyExcel.write(response.getOutputStream()).withTemplate(is).sheet().doFill(keyPersonList);
    }

    @ApiOperation(value = "删除重点人员信息", desc = "")
    public String deleteKeyPersonById(KeyPerson keyPerson) {
        if (commonService.delete(nameSpace + "deleteKeyPersonById", keyPerson) == 0) {
            throw new CustomException("操作失败!");
        }
//        commonService.delete(nameSpace + "deleteKeyPersonHighlyConcernedRelByPersonId", keyPerson);
        return "success";
    }

    @ApiOperation(value = "高度关注情形按类别统计，分别按类别统计", desc = "")
    public List<KeyPerson> findKeyPersonStatistics(KeyPerson keyPerson) {
        return commonService.findList(nameSpace + "findKeyPersonStatistics", keyPerson);
    }

    @ApiOperation(value = "新增重点未成年人员信息", desc = "新增重点未成年人员信息")
    public String insertKeyPersonById(KeyPerson keyPerson) {
        checkFied(keyPerson);
        if (StringUtils.isEmpty(keyPerson.getName())) {
            throw new CustomException("请填姓名！");
        }
        keyPerson.setId(UUIDUtil.getUUID());
        String communityId = keyPerson.getCommunityId();
        if(StrUtil.isNotBlank(communityId)){
            List<KeyPerson> list = commonService.findList(nameSpace + "checkCardNoRepeatList", keyPerson);
            if (list.size()>0){
                throw new CustomException("身份证重复无法新增！");
            }
        }
        if (commonService.insert(nameSpace + "insertKeyPersonById", keyPerson) == 0) {
            throw new CustomException("操作失败!");
        }
        keyPerson.getKeyPersonHighlyConcernedRel().forEach(keyPersonHighlyConcernedRel -> {
            keyPersonHighlyConcernedRel.setKeyPersonId(keyPerson.getId());
            keyPersonHighlyConcernedRel.setCardNo(keyPerson.getCardNo());
            keyPersonHighlyConcernedRel.setId(UUIDUtil.getUUID());
            keyPersonHighlyConcernedRel.set_user(keyPerson.get_user());
            if (commonService.insert(nameSpace + "insertKeyPersonHighlyConcernedRel", keyPersonHighlyConcernedRel) == 0) {
                throw new CustomException("操作失败!");
            }
        });
        return "success";
    }
    void checkFied(KeyPerson keyPerson){
        if (StringUtils.isEmpty(keyPerson.getCardNo())&& "".equals(keyPerson.getCardNo())) {
            throw new CustomException("身份证号不能为空");
        }
        if (!IdcardUtil.isValidCard(keyPerson.getCardNo())) {
            throw new CustomException("证件号不正确");
        }
        if (StringUtils.isEmpty(keyPerson.getSex())&& "".equals(keyPerson.getSex())) {
            throw new CustomException("性别不能为空");
        }
        if (StringUtils.isEmpty(keyPerson.getName())&& "".equals(keyPerson.getName())) {
            throw new CustomException("姓名不能为空");
        }
        if (StringUtils.isEmpty(keyPerson.getFolk())&& "".equals(keyPerson.getFolk())) {
            throw new CustomException("民族不能为空");
        }
        if (StringUtils.isEmpty(keyPerson.getPhone())&& "".equals(keyPerson.getPhone())) {
            throw new CustomException("本人联系方式不能为空");
        }
        if (StringUtils.isEmpty(keyPerson.getCityId())&& "".equals(keyPerson.getCityId())) {
            throw new CustomException("现住址市不能为空");
        }
        if (StringUtils.isEmpty(keyPerson.getAreaId())&& "".equals(keyPerson.getAreaId())) {
            throw new CustomException("现住址区不能为空");
        }
        if (StringUtils.isEmpty(keyPerson.getStreetId())&& "".equals(keyPerson.getStreetId())) {
            throw new CustomException("现住址街道不能为空");
        }
        if (StringUtils.isEmpty(keyPerson.getCommunityId())&& "".equals(keyPerson.getCommunityId())) {
            throw new CustomException("现住址社区不能为空");
        }
        if (StringUtils.isEmpty(keyPerson.getAddress())&& "".equals(keyPerson.getAddress())) {
            throw new CustomException("详细地址不能为空");
        }
        if (StringUtils.isEmpty(keyPerson.getRegisteredResidence())&& "".equals(keyPerson.getRegisteredResidence())) {
            throw new CustomException("户籍地址不能为空");
        }
//        if (StringUtils.isEmpty(keyPerson.getRelatedPersonAddress())&& "".equals(keyPerson.getRelatedPersonAddress())) {
//            throw new CustomException("监管人单位或地址不能为空");
//        }
//        if (StringUtils.isEmpty(keyPerson.getRelatedPersonName())&& "".equals(keyPerson.getRelatedPersonName())) {
//            throw new CustomException("监管人姓名不能为空");
//        }
//        if (StringUtils.isEmpty(keyPerson.getRelatedPersonPhone())&& "".equals(keyPerson.getRelatedPersonPhone())) {
//            throw new CustomException("监管人联系方式不能为空");
//        }
//        if (StringUtils.isEmpty(keyPerson.getRelatedPersonRelation())&& "".equals(keyPerson.getRelatedPersonRelation())) {
//            throw new CustomException("与本人关系不能为空");
//        }
//        if (StringUtils.isEmpty(keyPerson.getControlCompanySupervisor())&& "".equals(keyPerson.getControlCompanySupervisor())) {
//            throw new CustomException("列控单位不能为空");
//        }
//        if (StringUtils.isEmpty(keyPerson.getControlCompanySupervisorPerson())&& "".equals(keyPerson.getControlCompanySupervisorPerson())) {
//            throw new CustomException("责任人不能为空");
//        }
    }
    @ApiOperation(value = "修改重点人员信息", desc = "")
    public String updateKeyPersonById(KeyPerson keyPerson) {
        checkFied(keyPerson);
        if (commonService.update(nameSpace + "updateKeyPersonById", keyPerson) == 0) {
            throw new CustomException("操作失败!");
        }
        String communityId = keyPerson.getCommunityId();
        if(StrUtil.isNotBlank(communityId)){
            List<KeyPerson> list = commonService.findList(nameSpace + "checkCardNoRepeatList", keyPerson);
            if (list.size()>0){
                list.forEach(item ->{
                    if(!item.getId().equals(keyPerson.getId())){
                        throw new CustomException("社区和身份证重复无法编辑！");
                    }
                });
            }
        }
        commonService.delete(nameSpace + "deleteKeyPersonHighlyConcernedRelByPersonId", keyPerson);
        keyPerson.getKeyPersonHighlyConcernedRel().forEach(keyPersonHighlyConcernedRel -> {
            keyPersonHighlyConcernedRel.setKeyPersonId(keyPerson.getId());
            keyPersonHighlyConcernedRel.setCardNo(keyPerson.getCardNo());
            keyPersonHighlyConcernedRel.setId(UUIDUtil.getUUID());
            keyPersonHighlyConcernedRel.set_user(keyPerson.get_user());
            if (commonService.insert(nameSpace + "insertKeyPersonHighlyConcernedRel", keyPersonHighlyConcernedRel) == 0) {
                throw new CustomException("操作失败!");
            }
        });
        return "success";
    }

    @ApiOperation(value = "重点人员统计", desc = "")
    public List<KeyPerson> findKeyPersonStatisticsForType(KeyPerson keyPerson) {
        return commonService.findList(nameSpace + "findKeyPersonStatisticsForType", keyPerson);
    }

    @ApiOperation(value = "重点人员统计CountAll", desc = "")
    public KeyPerson keyPersonStatisticsForTypeAll(KeyPerson keyPerson) {
        return commonService.getObject(nameSpace + "keyPersonStatisticsForTypeAll", keyPerson);
    }

    @ApiOperation(value = "按照城市、区、街道、社区（分角色展示内容）统计重点人员数量", desc = "")
    public List<KeyPerson> keyPersonStatisticsForChunk(KeyPerson keyPerson) {
        if (keyPerson.get_user().getCompany_grade().equals("3")) {
            // city
            return commonService.findList(nameSpace + "keyPersonStatisticsForCity", keyPerson);
        } else if (keyPerson.get_user().getCompany_grade().equals("4")) {
            // area
            return commonService.findList(nameSpace + "keyPersonStatisticsForArea", keyPerson);
        } else if (keyPerson.get_user().getCompany_grade().equals("5")) {
            // street
            return commonService.findList(nameSpace + "keyPersonStatisticsForStreet", keyPerson);
        } else if (keyPerson.get_user().getCompany_grade().equals("6")) {
            // community
            return commonService.findList(nameSpace + "keyPersonStatisticsForCommunity", keyPerson);
        } else if (keyPerson.get_user().getCompany_grade().equals("2")) {
            // province
            return commonService.findList(nameSpace + "keyPersonStatisticsForProvince", keyPerson);
        } else {
            return null;
        }
    }

    @ApiOperation(value = "按照年龄统计重点人员数量", desc = "")
    public Map<String, Object> keyPersonStatisticsForAge(KeyPerson keyPerson) {
        List<KeyPerson> list = commonService.findList(nameSpace + "keyPersonStatisticsForAge", keyPerson);
        Map<String, Integer> map = new HashMap<>();
        map.put("0-18", 0);
        map.put("19-40", 0);
        map.put("41-60", 0);
        map.put("60+", 0);
        for (KeyPerson person : list) {
            String idcard = person.getCardNo();
            Integer age = DateUtil.calculateAgeByIdCard(idcard);
            if (age == null) {
                continue;
            }
            if (age <= 18) {
                map.put("0-18", map.get("0-18") + 1);
            } else if (age <= 40) {
                map.put("19-40", map.get("19-40") + 1);
            } else if (age <= 60) {
                map.put("41-60", map.get("41-60") + 1);
            } else {
                map.put("60+", map.get("60+") + 1);
            }
        }
        Map<String, Object> mapString = new HashMap<>();
        for (String key : map.keySet()) {
            mapString.put(key, map.get(key).toString());
        }
        return mapString;
    }

    @ApiOperation(value = "犯罪嫌疑人按照年龄段分组", desc = "")
    public Map<String, Object> homicideSuspectStatisticsForAge(JlHomicideCase jlHomicideCase) {
        List<JlHomicideCase> list = commonService.findList(nameSpace + "homicideSuspectStatisticsForAge", jlHomicideCase);
        Map<String, Integer> map = new HashMap<>();
        map.put("0-18", 0);
        map.put("19-40", 0);
        map.put("41-60", 0);
        map.put("60+", 0);
        for (JlHomicideCase jlHomicideCase1 : list) {
            // 犯罪嫌疑人身份证号
            String idcard = jlHomicideCase1.getSuspectCardno();
            Integer age = DateUtil.calculateAgeByIdCard(idcard);
            if (age == null) {
                continue;
            }
            if (age <= 18) {
                map.put("0-18", map.get("0-18") + 1);
            } else if (age <= 40) {
                map.put("19-40", map.get("19-40") + 1);
            } else if (age <= 60) {
                map.put("41-60", map.get("41-60") + 1);
            } else {
                map.put("60+", map.get("60+") + 1);
            }
        }
        Map<String, Object> mapString = new HashMap<>();
        for (String key : map.keySet()) {
            mapString.put(key, map.get(key).toString());
        }
        return mapString;
    }

    @ApiOperation(value = "按照城市、区、街道、社区（分角色展示内容）统计命案数量", desc = "")
    public List<JlHomicideCase> homicideSuspectStatisticsForChunk(JlHomicideCase jlHomicideCase) {
        if (jlHomicideCase.get_user().getCompany_grade().equals("3")) {
            // city
            return commonService.findList(nameSpace + "homicideSuspectStatisticsForCity", jlHomicideCase);
        } else if (jlHomicideCase.get_user().getCompany_grade().equals("4")) {
            // area
            return commonService.findList(nameSpace + "homicideSuspectStatisticsForArea", jlHomicideCase);
        } else if (jlHomicideCase.get_user().getCompany_grade().equals("5")) {
            // street
            return commonService.findList(nameSpace + "homicideSuspectStatisticsForStreet", jlHomicideCase);
        } else if (jlHomicideCase.get_user().getCompany_grade().equals("6")) {
            // community
            return commonService.findList(nameSpace + "homicideSuspectStatisticsForCommunity", jlHomicideCase);
        } else if (jlHomicideCase.get_user().getCompany_grade().equals("2")) {
            // province
            return commonService.findList(nameSpace + "homicideSuspectStatisticsForProvince", jlHomicideCase);
        } else {
            return null;
        }
    }

    @ApiOperation(value = "犯罪嫌疑人按照教育段分组", desc = "")
    public List<JlHomicideCase> homicideSuspectStatisticsForEduLevel(JlHomicideCase jlHomicideCase) {
        return commonService.findList(nameSpace + "homicideSuspectStatisticsEduLevel", jlHomicideCase);
    }

    @ApiOperation(value = "犯罪嫌疑人按照职业段分组", desc = "")
    public List<JlHomicideCase> homicideSuspectStatisticsForCareerSituation(JlHomicideCase jlHomicideCase) {
        return commonService.findList(nameSpace + "homicideSuspectStatisticsForCareerSituation", jlHomicideCase);
    }

    @ApiOperation(value = "犯罪嫌疑人案发原因分组", desc = "")
    public List<JlHomicideCase> homicideSuspectStatisticsForReasonIncident(JlHomicideCase jlHomicideCase) {
        jlHomicideCase.get_user().getCompany_id();
        return commonService.findList(nameSpace + "homicideSuspectStatisticsForReasonIncident", jlHomicideCase);
    }

    @ApiOperation(value = "按照矛盾等级统计重点人员数量", desc = "")
    public Map<String, Object> keyPersonStatisticsForRiskLevel(KeyPerson keyPerson) {
        List<KeyPerson> list = commonService.findList(nameSpace + "keyPersonStatisticsForRiskLevel", keyPerson);
        Map<String, Integer> map = new HashMap<>();
        map.put("1", 0);
        map.put("2", 0);
        map.put("3", 0);
        for (KeyPerson person : list) {
            if (person.getCount()!= null) {
                if ("1".equals(person.getRiskLevel())) {
                    map.put("1", Integer.parseInt(person.getCount()));
                } else if ("2".equals(person.getRiskLevel())) {
                    map.put("2", Integer.parseInt(person.getCount()));
                } else if("3".equals(person.getRiskLevel())) {
                    map.put("3", Integer.parseInt(person.getCount()));
                }
            }
        }
        map.put("1+2+3", (map.get("1") + map.get("2") + map.get("3")));
        Map<String, Object> mapString = new HashMap<>();
        for (String key : map.keySet()) {
            mapString.put(key, map.get(key).toString());
        }
        return mapString;
    }

    @ApiOperation(value = "命案数量", desc = "")
    public JlHomicideCase homicideCaseStatisticsCount(JlHomicideCase homicideCase) {
        return commonService.getObject(nameSpace + "homicideCaseStatisticsCount", homicideCase);
    }

    @ApiOperation(value = "命案统计-死亡人数", desc = "")
    public JlHomicideCase homicideCaseStatisticsCountDeadNumber(JlHomicideCase homicideCase) {
        return commonService.getObject(nameSpace + "homicideCaseStatisticsCountDeadNumber", homicideCase);
    }

    @ApiOperation(value = "命案统计（一杀一人数量）", desc = "")
    public JlHomicideCase homicideCaseStatisticsCountOneKillOnePerson(JlHomicideCase homicideCase) {
        return commonService.getObject(nameSpace + "homicideCaseStatisticsCountOneKillOnePerson", homicideCase);
    }

    @ApiOperation(value = "命案统计（一杀二人数量）", desc = "")
    public JlHomicideCase homicideCaseStatisticsCountOneKillTwoPerson(JlHomicideCase homicideCase) {
        return commonService.getObject(nameSpace + "homicideCaseStatisticsCountOneKillTwoPerson", homicideCase);
    }

    @ApiOperation(value = "命案统计（一杀三人及以上数量）", desc = "")
    public JlHomicideCase homicideCaseStatisticsCountOneKillMorePerson(JlHomicideCase homicideCase) {
        return commonService.getObject(nameSpace + "homicideCaseStatisticsCountOneKillMorePerson", homicideCase);
    }

    @ApiOperation(value = "添加和修改命案信息", desc = "添加和修改命案信息")
    public String createJlHomicideCase(Map<String, Object> map) {
        if (commonService.insert(nameSpace + "createJlHomicideCase", map) != NumberConstant.ONE_INT) {
            throw new CustomException("操作失败!");
        }
        return "success";
    }

    @ApiOperation(value = "删除命案信息", desc = "删除命案信息")
    public String deleteJlHomicideCaseAll(Map<String, Object> map) {
        if (StringUtils.isEmpty(map.get("id"))) {
            throw new CustomException("id不可为空！");
        }
        map.put("homicide_id", map.get("id"));
        commonService.delete(nameSpace + "deleteJlHomicideCaseALL", map);
        return "success";
    }

    @ApiOperation(value = "添加和修改命案受害者信息", desc = "添加和修改命案受害者信息")
    public String createJlHomicideVictime(Map<String, Object> map) {
        if (StringUtils.isEmpty(map.get("homicide_id"))) {
            throw new CustomException("命案id不可为空！");
        }
        if (commonService.insert(nameSpace + "createJlHomicideVictime", map) != NumberConstant.ONE_INT) {
            throw new CustomException("操作失败!");
        }
        return "success";
    }

    @ApiOperation(value = "删除命案受害者信息", desc = "删除命案受害者信息")
    public String deleteJlHomicideVictime(Map<String, Object> map) {
        if (StringUtils.isEmpty(map.get("id"))) {
            throw new CustomException("id不可为空！");
        }
        commonService.delete(nameSpace + "deleteJlHomicideVictimeFamilyALL", map);
        return "success";
    }

    @ApiOperation(value = "添加和修改命案受害者家属信息", desc = "添加和修改命案受害者家属信息")
    public String createJlHomicideFamily(Map<String, Object> map) {
        if (StringUtils.isEmpty(map.get("homicide_victime_id"))) {
            throw new CustomException("命案受害者id不可为空！");
        }
        if (commonService.insert(nameSpace + "createJlHomicideFamily", map) != NumberConstant.ONE_INT) {
            throw new CustomException("操作失败!");
        }
        return "success";
    }

    @ApiOperation(value = "删除命案受害者家属信息", desc = "删除命案受害者家属信息")
    public String deleteJlHomicideFamily(Map<String, Object> map) {
        if (StringUtils.isEmpty(map.get("id"))) {
            throw new CustomException("id不可为空！");
        }
        commonService.delete(nameSpace + "deleteJlHomicideFamily", map);
        return "success";
    }

    @ApiOperation(value = "添加和修改命案嫌疑人信息", desc = "添加和修改命案嫌疑人信息")
    public String createJlHomicideSuspect(Map<String, Object> map) {
        if (StringUtils.isEmpty(map.get("homicide_id"))) {
            throw new CustomException("命案id不可为空！");
        }
        Integer count = commonService.getObject(nameSpace + "getSuspect", map);
        if (count >= 1) {
            throw new CustomException("身份证号重复!");
        }
        if (commonService.insert(nameSpace + "createJlHomicideSuspect", map) != NumberConstant.ONE_INT) {
            throw new CustomException("操作失败!");
        }
        return "success";
    }

    @ApiOperation(value = "删除命案嫌疑人信息", desc = "删除命案嫌疑人信息")
    public String deleteJlHomicideSuspect(Map<String, Object> map) {
        if (StringUtils.isEmpty(map.get("id"))) {
            throw new CustomException("id不可为空！");
        }
        commonService.delete(nameSpace + "deleteJlHomicideSuspect", map);
        return "success";
    }

    @ApiOperation(value = "添加和修改命案证人信息", desc = "添加和修改命案证人信息")
    public String createJlHomicideWitness(Map<String, Object> map) {
        if (StringUtils.isEmpty(map.get("homicide_id"))) {
            throw new CustomException("命案id不可为空！");
        }
        if (commonService.insert(nameSpace + "createJlHomicideWitness", map) != NumberConstant.ONE_INT) {
            throw new CustomException("操作失败!");
        }
        return "success";
    }

    @ApiOperation(value = "删除命案证人信息", desc = "删除命案证人信息")
    public String deleteJlHomicideWitness(Map<String, Object> map) {
        if (StringUtils.isEmpty(map.get("id"))) {
            throw new CustomException("id不可为空！");
        }
        commonService.delete(nameSpace + "deleteJlHomicideWitness", map);
        return "success";
    }

    @ApiOperation(value = "查询命案信息分页列表", desc = "查询命案信息分页列表")
    public Page getJlHomicideCasePageList(Page page) {
//        Map paramsMap = page.getParams();
//        paramsMap.putAll(peopleInfoService.disposeOfficeCodeLevel(paramsMap));
//        page.setParams(paramsMap);
        return commonService.findPage(nameSpace + "getJlHomicideCasePageList", page);
    }

    @ApiOperation(value = "查询命案受害者列表", desc = "查询命案受害者列表")
    public List<Map<String, Object>> getJlHomicideVictimeList(Map<String, Object> map) {
        return commonService.findList(nameSpace + "getJlHomicideVictimeList", map);
    }

    @ApiOperation(value = "查询命案受害者家属列表", desc = "查询命案受害者家属列表")
    public List<Map<String, Object>> getJlHomicideFamilyList(Map<String, Object> map) {
        return commonService.findList(nameSpace + "getJlHomicideFamilyList", map);
    }

    @ApiOperation(value = "查询命案嫌疑人列表", desc = "查询命案嫌疑人列表")
    public List<Map<String, Object>> getJlHomicideSuspectList(Map<String, Object> map) {
        return commonService.findList(nameSpace + "getJlHomicideSuspectList", map);
    }

    @ApiOperation(value = "查询命案证人列表", desc = "查询命案证人列表")
    public List<Map<String, Object>> getJlHomicideWitnessList(Map<String, Object> map) {
        return commonService.findList(nameSpace + "getJlHomicideWitnessList", map);
    }

    @ApiOperation(value = "命案导出", desc = "命案导出")
    public List<JlHomicideCase> exportHomicideCaseData(Map<String, Object> map) throws IOException {
        List<JlHomicideCase> jlHomicideCaseList = commonService.findList(nameSpace + "selectHomicideCaseDataList", map);
        return jlHomicideCaseList;
        /*if (jlHomicideCaseList.isEmpty()) {
            throw new CustomException("暂无数据");
        }
//        String fileName = URLEncoder.encode("命案导出", "UTF-8").replaceAll("\\+", "%20");

        // attachment为以附件方式下载
        response.addHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        // xlsx 文件固定ContentType为application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        EasyExcel.write(response.getOutputStream(), JlHomicideCase.class)
                .useDefaultStyle(false)
                .sheet("sheet1")
                .doWrite(jlHomicideCaseList);*/

    }

    @ApiOperation(value = "命案导出-新", desc = "命案导出-新")
    public void exportHomicideCaseDataNew(Map<String, Object> map, HttpServletResponse response) throws IOException {
        List<JlHomicideCaseNew> jlHomicideCaseList = commonService.findList(nameSpace + "selectHomicideCaseDataListNew", map);
        // web环境下导出设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("命案导出", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        String pdfFilePath = "fuzaTemplateWithMerge.xlsx";
        Resource resource = (Resource) new ClassPathResource(pdfFilePath);
        InputStream is = resource.getInputStream();

        List<JlHomicideCaseNew> list = jlHomicideCaseList;
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(is).excelType(ExcelTypeEnum.XLSX).build();
        WriteSheet writeSheet = EasyExcel.writerSheet("Sheet1").head(JlHomicideCaseNew.class)
                .registerWriteHandler(new CustomMergeStrategyWithTemplate(list.stream().map(JlHomicideCaseNew::getId).collect(Collectors.toList()), 0))//合并第1列
                .registerWriteHandler(new CustomMergeStrategyWithTemplate(list.stream().map(JlHomicideCaseNew::getId).collect(Collectors.toList()), 1))
                .registerWriteHandler(new CustomMergeStrategyWithTemplate(list.stream().map(JlHomicideCaseNew::getId).collect(Collectors.toList()), 2))
                .registerWriteHandler(new CustomMergeStrategyWithTemplate(list.stream().map(JlHomicideCaseNew::getId).collect(Collectors.toList()), 3))
                .registerWriteHandler(new CustomMergeStrategyWithTemplate(list.stream().map(JlHomicideCaseNew::getId).collect(Collectors.toList()), 4))
                .registerWriteHandler(new CustomMergeStrategyWithTemplate(list.stream().map(JlHomicideCaseNew::getId).collect(Collectors.toList()), 11))
                .build();
        //上面的方式是只合并了第0列，如果要合并多个列，创建多个registerWriteHandler就可以
        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
        Map<String, Object> _user = (Map<String, Object>) map.get("_user");
        map.put("companyName", _user.get("company_name"));
        excelWriter.fill(jlHomicideCaseList,fillConfig, writeSheet);
        excelWriter.fill(map,fillConfig, writeSheet);
        excelWriter.finish();
    }

    @ApiOperation(value = "重复类型统计列表", desc = "重复类型统计列表")
    public Page<RepeatTypeStatisticsVo> getRepeatTypeStatistics(Page<RepeatTypeStatisticsVo> page) {
        return commonService.findPage(nameSpace + "getRepeatTypeStatistics",page);
    }

    /**
     * 通过身份证号查询重复类型统计详情
     */
    @ApiOperation(value = "重复类型统计详情", desc = "重复类型统计详情")
    public Map<String, Object> getRepeatTypeStatisticsDetail(Map<String, Object> map) {
        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> list = commonService.findList(nameSpace + "getRepeatTypeStatisticsDetail", map);

        if (CollectionUtils.isNotEmpty(list)) {
            // 对 list  根据 sysType 去重后的数量
            List<Map<String, Object>> sysType = list.stream().collect(Collectors.collectingAndThen(
                    Collectors.toMap(v -> v.get("sysType"), v -> v, (existing, replacement) -> existing),
                    s -> new ArrayList<>(s.values())
            ));
            result.put("count", sysType.size());

            list.forEach(item -> {
                KeyPerson keyPerson = new KeyPerson();
                keyPerson.setId((String) item.get("id"));
                item.put("keyPersonHighlyConcernedRel", commonService.findList(nameSpace + "findKeyPersonHighlyConcernedRelListByKeyPersonId", keyPerson));
            });
        } else {
            result.put("count", 0);
        }
        result.put("list", list);
        return result;
    }

    @ApiOperation(value = "人员统计(正常待办，临期待办)", desc = "人员统计(正常待办，临期待办)")
    public KeyPerson doStatusAllCount(KeyPerson keyPerson) {
        if (keyPerson.getSysType().equals("6")) {
            return commonService.getObject(nameSpace + "doStatusAllCount", keyPerson);
        } else {
            return commonService.getObject(murderManagementNameSpace + "doStatusAllCount", keyPerson);
        }
    }
}
