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

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.UUIDUtil;
import com.scpyun.base.db.service.CommonService;
import com.scpyun.platform.jilinsscgsdp.utils.DataScopeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.scpyun.platform.jilinsscgsdp.utils.MaterialFileListener;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.io.IOException;

@Api("基础配置管理")
@Service("keyDmUserCategory")
public class KeyDmUserCategoryServiceImpl {
    @Autowired
    private CommonService commonService;

    private static final String SUCCESS = "success";
    private final String namespace = "com.scpyun.platform.standard.jilinsscgsdp.keyDmUserCategory.";

    @ApiOperation(value = "获取人员权限配置列表", desc = "从字典获取权限并关联用户")
    public List<Map<String, Object>> selectPermissionConfigList() {
        return commonService.findList(namespace + "selectPermissionConfigList", null);
    }

    @ApiOperation(value = "获取人员权限配置列表", desc = "从字典获取权限并关联用户")
    public List<Map<String, Object>> selectUserDmPermissionList(Map<String, Object> map) {
        return commonService.findList(namespace + "selectUserDmPermissionList", map);
    }

    @ApiOperation(value = "保存权限用户配置", desc = "保存权限对应的用户配置")
    public String savePermissionUsers(Map<String, Object> map) {
        if (map == null || map.get("permission_code") == null) {
            throw new CustomException("参数缺失");
        }

        String permissionCode = map.get("permission_code").toString();
        @SuppressWarnings("unchecked")
        List<String> userIds = (List<String>) map.get("user_ids");

        // 先删除原有配置
        Map<String, Object> deleteParam = new HashMap<>();
        deleteParam.put("permission_code", permissionCode);
        commonService.delete(namespace + "deletePermissionUsers", deleteParam);

        // 再插入新配置
        if (userIds != null && !userIds.isEmpty()) {
            for (String userId : userIds) {
                Map<String, Object> insertParam = new HashMap<>();
                insertParam.put("permission_code", permissionCode);
                insertParam.put("user_id", userId);
                commonService.insert(namespace + "insertPermissionUser", insertParam);
            }
        }

        return SUCCESS;
    }

    // ===== 请假类型管理 =====
    @ApiOperation(value = "查询请假类型", desc = "查询请假类型")
    public List<Map<String, Object>> findLeaveTypeList(Map<String,Object> map) {
        if (map == null) {
            map = new HashMap<>();
        }
        return commonService.findList(namespace + "findLeaveTypeList", map);
    }

    @ApiOperation(value = "查询请假类型列表", desc = "分页查询请假类型")
    public Page<Map<String, Object>> selectLeaveTypeList(Page<Map<String,Object>> map) {
        if (map == null) map = new Page<>();
        return commonService.findPage(namespace + "selectLeaveTypeList", map);
    }

    @ApiOperation(value = "保存请假类型", desc = "新增或修改请假类型")
    public String saveLeaveType(Map<String, Object> map) {
        if (map == null) {
            throw new CustomException("参数不能为空");
        }
        Object id = map.get("id");
        if (id == null || String.valueOf(id).trim().isEmpty()) {
            // 新增
            map.put("id", UUIDUtil.getUUID());
            if (commonService.insert(namespace + "insertLeaveType", map) != 1) {
                throw new CustomException("保存失败");
            }
        } else {
            // 修改
            int affected = commonService.update(namespace + "updateLeaveType", map);
            if (affected < 0) throw new CustomException("保存失败");
        }
        return SUCCESS;
    }

    @ApiOperation(value = "删除请假类型", desc = "逻辑删除请假类型")
    public String deleteLeaveType(Map<String, Object> map) {
        if (map == null || map.get("id") == null) {
            throw new CustomException("参数不能为空");
        }
        int affected = commonService.update(namespace + "deleteLeaveType", map);
        if (affected < 0) throw new CustomException("删除失败");
        return SUCCESS;
    }

    // ===== 办公用品分类管理 =====
    @ApiOperation(value = "查询办公用品分类", desc = "查询办公用品分类")
    public List<Map<String, Object>> findMaterialCategoryList(Map<String, Object> map) {
        if (map == null) {
            map = new HashMap<>();
        }
        return commonService.findList(namespace + "findMaterialCategoryList", map);
    }

    @ApiOperation(value = "查询办公用品分类列表", desc = "分页查询办公用品分类")
    public Page<Map<String, Object>> selectMaterialCategoryList(Page<Map<String, Object>> map) {
        if (map == null) map = new Page<>();
        return commonService.findPage(namespace + "selectMaterialCategoryList", map);
    }

    @ApiOperation(value = "保存办公用品分类", desc = "新增或修改办公用品分类")
    public String saveMaterialCategory(Map<String, Object> map) {
        if (map == null) {
            throw new CustomException("参数不能为空");
        }
        Object id = map.get("id");
        if (id == null || String.valueOf(id).trim().isEmpty()) {
            // 新增
            map.put("id", UUIDUtil.getUUID());
            if (commonService.insert(namespace + "insertMaterialCategory", map) != 1) {
                throw new CustomException("保存失败");
            }
        } else {
            // 修改
            int affected = commonService.update(namespace + "updateMaterialCategory", map);
            if (affected < 0) throw new CustomException("保存失败");
        }
        return SUCCESS;
    }

    @ApiOperation(value = "删除办公用品分类", desc = "逻辑删除办公用品分类")
    public String deleteMaterialCategory(Map<String, Object> map) {
        if (map == null || map.get("id") == null) {
            throw new CustomException("参数不能为空");
        }
        int affected = commonService.update(namespace + "deleteMaterialCategory", map);
        if (affected < 0) throw new CustomException("删除失败");
        return SUCCESS;
    }

    // ===== 办公用品管理 =====
    @ApiOperation(value = "查询办公用品列表", desc = "分页查询办公用品")
    public Page<Map<String, Object>> findMaterialList(Page<Map<String, Object>> map) {
        if (map == null) map = new Page<>();
        return commonService.findPage(namespace + "findMaterialList", map);
    }

    @ApiOperation(value = "查询办公用品列表", desc = "分页查询办公用品")
    public Page<Map<String, Object>> selectMaterialList(Page<Map<String, Object>> map) {
        if (map == null) map = new Page<>();
        return commonService.findPage(namespace + "selectMaterialList", map);
    }

    @ApiOperation(value = "保存办公用品", desc = "新增或修改办公用品")
    public String saveMaterial(Map<String, Object> map) {
        if (map == null) {
            throw new CustomException("参数不能为空");
        }
        Object id = map.get("id");
        if (id == null || String.valueOf(id).trim().isEmpty()) {
            // 新增
            map.put("id", UUIDUtil.getUUID());
            if (commonService.insert(namespace + "insertMaterial", map) != 1) {
                throw new CustomException("保存失败");
            }
        } else {
            // 修改
            int affected = commonService.update(namespace + "updateMaterial", map);
            if (affected < 0) throw new CustomException("保存失败");
        }
        return SUCCESS;
    }

    @ApiOperation(value = "删除办公用品", desc = "逻辑删除办公用品")
    public String deleteMaterial(Map<String, Object> map) {
        if (map == null || map.get("id") == null) {
            throw new CustomException("参数不能为空");
        }
        int affected = commonService.update(namespace + "deleteMaterial", map);
        if (affected < 0) throw new CustomException("删除失败");
        return SUCCESS;
    }

    @ApiOperation(value = "导入物料", desc = "解析 Excel 导入物料信息")
    public Map<String, Object> importMaterial(Map<String, Object> map, MultipartFile file) {
        Map<String, Object> result = new HashMap<>();
        try {
            MaterialFileListener listener = new MaterialFileListener(commonService, namespace, map);
            EasyExcel.read(file.getInputStream(), com.scpyun.platform.jilinsscgsdp.bean.entity.MaterialImp.class, listener).sheet().headRowNumber(1).doRead();
            result = listener.getResult();
        } catch (IOException e) {
            throw new CustomException("导入失败");
        }
        return result;
    }

    @ApiOperation(value = "导入模板下载", desc = "下载物料导入模板")
    public void templateDownload(Map<String, Object> map, HttpServletResponse response) {
        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 tpl = "keyMaterialImp.xlsx";
            Resource resource = new ClassPathResource(tpl);
            InputStream is = resource.getInputStream();
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(is).excelType(ExcelTypeEnum.XLSX).build();
            excelWriter.finish();
        } catch (Exception e) {
            throw new CustomException("模板下载失败");
        }
    }

    @ApiOperation(value = "获取人员权限配置列表", desc = "从字典获取权限并关联用户")
    public List<Map<String, Object>> selectOrgPermission(Map<String, Object> map) {
        if (map == null) map = new HashMap<>();
        Map<String, Object> user = (Map<String, Object>) map.get("_user");
        String leader = commonService.getObject(namespace + "findLeader", user.get("id"));
        List<Map<String, Object>> userList = commonService.findList(namespace + "selectOrgPermission", map);
        for (Map<String, Object> map1 : userList) {
            if (map1.get("id") != null && map1.get("id").equals(leader)){
                map1.put("leader",1);
            }
        }
        return userList;
    }

	// ===== 图表分析 =====
    @ApiOperation(value = "获取汇总统计数据", desc = "获取请假、申领、入库次数统计")
    public Map<String, Object> getSummaryStats() {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> map = new HashMap<>();

        // 请假次数
        Map<String, Object> leaveCount = commonService.getObject(namespace + "getLeaveCount", map);
        result.put("leaveCount", leaveCount != null ? leaveCount.get("count") : 0);

        // 申领次数
        Map<String, Object> borrowCount = commonService.getObject(namespace + "getBorrowCount", map);
        result.put("borrowCount", borrowCount != null ? borrowCount.get("count") : 0);

        // 入库次数
        Map<String, Object> inboundCount = commonService.getObject(namespace + "getInboundCount", map);
        result.put("inboundCount", inboundCount != null ? inboundCount.get("count") : 0);

        return result;
    }

    @ApiOperation(value = "获取请假类型统计", desc = "获取各请假类型的占比统计")
    public List<Map<String, Object>> getLeaveTypeStats() {
        return commonService.findList(namespace + "getLeaveTypeStats", null);
    }

    @ApiOperation(value = "获取人员请假统计", desc = "获取月度各人员的请假次数统计")
    public List<Map<String, Object>> getLeaveUserStats() {
        return commonService.findList(namespace + "getLeaveUserStats", null);
    }

    @ApiOperation(value = "获取用品领用统计", desc = "获取月度各用品的领用量统计")
    public List<Map<String, Object>> getMaterialUsageStats() {
        return commonService.findList(namespace + "getMaterialUsageStats", null);
    }

    @ApiOperation(value = "获取库存预警列表", desc = "获取超出或低于阙值的用品信息")
    public List<Map<String, Object>> getStockWarningList() {
        return commonService.findList(namespace + "getStockWarningList", null);
    }

    // ===== 部门管理 =====
    @ApiOperation(value = "查询部门列表", desc = "分页查询部门")
    public Page<Map<String, Object>> selectOrgList(Page<Map<String, Object>> map) {
        if (map == null) map = new Page<>();
        Map<String, Object> user = (Map<String, Object>) map.getParams().get("_user");
        Map<String, String> pos = DataScopeUtil.getPosition(user);
        map.getParams().put("area_id", pos.get("area_id"));
        return commonService.findPage(namespace + "selectOrgList", map);
    }

    @ApiOperation(value = "保存部门", desc = "新增或修改部门")
    public String saveOrg(Map<String, Object> map) {
        if (map == null) {
            throw new CustomException("参数不能为空");
        }
        Object id = map.get("id");
        if (id == null || String.valueOf(id).trim().isEmpty()) {
            Map<String, Object> user = (Map<String, Object>) map.get("_user");
            Map<String, String> pos = DataScopeUtil.getPosition(user);
            // 新增
            map.put("id", UUIDUtil.getUUID());
            map.put("source_org", pos.get("area_id"));
            map.put("org_code", map.get("id"));
            if (commonService.insert(namespace + "insertOrg", map) != 1) {
                throw new CustomException("保存失败");
            }
        } else {
            // 修改
            int affected = commonService.update(namespace + "updateOrg", map);
            if (affected < 0) throw new CustomException("保存失败");
        }
        return SUCCESS;
    }

    @ApiOperation(value = "删除部门", desc = "逻辑删除部门")
    public String deleteOrg(Map<String, Object> map) {
        if (map == null || map.get("id") == null) {
            throw new CustomException("参数不能为空");
        }
        int affected = commonService.update(namespace + "deleteOrg", map);
        if (affected < 0) throw new CustomException("删除失败");
        return SUCCESS;
    }

    @ApiOperation(value = "分配用户到部门", desc = "将用户分配到指定部门")
    public String assignUsersToOrg(Map<String, Object> map) {
        if (map == null || map.get("org_id") == null) {
            throw new CustomException("参数缺失");
        }

        String orgId = map.get("org_id").toString();
        List<String> userIds = (List<String>) map.get("user_ids");
        Map<String, Object> user = (Map<String, Object>) map.get("_user");
        Map<String, String> pos = DataScopeUtil.getPosition(user);

        // 先清除该部门的所有用户分配
        Map<String, Object> clearParam = new HashMap<>();
        clearParam.put("belong_org_id", orgId);
        clearParam.put("area_id", pos.get("area_id"));
        clearParam.put("parent_ids", user.get("parent_ids")+","+pos.get("area_id"));
        commonService.update(namespace + "clearOrgUsers", clearParam);

        // 再分配新用户
        if (userIds != null && !userIds.isEmpty()) {
            for (String userId : userIds) {
                Map<String, Object> assignParam = new HashMap<>();
                assignParam.put("user_id", userId);
                assignParam.put("belong_org_id", orgId);
                // 这里需要根据实际的部门信息设置其他字段
                // 暂时只更新 belong_org_id，后续可以扩展
                commonService.update(namespace + "assignUserToOrg", assignParam);
            }
        }

        return SUCCESS;
    }
}
