package org.linlinjava.jz.db.service;

import org.linlinjava.jz.db.dao.JzCallConfigMapper;
import org.linlinjava.jz.db.domain.JzCallConfig;
import org.linlinjava.jz.db.domain.JzCallConfigExample;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class JzCallConfigService {
    @Resource
    private JzCallConfigMapper systemMapper;

    public Map<String, String> queryAll() {
        JzCallConfigExample example = new JzCallConfigExample();
        example.or().andDeletedEqualTo(false);

        List<JzCallConfig> systemList = systemMapper.selectByExample(example);
        Map<String, String> systemConfigs = new HashMap<>();
        for (JzCallConfig item : systemList) {
            systemConfigs.put(item.getKeyName(), item.getKeyValue());
        }

        return systemConfigs;
    }


    public Map<String, String> listCall() {
        JzCallConfigExample example = new JzCallConfigExample();
        example.or().andKeyNameLike("jz_call_%").andDeletedEqualTo(false);
        List<JzCallConfig> systemList = systemMapper.selectByExample(example);
        Map<String, String> data = new HashMap<>();
        for(JzCallConfig system : systemList){
            data.put(system.getKeyName(), system.getKeyValue());
        }
        return data;
    }


    public void updateConfig(Map<String, String> data) {
        for (Map.Entry<String, String> entry : data.entrySet()) {
            JzCallConfigExample example = new JzCallConfigExample();
            example.or().andKeyNameEqualTo(entry.getKey()).andDeletedEqualTo(false);

            JzCallConfig system = new JzCallConfig();
            system.setKeyName(entry.getKey());
            system.setKeyValue(entry.getValue());
            system.setUpdateTime(LocalDateTime.now());
            systemMapper.updateByExampleSelective(system, example);
        }

    }

    public void addConfig(String key, String value) {
        JzCallConfig system = new JzCallConfig();
        system.setKeyName(key);
        system.setKeyValue(value);
        system.setAddTime(LocalDateTime.now());
        system.setUpdateTime(LocalDateTime.now());
        systemMapper.insertSelective(system);
    }

    public JzCallConfig selectByKeyName(String keyName) {
        JzCallConfigExample example = new JzCallConfigExample();
        example.or().andKeyNameEqualTo(keyName);
        return systemMapper.selectOneByExample(example);
    }
}
