package com.sckw.excel.translate.context;

import com.alibaba.fastjson.JSON;
import com.sckw.core.common.enums.NumberConstant;
import com.sckw.excel.translate.Sources;
import com.sckw.core.exception.SourceInitializeException;
import com.sckw.excel.translate.properties.TranslateProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 *
 * 组织机构信息数据源
 *
 *
 * @author lfdc
 * @version v1
 * @create 2020-11-28 14:18:49
 * @copyright
 */
@Component(value = "organizationSource")
public class Organization implements Source, Ordered {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private TranslateProperties properties;

    public Organization() {
        initial();
    }

    @Override
    @SuppressWarnings("unchecked")
    public Map<Integer, Object> get() throws SourceInitializeException {
        Object values = redisTemplate.opsForValue().get(Sources.SOURCE_ORGANIZATION);
        if (values == null) {
            return flush();
        }
        return (Map<Integer, Object>) values;
    }

    @Override
    @SuppressWarnings("unchecked")
    public Map<Integer, Object> flush() throws SourceInitializeException {
        try {
            String content = restTemplate.postForObject(properties.getOrganizationUrl(), null, String.class);
            Map<String, Object> result = JSON.parseObject(content, Map.class);

            Object status = result.get("status");
            Assert.isTrue(status != null && (Integer) status == NumberConstant.TWO_HUNDRED, "The status code returned is failure");

            Object data = result.get("data");
            if (data != null) {
                Map<Integer, Object> source = (Map<Integer, Object>) result.get("data");
                if (!source.isEmpty()) {
                    redisTemplate.opsForValue().set(Sources.SOURCE_ORGANIZATION, source, properties.getExpireTime(), TimeUnit.MINUTES);
                    return source;
                }
            }
            throw new SourceInitializeException("the resulting organization cache data is empty");
        } catch (Exception e) {
            throw new SourceInitializeException("failed to get organization cache data, ex:" + e.toString());
        }
    }

    @Override
    public void clear() {
        redisTemplate.delete(Sources.SOURCE_ORGANIZATION);
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}