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

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@Api("评分等级维护")
@Service("keyPersonLevelSet")
public class KeyPersonLevelSetServiceImpl {

    @Autowired
    CommonService commonService;

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

    @ApiOperation(value = "列表", desc = "查询评分等级（sys_dict，type=rating_level）")
    public List<Map<String, Object>> selectList(Map<String, Object> map) {
        return commonService.findList(namespace + "selectList", map);
    }

    @ApiOperation(value = "新增或修改", desc = "根据是否传 id 判断：无 id 新增，有 id 更新；校验 value 唯一且必填，label 必填，sort 必须为数字")
    public String save(Map<String, Object> map) {
        if (map == null) throw new CustomException("参数不能为空");
        String value = str(map.get("value"));
        String label = str(map.get("label"));
        String id = str(map.get("id"));
        String sortStr = str(map.get("sort"));

        if (StringUtils.isBlank(value)) throw new CustomException("评分等级（value）不能为空");
        if (StringUtils.isBlank(label)) throw new CustomException("评分描述（label）不能为空");
        if (StringUtils.isBlank(sortStr)) throw new CustomException("排序不能为空");
        try {
            new BigDecimal(sortStr);
        } catch (Exception e) {
            throw new CustomException("排序必须为数字");
        }

        // 重复性校验（同 type 下 value 不能重复）
        Integer exists = commonService.getObject(namespace + "existsByValue", map);
        if (exists != null && exists > 0) {
            throw new CustomException("评分等级已存在，不可重复");
        }

        if (StringUtils.isBlank(id)) {
            int n = commonService.insert(namespace + "insert", map);
            if (n != 1) throw new CustomException("保存失败");
        } else {
            int n = commonService.update(namespace + "update", map);
            if (n < 0) throw new CustomException("保存失败");
        }
        return SUCCESS;
    }

    @ApiOperation(value = "删除", desc = "逻辑删除 del_flag=1")
    public String delete(Map<String, Object> map) {
        if (map == null) throw new CustomException("参数不能为空");
        Object id = map.get("id");
        if (id == null || StringUtils.isBlank(String.valueOf(id))) throw new CustomException("缺少ID");
        int n = commonService.update(namespace + "delete", map);
        if (n < 0) throw new CustomException("删除失败");
        return SUCCESS;
    }

    private String str(Object o) { return o == null ? null : String.valueOf(o); }
}
