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

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.db.service.CommonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api("人员分类权限管理")
@Service("keyDmUserCategoryPermission")
public class KeyDmUserCategoryPermissionServiceImpl {
    @Autowired
    private CommonService commonService;

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

    @ApiOperation(value = "查询人员分类权限列表", desc = "根据分类ID查询权限列表")
    public List<Map<String, Object>> selectList(Map<String, Object> map) {
        if (map == null) {
            map = new HashMap<>();
        }
        return commonService.findList(namespace + "selectList", map);
    }

    @ApiOperation(value = "保存人员分类权限", desc = "保存分类的权限配置，先删除旧权限再插入新权限")
    public String save(Map<String, Object> map) {
        if (map == null) {
            throw new CustomException("参数不能为空");
        }
        Object categoryId = map.get("category_id");
        if (categoryId == null || String.valueOf(categoryId).trim().isEmpty()) {
            throw new CustomException("分类ID不能为空");
        }
        
        // 先删除该分类的所有权限
        commonService.delete(namespace + "deleteByCategoryId", map);
        
        // 插入新权限
        Object permissions = map.get("permissions");
        if (permissions != null && permissions instanceof List) {
            List<Map<String, Object>> permissionList = (List<Map<String, Object>>) permissions;
            for (Map<String, Object> permission : permissionList) {
                permission.put("category_id", categoryId);
                if (commonService.insert(namespace + "insert", permission) != 1) {
                    throw new CustomException("保存权限失败");
                }
            }
        }
        return SUCCESS;
    }
}

