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

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.scpyun.base.bean.Page;
import com.scpyun.base.bean.User;
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.KeyPerson;
import com.scpyun.platform.jilinsscgsdp.utils.DataScopeUtil;
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.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 重点人员统一管理（支持sysType=2,3,6）
 * @author: system
 * @date: 2024-12-19
 */
@Api("重点人员统一管理")
@Service("keyPersonUnifiedService")
public class keyPersonUnifiedServiceImpl {
    @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(keyPersonUnifiedServiceImpl.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 = "支持sysType=2,3,6")
    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);
        }
        // 根据sysType选择不同的命名空间
        String sysType = (String) page.getParams().get("sysType");
        String queryNameSpace = nameSpace;
        String highlyConcernedRelNameSpace = nameSpace;
        if (sysType != null && (sysType.equals("2") || sysType.equals("3"))) {
            // sysType=2,3 使用 murderManagement 命名空间
            queryNameSpace = murderManagementNameSpace;
            highlyConcernedRelNameSpace = murderManagementNameSpace;
            String changchunMark = DataScopeUtil.isChanChun(user) ? "_changchun" : "";
            Page<KeyPerson> keyPersonList = commonService.findPage(queryNameSpace + "findKeyPersonList" + changchunMark, page);
            for (KeyPerson keyPerson : keyPersonList.getResults()) {
                keyPerson.setKeyPersonHighlyConcernedRel(commonService.findList(highlyConcernedRelNameSpace + "findKeyPersonHighlyConcernedRelListByKeyPersonId", keyPerson));
            }
            return keyPersonList;
        } else {
            // sysType=6 使用 keyPersonMinor 命名空间
            Page<KeyPerson> keyPersonList = commonService.findPage(queryNameSpace + "findKeyPersonList", page);
            for (KeyPerson keyPerson : keyPersonList.getResults()) {
                keyPerson.setKeyPersonHighlyConcernedRel(commonService.findList(highlyConcernedRelNameSpace + "findKeyPersonHighlyConcernedRelListByKeyPersonId", keyPerson));
            }
            return keyPersonList;
        }
    }

    @ApiOperation(value = "重点人员数据导出", desc = "重点人员数据导出（支持sysType=2,3,6）")
    public void findKeyPersonListExport(KeyPerson keyPerson,HttpServletResponse response) throws IOException {
        if(StringUtils.isEmpty(keyPerson.getSysType())){
            throw new CustomException("sysType不可为空！");
        }
        
        // 根据sysType选择不同的命名空间
        String sysType = keyPerson.getSysType();
        String queryNameSpace = nameSpace;
        List<KeyPerson> keyPersonList;
        
        if (sysType.equals("2") || sysType.equals("3")) {
            // sysType=2,3 使用 murderManagement 命名空间
            queryNameSpace = murderManagementNameSpace;
            String changchunMark = DataScopeUtil.isChanChun(keyPerson.get_user()) ? "_changchun" : "";
            User _user = keyPerson.get_user();
            if (_user != null && changchunMark.length()>0) {
                Map<String, String> pos = DataScopeUtil.getPosition(_user);
                keyPerson.setScopeGrade(pos.get("grade"));
                keyPerson.setScopeAreaId(pos.get("area_id"));
            }
            keyPersonList = commonService.findList(queryNameSpace + "findKeyPersonListExport" + changchunMark, keyPerson);
        } else {
            // sysType=6 使用 keyPersonMinor 命名空间
            keyPersonList = commonService.findList(queryNameSpace + "findKeyPersonListExport", keyPerson);
        }
        
        if(keyPersonList==null || keyPersonList.size()==0){
            throw new CustomException("暂无数据！");
        }
        
        String exportfileName="";
        String exportfilePath="";
        if(sysType.equals("2")){
            exportfileName="刑满释放人员排查稳控登记表";
            exportfilePath="xingmanshifang.xlsx";
        }else if(sysType.equals("3")){
            exportfileName="严重精神障碍患者排查稳控登记表";
            exportfilePath="yanzhongjingshenzhangai.xlsx";
        }else if(sysType.equals("1")){
            exportfileName="三失一偏人员排查稳控登记表";
            exportfilePath="sanshiyipian.xlsx";
        }else if(sysType.equals("4")){
            exportfileName="涉重点信访事项人员排查稳控登记表";
            exportfilePath="shezhongdianxinfang.xlsx";
        }else if(sysType.equals("5")){
            exportfileName="涉重点涉法涉诉类矛盾人员排查稳控登记表";
            exportfilePath="shezhongdianshefashesu.xlsx";
        }else if(sysType.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 = "支持sysType=2,3,6")
    public String deleteKeyPersonById(KeyPerson keyPerson) {
        // 根据sysType选择不同的命名空间
        String sysType = keyPerson.getSysType();
        String deleteNameSpace = nameSpace;
        if (sysType != null && (sysType.equals("2") || sysType.equals("3"))) {
            deleteNameSpace = murderManagementNameSpace;
            if (commonService.delete(deleteNameSpace + "deleteKeyPersonById", keyPerson) == 0) {
                throw new CustomException("操作失败!");
            }
            commonService.delete(deleteNameSpace + "deleteKeyPersonHighlyConcernedRelByPersonId", keyPerson);
        } else {
            if (commonService.delete(deleteNameSpace + "deleteKeyPersonById", keyPerson) == 0) {
                throw new CustomException("操作失败!");
            }
        }
        return "success";
    }

    @ApiOperation(value = "新增重点人员信息", desc = "新增重点人员信息（支持sysType=2,3,6）")
    public String insertKeyPersonById(KeyPerson keyPerson) {
        checkFied(keyPerson);
        if (StringUtils.isEmpty(keyPerson.getName())) {
            throw new CustomException("请填姓名！");
        }
        keyPerson.setId(UUIDUtil.getUUID());
        
        // 根据sysType选择不同的命名空间
        String sysType = keyPerson.getSysType();
        String insertNameSpace = nameSpace;
        String highlyConcernedRelNameSpace = nameSpace;
        
        if (sysType != null && (sysType.equals("2") || sysType.equals("3"))) {
            insertNameSpace = murderManagementNameSpace;
            highlyConcernedRelNameSpace = murderManagementNameSpace;
            // sysType=2,3 需要设置region默认值
            String communityId = keyPerson.getCommunityId();
            if(StrUtil.isNotBlank(communityId)){
                keyPerson.setRegion("1");//地区：1 省内(默认)，2 省外，3 国外
                List<KeyPerson> list = commonService.findList(insertNameSpace + "checkCardNoRepeatList", keyPerson);
                if (list.size()>0){
                    throw new CustomException("社区和身份证重复无法新增！");
                }
            }
        } else {
            // sysType=6
            String communityId = keyPerson.getCommunityId();
            if(StrUtil.isNotBlank(communityId)){
                List<KeyPerson> list = commonService.findList(insertNameSpace + "checkCardNoRepeatList", keyPerson);
                if (list.size()>0){
                    throw new CustomException("身份证重复无法新增！");
                }
            }
        }
        
        if (commonService.insert(insertNameSpace + "insertKeyPersonById", keyPerson) == 0) {
            throw new CustomException("操作失败!");
        }
        
        if (keyPerson.getKeyPersonHighlyConcernedRel() != null && keyPerson.getKeyPersonHighlyConcernedRel().size() > 0) {
            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("户籍地址不能为空");
        }
    }

    @ApiOperation(value = "修改重点人员信息", desc = "支持sysType=2,3,6")
    public String updateKeyPersonById(KeyPerson keyPerson) {
        checkFied(keyPerson);
        
        // 根据sysType选择不同的命名空间
        String sysType = keyPerson.getSysType();
        String updateNameSpace = nameSpace;
        String highlyConcernedRelNameSpace = nameSpace;
        
        if (sysType != null && (sysType.equals("2") || sysType.equals("3"))) {
            updateNameSpace = murderManagementNameSpace;
            highlyConcernedRelNameSpace = murderManagementNameSpace;
        }
        
        if (commonService.update(updateNameSpace + "updateKeyPersonById", keyPerson) == 0) {
            throw new CustomException("操作失败!");
        }
        
        String communityId = keyPerson.getCommunityId();
        if(StrUtil.isNotBlank(communityId)){
            List<KeyPerson> list = commonService.findList(updateNameSpace + "checkCardNoRepeatList", keyPerson);
            if (list.size()>0){
                list.forEach(item ->{
                    if(!item.getId().equals(keyPerson.getId())){
                        throw new CustomException("社区和身份证重复无法编辑！");
                    }
                });
            }
        }
        
        commonService.delete(highlyConcernedRelNameSpace + "deleteKeyPersonHighlyConcernedRelByPersonId", keyPerson);
        if (keyPerson.getKeyPersonHighlyConcernedRel() != null && keyPerson.getKeyPersonHighlyConcernedRel().size() > 0) {
            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 KeyPerson doStatusAllCount(KeyPerson keyPerson) {
        if (keyPerson.getSysType().equals("6")) {
            return commonService.getObject(nameSpace + "doStatusAllCount", keyPerson);
        } else {
            return commonService.getObject(murderManagementNameSpace + "doStatusAllCount", keyPerson);
        }
    }
}

