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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
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.UserInfoBo;
import com.scpyun.platform.jilinsscgsdp.bean.vo.JlGridUserVo;
import com.scpyun.platform.jilinsscgsdp.check.DutyCheckUtils;
import com.scpyun.platform.jilinsscgsdp.check.GridUserCheckUtils;
import com.scpyun.platform.jilinsscgsdp.enums.UserGradeEnum;
import com.scpyun.platform.jilinsscgsdp.utils.ValidatorUtil;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Update;
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.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author liu
 * @Date 2024/7/31 9:42
 * @PackageName:com.scpyun.platform.jilinsscgsdp.service.impl
 * @ClassName: GridUserServiceImpl
 * @Description: TODO
 * @Version 1.0
 */
@Api("网格人员")
@Service("gridUserService")
public class GridUserServiceImpl {
    @Autowired
    CommonService commonService;
    
    private String nameSpace = "com.scpyun.platform.standard.jilinsscgsdp.user.";
    private String nameSpaceSys = "com.scpyun.platform.standard.jilinsscgsdp.sys.";
    private String nameSpaceDuty = "com.scpyun.platform.standard.jilinsscgsdp.duty.";
    private String nameSpaceFocusGroup = "com.scpyun.platform.standard.jilinsscgsdp.gridfocusgroup.";
    private static final Logger log = LoggerFactory.getLogger(GridUserServiceImpl.class);


    @ApiOperation(value = "下载模版", desc = "下载模版" ,nologin = true)
    public void exportDownloadTemplate(Map<String, Object> map, HttpServletResponse response) throws IOException {
//            // 读取模板文件
//            InputStream templateStream = getClass().getClassLoader()
//                    .getResourceAsStream("importTem.xlsx");
//                if (templateStream == null) {
//                    throw new FileNotFoundException("模板文件不存在: templates/importTem.xlsx");
//                }


//        try {
//            String fileName = "importTem.xlsx";
//            // 设置响应头（.xlsx 专用媒体类型）
//            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//
//            // 编码文件名（兼容各浏览器）
//            String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name())
//                    .replace("+", "%20");
//            response.setHeader("Content-Disposition",
//                    "attachment; filename*=UTF-8''" + encodedFileName);
//
//            // 读取模板文件
//            try (InputStream templateStream = getClass().getClassLoader()
//                    .getResourceAsStream("templates/importTem.xlsx");
//                 OutputStream outputStream = response.getOutputStream()) {
//
//                if (templateStream == null) {
//                    throw new FileNotFoundException("模板文件不存在: templates/importTem.xlsx");
//                }
//
//                // 直接拷贝流到响应输出流
//                byte[] buffer = new byte[1024];
//                int bytesRead;
//                while ((bytesRead = templateStream.read(buffer)) != -1) {
//                    outputStream.write(buffer, 0, bytesRead);
//                }
//                outputStream.flush(); // 确保数据全部写出
//            }
//        } catch (FileNotFoundException e) {
//            UnifyLogger.parent(UnifyLogger.getTrace(e),UnifyLogger.Level.INFO);
//            response.reset();
//            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
//            response.setContentType("text/plain;charset=UTF-8");
//            response.getWriter().write("模板文件不存在");
//        } catch (Exception e) {
//            UnifyLogger.parent(UnifyLogger.getTrace(e),UnifyLogger.Level.INFO);
//            // 重置响应（关键！清除之前的 Content-Type 设置）
//            response.reset();
//            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
//            response.setContentType("text/plain;charset=UTF-8");
//            response.getWriter().write("下载失败，请稍后重试");
//        }
//        // web环境下导出设置响应头
        response.setContentType("application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        try {
            String fileName = URLEncoder.encode("导入模板", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            response.setHeader("filename", fileName + ".xlsx");
            response.setHeader("Access-Control-Expose-Headers", "filename,Content-Disposition");

            String pdfFilePath = "importTem.xlsx";
            Resource resource = new ClassPathResource(pdfFilePath);
            InputStream is = resource.getInputStream();
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(is).excelType(ExcelTypeEnum.XLSX).build();
            excelWriter.finish();
        } catch (Exception e) {
            log.error("下载模版异常", e);
        }
    }

    @ApiOperation(value = "添加网格居民", desc = "添加网格居民")
    public String insertGridUser(Map<String, Object> map) {
    	JlGridUserVo vo=new JlGridUserVo();
    	BeanUtil.fillBeanWithMap(map, vo, false, true);
    	ValidatorUtil.validate(vo, Insert.class);
    	GridUserCheckUtils.gridUserCheck(map);
    	DataSourceSwitcher.setMaster();
    	//DataSourceSwitcher.setShardingSphere("ShardingDataSource");
        Map<String, Object> user = commonService.getObject(nameSpace + "getGridUserByCardNo", map);
        if (user != null) {
        	user.putAll(commonService.getObject(nameSpace+"queryAreaName", user.get("community_id")));
        	return "添加失败！人员：" + map.get("user_name") +
                    " 已被" + user.get("city") + "，" + user.get("area") + "，" + user.get("street") + "，" + user.get("community") + "录入";
        }
        map.putAll(this.getCityId(map));
        log.info("人员添加       人员信息=" + map);
        if (commonService.insert(nameSpace + "insertUserGrid", map) != 1) {
        	return "添加人员失败";
        }
        	
        if (!StringUtils.isEmpty(map.get("doorplate_id"))) {
            if (commonService.insert(nameSpace + "updateGridDoorplate", map) != 1) {
                throw new CustomException("修改户失败");
            }
        }
        return "success";
    }

    @ApiOperation(value = "网格居民修改", desc = "网格居民修改")
    public String updateGridUser(Map<String, Object> map) {
    	JlGridUserVo vo=new JlGridUserVo();
    	BeanUtil.fillBeanWithMap(map, vo, false, true);
    	ValidatorUtil.validate(vo, Update.class);
    	GridUserCheckUtils.gridUserCheck(map);
        
    	DataSourceSwitcher.setMaster();
    	//DataSourceSwitcher.setShardingSphere("ShardingDataSource");
    	if (commonService.update(nameSpace + "updateGridUser", map) != 1) {
    		return "修改人员失败";
        }
        return "success";
    }
    
    @ApiOperation(value = "网格员部门定责新增", desc = "网格员部门定责新增")
    public String insetDuty(Map<String, Object> map) {
    	UserInfoBo userInfo = UserInfoBo.getUserInfo(map);
        UserGradeEnum.checkUserPermission(userInfo.getCompany_grade(),UserGradeEnum.CITY);
        DutyCheckUtils.dutyCheck(map);
        map.put("city_id", userInfo.getCompany_id());
        try {
        	commonService.insert(nameSpaceDuty + "insetUserDuty", map);
        }catch (Exception e) {
        	e.printStackTrace();
			throw new CustomException("新增失败，请检查当前部门职责是否已被制定！");
		}
        return "success";
    }

    @ApiOperation(value = "网格员部门定责更新", desc = "网格员部门定责更新")
    public String updateUserDutyById(Map<String, Object> map) {
    	UserInfoBo userInfo = UserInfoBo.getUserInfo(map);
        UserGradeEnum.checkUserPermission(userInfo.getCompany_grade(),UserGradeEnum.CITY);
        if (StringUtils.isEmpty(map.get("id"))) {
            throw new CustomException("数据主键未传");
        }
        DutyCheckUtils.dutyCheck(map);
        map.put("city_id", userInfo.getCompany_id());
        try {
        	commonService.update(nameSpaceDuty + "updateUserDutyById", map);
        }catch (Exception e) {
			throw new CustomException("修改失败，请检查当前部门职责是否已被制定！");
		}
        return "success";
    }

    @ApiOperation(value = "网格员定责删除", desc = "网格员定责删除")
    public String deleteUserDutyById(Map<String, Object> map) {
    	UserInfoBo userInfo = UserInfoBo.getUserInfo(map);
    	UserGradeEnum.checkUserPermission(userInfo.getCompany_grade(),UserGradeEnum.CITY);
        if (StringUtils.isEmpty(map.get("id"))) {
            throw new CustomException("数据主键未传");
        }
        try {
        	commonService.delete(nameSpaceDuty + "deleteUserDutyById", map);
        	commonService.update(nameSpaceDuty + "removeGardenUserDutys", MapUtil.getStr(map, "id"));
        }catch (Exception e) {
			throw new CustomException("删除网格员定责失败！");
		}
        
        return "success";
    }


    @ApiOperation(value = "网格员定线添加", desc = "网格员定线添加")
    public String insertGardenUserFixed(Map<String, Object> map) {
        DutyCheckUtils.fixedCheck(map);
        if (commonService.update(nameSpaceDuty + "insertGardenUserFixed", map) != 1) {
            throw new CustomException("新增失败");
        }
        return "success";
    }

    @ApiOperation(value = "网格员定线修改", desc = "网格员定线修改")
    public String updateGardenUserFixed(Map<String, Object> map) {
        DutyCheckUtils.fixedCheck(map);
        if (commonService.update(nameSpaceDuty + "updateGardenUserFixed", map) != 1) {
            throw new CustomException("修改定责信息失败");
        }
        return "success";
    }

    @ApiOperation(value = "网格员定人添加", desc = "网格员定人添加")
    public String insertGardenUser(Map<String, Object> map) {
        DutyCheckUtils.GardenUserCheck(map);
        if (commonService.update(nameSpaceDuty + "insertGardenUser", map) != 1) {
            throw new CustomException("新增失败");
        }
        return "success";
    }

    @ApiOperation(value = "网格员定人修改", desc = "网格员定人修改")
    public String updateGardenUser(Map<String, Object> map) {
        DutyCheckUtils.GardenUserCheck(map);
        if (commonService.update(nameSpaceDuty + "updateGardenUser", map) != 1) {
            throw new CustomException("修改定责信息失败");
        }
        return "success";
    }

    @ApiOperation(value = "标签列表树形结构", desc = "标签列表树形结构")
    public List<Map<String, Object>> selectGridFocusGroupTypeList(Map<String, Object> map) {
        List<Map<String, Object>> rootMenu = new ArrayList<Map<String, Object>>();
        map.put("parent_id", "0");
        List<Map<String, Object>> firstList = commonService.findList(nameSpaceFocusGroup + "selectGridFocusGroupTypeList", map);
        map.remove("parent_id");
        List<Map<String, Object>> subList = commonService.findList(nameSpaceFocusGroup + "selectGridFocusGroupTypeList", map);
        for (Map<String, Object> sub : firstList) {
            List<Map<String, Object>> childList = this.getChild(String.valueOf(sub.get("id")), subList);
            sub.put("children", childList);
            rootMenu.add(sub);
        }
        return rootMenu;
    }

    /**
     * 获取子节点
     *
     * @param id       父节点id
     * @param menuList 所有菜单列表
     * @return 每个根节点下，所有子菜单列表
     */
    private List<Map<String, Object>> getChild(String id, List<Map<String, Object>> menuList) {
        //子菜单
        List<Map<String, Object>> childList = new ArrayList<Map<String, Object>>();
        for (Map<String, Object> nav : menuList) {
            // 遍历所有节点，将所有菜单的父id与传过来的根节点的id比较
            //相等说明：为该根节点的子节点。
            if (String.valueOf(nav.get("parent_id")).equals(id)) {
                childList.add(nav);
            }
        }
        //递归
        for (Map<String, Object> nav : childList) {
            List<Map<String, Object>> subList = this.getChild(String.valueOf(nav.get("id")), menuList);
            if (subList.size() != 0) {
                nav.put("children", subList);
            }
        }
        //如果节点下没有子节点，返回一个空List（递归退出）
        if (childList.size() == 0) {
            return new ArrayList<Map<String, Object>>();
        }
        return childList;
    }

    private Map<String, Object> getCityId(Map<String, Object> map) {
        return commonService.getObject(nameSpaceSys + "getCityId", map);
    }
    
    @ApiOperation(value = "查询网格居民", desc = "查询网格居民")
    public Map getGridUser(Map<String, Object> map) {
    	DataSourceSwitcher.setMaster();
    	//DataSourceSwitcher.setShardingSphere("ShardingDataSource");
    	Map<String, Object> user = commonService.getObject(nameSpace + "getGridUserByCardNo", map);
    	user.put("cardno", map.get("cardno"));
        return user;
    }
}
