package com.example.demo.service;

import com.example.demo.model.Dictionary;
import jakarta.annotation.PostConstruct;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

/**
 * 数据字典管理服务。
 * 使用内存假数据实现数据字典的维护功能。
 */
@Service
public class DictionaryService {

    /** 内存数据存储 */
    private final Map<Long, Dictionary> dictMap = new ConcurrentHashMap<>();

    private final AtomicLong idGenerator = new AtomicLong(300);

    /**
     * 新增字典项。
     *
     * @requirement(name="字典管理", id="SRS-IMS_F-004")
     *
     * @param dictionary 字典项信息
     * @return 创建后的字典项
     */
    public Dictionary createDictionary(Dictionary dictionary) {
        long id = idGenerator.incrementAndGet();
        dictionary.setId(id);
        dictionary.setCreateTime(LocalDateTime.now());
        dictionary.setUpdateTime(LocalDateTime.now());
        if (dictionary.getStatus() == null) {
            dictionary.setStatus(1);
        }
        dictMap.put(id, dictionary);
        return dictionary;
    }

    /**
     * 编辑字典项。
     *
     * @requirement(name="字典管理", id="SRS-IMS_F-004")
     *
     * @param id          字典ID
     * @param dictionary  更新后的字典信息
     * @return 更新后的字典项
     */
    public Dictionary updateDictionary(Long id, Dictionary dictionary) {
        Dictionary existing = dictMap.get(id);
        if (existing == null) {
            throw new IllegalArgumentException("字典项不存在，ID: " + id);
        }
        if (dictionary.getDictType() != null) {
            existing.setDictType(dictionary.getDictType());
        }
        if (dictionary.getDictTypeName() != null) {
            existing.setDictTypeName(dictionary.getDictTypeName());
        }
        if (dictionary.getItemKey() != null) {
            existing.setItemKey(dictionary.getItemKey());
        }
        if (dictionary.getItemValue() != null) {
            existing.setItemValue(dictionary.getItemValue());
        }
        if (dictionary.getSortOrder() != null) {
            existing.setSortOrder(dictionary.getSortOrder());
        }
        if (dictionary.getStatus() != null) {
            existing.setStatus(dictionary.getStatus());
        }
        existing.setUpdateTime(LocalDateTime.now());
        dictMap.put(id, existing);
        return existing;
    }

    /**
     * 删除字典项。
     *
     * @requirement(name="字典管理", id="SRS-IMS_F-004")
     *
     * @param id 字典ID
     */
    public void deleteDictionary(Long id) {
        if (!dictMap.containsKey(id)) {
            throw new IllegalArgumentException("字典项不存在，ID: " + id);
        }
        dictMap.remove(id);
    }

    /**
     * 查询字典列表，支持按字典类型筛选。
     *
     * @requirement(name="字典管理", id="SRS-IMS_F-004")
     *
     * @param dictType 字典类型（可选）
     * @return 字典项列表
     */
    public List<Dictionary> listDictionaries(String dictType) {
        List<Dictionary> allDicts = new ArrayList<>(dictMap.values());
        if (dictType != null && !dictType.isBlank()) {
            allDicts = allDicts.stream()
                    .filter(d -> dictType.equals(d.getDictType()))
                    .collect(Collectors.toList());
        }
        return allDicts;
    }

    /**
     * 初始化默认字典数据。
     */
    @PostConstruct
    public void initDefaultDicts() {
        if (dictMap.isEmpty()) {
            dictMap.put(1L, new Dictionary(1L, "business_type", "业务类型", "finance", "财务", 1, 1));
            dictMap.put(2L, new Dictionary(2L, "business_type", "业务类型", "project", "项目", 2, 1));
            dictMap.put(3L, new Dictionary(3L, "business_type", "业务类型", "purchase", "采购", 3, 1));
            dictMap.put(4L, new Dictionary(4L, "business_type", "业务类型", "hr", "人事", 4, 1));
            dictMap.put(5L, new Dictionary(5L, "user_status", "用户状态", "1", "启用", 1, 1));
            dictMap.put(6L, new Dictionary(6L, "user_status", "用户状态", "0", "禁用", 2, 1));
            dictMap.put(7L, new Dictionary(7L, "business_status", "业务状态", "draft", "草稿", 1, 1));
            dictMap.put(8L, new Dictionary(8L, "business_status", "业务状态", "pending", "待审核", 2, 1));
            dictMap.put(9L, new Dictionary(9L, "business_status", "业务状态", "approved", "已通过", 3, 1));
            dictMap.put(10L, new Dictionary(10L, "business_status", "业务状态", "rejected", "已驳回", 4, 1));
            dictMap.put(11L, new Dictionary(11L, "business_status", "业务状态", "archived", "已归档", 5, 1));

            // 设置时间
            dictMap.values().forEach(d -> {
                d.setCreateTime(LocalDateTime.now());
                d.setUpdateTime(LocalDateTime.now());
            });
        }
    }
}
