package com.bizzan.bitrade.service;

import com.bizzan.bitrade.dao.ConfigCoinSymbolDao;
import com.bizzan.bitrade.entity.ConfigCoinSymbol;
import com.bizzan.bitrade.service.Base.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class ConfigCoinSymbolService extends BaseService {

    /** isOpen=1 表示开启 */
    private static final int IS_OPEN_ENABLED = 1;

    @Autowired
    private ConfigCoinSymbolDao configCoinSymbolDao;

    /**
     * 开启币种内存缓存，启动时加载，每 10 分钟刷新一次
     * volatile 保证多线程可见性
     */
    private volatile List<ConfigCoinSymbol> openCoinSymbolCache = Collections.emptyList();

    /**
     * 启动时加载开启币种缓存
     *
     * @author auto
     * @date 2026-05-20
     */
    @PostConstruct
    public void initOpenCoinSymbolCache() {
        refreshOpenCoinSymbolCache();
    }

    /**
     * 每 10 分钟刷新一次开启币种缓存
     *
     * @author auto
     * @date 2026-05-20
     */
    @Scheduled(fixedRate = 10 * 60 * 1000)
    public void refreshOpenCoinSymbolCache() {
        try {
            List<ConfigCoinSymbol> list = configCoinSymbolDao.findByIsOpenOrderBySortAsc(IS_OPEN_ENABLED);
            openCoinSymbolCache = list != null ? list : Collections.emptyList();
            log.info("[ConfigCoinSymbolService] 开启币种缓存刷新完成，共 {} 个币种", openCoinSymbolCache.size());
        } catch (Exception e) {
            log.warn("[ConfigCoinSymbolService] 开启币种缓存刷新失败: {}", e.getMessage());
        }
    }

    /**
     * 获取所有开启的币种配置（从内存缓存读取）
     *
     * @return 开启的币种配置列表，按 sort 升序
     * @author auto
     * @date 2026-05-20
     */
    public List<ConfigCoinSymbol> getOpenCoinSymbols() {
        return openCoinSymbolCache;
    }

    public ConfigCoinSymbol findOne(Long id) {
        return configCoinSymbolDao.findOne(id);
    }

    public ConfigCoinSymbol findByCoinSymbol(String coinSymbol) {
        return configCoinSymbolDao.findByCoinSymbol(coinSymbol);
    }

    public List<ConfigCoinSymbol> findAll() {
        return configCoinSymbolDao.findAll();
    }

    public Page<ConfigCoinSymbol> pageQuery(String coinSymbol, String startTime, String endTime, Pageable pageable) {
        Specification<ConfigCoinSymbol> spec = (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (StringUtils.hasText(coinSymbol)) {
                predicates.add(cb.like(cb.upper(root.get("coinSymbol")), "%" + coinSymbol.toUpperCase() + "%"));
            }
            if (StringUtils.hasText(startTime)) {
                predicates.add(cb.greaterThanOrEqualTo(root.get("mtime"), startTime));
            }
            if (StringUtils.hasText(endTime)) {
                predicates.add(cb.lessThanOrEqualTo(root.get("mtime"), endTime + " 23:59:59"));
            }
            return cb.and(predicates.toArray(new Predicate[0]));
        };
        return configCoinSymbolDao.findAll(spec, pageable);
    }

    public ConfigCoinSymbol create(ConfigCoinSymbol coin) {
        coin.setCtime(new Date());
        coin.setMtime(new Date());
        return configCoinSymbolDao.save(coin);
    }

    public ConfigCoinSymbol update(ConfigCoinSymbol coin) {
        coin.setMtime(new Date());
        return configCoinSymbolDao.save(coin);
    }

    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        configCoinSymbolDao.delete(id);
    }

    @Transactional(rollbackFor = Exception.class)
    public void toggleStatus(Long id) {
        ConfigCoinSymbol coin = configCoinSymbolDao.findOne(id);
        if (coin != null) {
            coin.setIsOpen(coin.getIsOpen() == 1 ? 0 : 1);
            coin.setMtime(new Date());
            configCoinSymbolDao.save(coin);
        }
    }
}
