package com.bizzan.bitrade.service;

import com.bizzan.bitrade.dao.ExperienceGiftProductCoinRepository;
import com.bizzan.bitrade.dao.ExperienceGiftProductDao;
import com.bizzan.bitrade.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class ExperienceGiftProductService {

    @Autowired
    private ExperienceGiftProductDao productDao;

    @Autowired
    private ExperienceGiftProductCoinRepository coinRepository;

    // ----------------------------------------------------------------
    // 供业务模块使用
    // ----------------------------------------------------------------

    public ExperienceGiftProduct findById(Long id) {
        return productDao.findOne(id);
    }

    public List<ExperienceGiftProduct> findEnabled() {
        return productDao.findByStatus(ExperienceGiftProductStatus.ENABLED);
    }

    /** 返回所有启用的手动赠送类型产品（用于后台赠送下拉列表） */
    public List<ExperienceGiftProduct> findManualEnabled() {
        return productDao.findByStatusAndGrantType(
                ExperienceGiftProductStatus.ENABLED, ExperienceGiftGrantType.MANUAL);
    }

    public ExperienceGiftProduct save(ExperienceGiftProduct product) {
        return productDao.save(product);
    }

    // ----------------------------------------------------------------
    // 管理后台 - 分页列表
    // ----------------------------------------------------------------

    public Page<Map> pageQuery(String name, Integer status, Integer grantType, int pageNo, int pageSize) {
        return productDao.pageQuery(name, status, grantType, pageNo, pageSize);
    }

    // ----------------------------------------------------------------
    // 管理后台 - 详情（编辑回填）
    // ----------------------------------------------------------------

    public Map<String, Object> getDetail(Long id) {
        ExperienceGiftProduct product = productDao.findOne(id);
        if (product == null) return null;

        List<ExperienceGiftProductCoin> coins = coinRepository.findByProductId(id);

        Map<String, Object> result = new HashMap<>();
        result.put("id", product.getId());
        result.put("name", product.getName());
        result.put("amount", product.getAmount());
        result.put("validityDays", product.getValidityDays());
        result.put("totalQuantity", product.getTotalQuantity());
        result.put("perUserLimit", product.getPerUserLimit());
        result.put("maxProfitPerCard", product.getMaxProfitPerCard());
        result.put("grantType", product.getGrantType() != null ? product.getGrantType().getCode() : 0);
        result.put("triggerType", product.getTriggerType() != null ? product.getTriggerType().getCode() : null);
        result.put("minRechargeAmount", product.getMinRechargeAmount());
        result.put("minOpenValue", product.getMinOpenValue());
        result.put("minHoldMinutes", product.getMinHoldMinutes());
        result.put("status", product.getStatus() != null ? product.getStatus().getCode() : 0);
        result.put("remark", product.getRemark());

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        result.put("activityStartTime", product.getActivityStartTime() != null
                ? sdf.format(product.getActivityStartTime()) : null);
        result.put("activityEndTime", product.getActivityEndTime() != null
                ? sdf.format(product.getActivityEndTime()) : null);

        List<String> coinSymbols = new ArrayList<>();
        int leverage = 2;
        for (ExperienceGiftProductCoin c : coins) {
            coinSymbols.add(c.getCoinSymbol());
            leverage = c.getLeverage();
        }
        result.put("coins", coinSymbols);
        result.put("leverage", leverage);
        return result;
    }

    // ----------------------------------------------------------------
    // 管理后台 - 新增 / 修改
    // ----------------------------------------------------------------

    @Transactional(rollbackFor = Exception.class)
    public Long adminSave(Long id, String name, BigDecimal amount, Integer validityDays,
                          Integer leverage, Integer totalQuantity, Integer perUserLimit,
                          BigDecimal maxProfitPerCard,
                          Integer grantType, Integer triggerType,
                          Boolean hasMinRecharge, BigDecimal minRechargeAmount,
                          Boolean hasMinOpenValue, BigDecimal minOpenValue,
                          Boolean hasMinHoldMinutes, Integer minHoldMinutes,
                          String activityStartTime, String activityEndTime,
                          List<String> coins, Integer status, Long adminId) {

        Date now = new Date();
        ExperienceGiftProduct product;

        if (id != null) {
            product = productDao.findOne(id);
            if (product == null) throw new RuntimeException("产品不存在");
        } else {
            product = new ExperienceGiftProduct();
            product.setCreatedAt(now);
            product.setCreatedBy(adminId);
            product.setIssuedCount(0);
        }

        product.setName(name);
        product.setAmount(amount);
        product.setValidityDays(validityDays);
        product.setTotalQuantity(totalQuantity == null ? 0 : totalQuantity);
        product.setPerUserLimit(perUserLimit == null ? 1 : perUserLimit);
        product.setMaxProfitPerCard(maxProfitPerCard != null ? maxProfitPerCard : amount);
        product.setStatus(status != null && status == 1
                ? ExperienceGiftProductStatus.ENABLED : ExperienceGiftProductStatus.DISABLED);
        product.setUpdatedAt(now);

        ExperienceGiftGrantType grantTypeEnum = (grantType != null && grantType == 1)
                ? ExperienceGiftGrantType.SYSTEM_TRIGGER : ExperienceGiftGrantType.MANUAL;
        product.setGrantType(grantTypeEnum);

        // 解析活动时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date parsedStartTime = null;
        Date parsedEndTime = null;
        try {
            if (activityStartTime != null && !activityStartTime.isEmpty()) parsedStartTime = sdf.parse(activityStartTime);
            if (activityEndTime != null && !activityEndTime.isEmpty()) parsedEndTime = sdf.parse(activityEndTime);
        } catch (Exception ignored) {}

        if (grantTypeEnum == ExperienceGiftGrantType.SYSTEM_TRIGGER) {
            ExperienceGiftTriggerType triggerTypeEnum = (triggerType != null && triggerType == 1)
                    ? ExperienceGiftTriggerType.INVITE : ExperienceGiftTriggerType.REGISTER;
            product.setTriggerType(triggerTypeEnum);
            // 活动起止时间：
            // 新建：开始时间 = now，结束时间 = now + validityDays
            // 修改：开始时间保持不变，结束时间 = 原开始时间 + validityDays
            if (id == null) {
                Calendar actCal = Calendar.getInstance();
                actCal.setTime(now);
                actCal.add(Calendar.DAY_OF_MONTH, validityDays);
                product.setActivityStartTime(now);
                product.setActivityEndTime(actCal.getTime());
            } else {
                Date existingStart = product.getActivityStartTime();
                if (existingStart == null) existingStart = product.getCreatedAt() != null ? product.getCreatedAt() : now;
                Calendar actCal = Calendar.getInstance();
                actCal.setTime(existingStart);
                actCal.add(Calendar.DAY_OF_MONTH, validityDays);
                product.setActivityEndTime(actCal.getTime());
            }
            if (triggerTypeEnum == ExperienceGiftTriggerType.REGISTER) {
                product.setMinRechargeAmount(Boolean.TRUE.equals(hasMinRecharge) ? minRechargeAmount : null);
                product.setMinOpenValue(null);
                product.setMinHoldMinutes(null);
            } else {
                product.setMinRechargeAmount(null);
                product.setMinOpenValue(Boolean.TRUE.equals(hasMinOpenValue) ? minOpenValue : null);
                product.setMinHoldMinutes(Boolean.TRUE.equals(hasMinHoldMinutes) ? minHoldMinutes : null);
            }
        } else {
            product.setTriggerType(null);
            product.setActivityStartTime(null);
            product.setActivityEndTime(null);
            product.setMinRechargeAmount(null);
            product.setMinOpenValue(null);
            product.setMinHoldMinutes(null);
        }

        product = productDao.save(product);
        Long productId = product.getId();

        // 更新交易对（先删再插）
        if (id != null) {
            coinRepository.deleteByProductId(productId);
        }
        if (coins != null) {
            for (String symbol : coins) {
                ExperienceGiftProductCoin coin = new ExperienceGiftProductCoin();
                coin.setProductId(productId);
                coin.setCoinSymbol(symbol);
                coin.setLeverage(leverage != null ? leverage : 2);
                coin.setCreatedAt(now);
                coinRepository.save(coin);
            }
        }

        return productId;
    }

    // ----------------------------------------------------------------
    // 管理后台 - 切换状态
    // ----------------------------------------------------------------

    @Transactional(rollbackFor = Exception.class)
    public boolean toggleStatus(Long id) {
        ExperienceGiftProduct product = productDao.findOne(id);
        if (product == null) return false;
        product.setStatus(product.getStatus() == ExperienceGiftProductStatus.ENABLED
                ? ExperienceGiftProductStatus.DISABLED : ExperienceGiftProductStatus.ENABLED);
        product.setUpdatedAt(new Date());
        productDao.save(product);
        return true;
    }
}
