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("keyPersonVisitPower")
public class KeyPersonVisitPowerServiceImpl {
    @Autowired
    private CommonService commonService;

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

    @ApiOperation(value = "查询按钮权限列表", desc = "从字典page_button加载所有按钮并合并权限配置")
    public List<Map<String, Object>> selectPageButtonPowerList(Map<String, Object> map) {
        return commonService.findList(namespace + "selectPageButtonPowerList", map == null ? new HashMap<>() : map);
    }

    @ApiOperation(value = "保存按钮权限配置", desc = "为按钮配置可见部门类型，多选，存labels与values")
    public String savePageButtonPower(Map<String, Object> map) {
        if (map == null) {
            throw new CustomException("参数不能为空");
        }
        Object value = map.get("rating_dict_value");
        Object label = map.get("rating_dict_label");
        if (value == null || String.valueOf(value).trim().isEmpty()) {
            throw new CustomException("缺少按钮标识");
        }
        if (label == null || String.valueOf(label).trim().isEmpty()) {
            throw new CustomException("缺少按钮名称");
        }
        // 允许清空权限：labels/values可为空字符串
        Map<String, Object> exists = commonService.getObject(namespace + "getPowerByRatingValue", map);
        if (exists == null) {
            // insert
            if (commonService.insert(namespace + "insertPower", map) != 1) {
                throw new CustomException("保存失败");
            }
        } else {
            // update by rating_dict_value
            int affected = commonService.update(namespace + "updatePower", map);
            // MySQL 会在值未变化时返回 0，视为成功
            if (affected < 0) {
                throw new CustomException("保存失败");
            }
        }
        return SUCCESS;
    }
}
