package com.ycwl.basic.pricing.service.impl;

import com.ycwl.basic.pricing.entity.*;
import com.ycwl.basic.pricing.mapper.*;
import com.ycwl.basic.pricing.service.IPricingManagementService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;

/**
 * 价格管理服务实现（用于配置管理，手动处理时间字段）
 */
@Slf4j
@Service("pricingManagementServiceImpl")
@RequiredArgsConstructor
public class PricingManagementServiceImpl implements IPricingManagementService {
    
    private final PriceProductConfigMapper productConfigMapper;
    private final PriceTierConfigMapper tierConfigMapper;
    private final PriceCouponConfigMapper couponConfigMapper;
    private final PriceCouponClaimRecordMapper couponClaimRecordMapper;
    private final PriceBundleConfigMapper bundleConfigMapper;
    
    @Override
    @Transactional
    public Long createProductConfig(PriceProductConfig config) {
        // 校验：如果是default配置，确保该商品类型只能有一个default配置
        if ("default".equals(config.getProductId())) {
            int existingCount = productConfigMapper.countDefaultConfigsByProductType(config.getProductType());
            if (existingCount > 0) {
                throw new IllegalArgumentException("商品类型 " + config.getProductType() + " 的default配置已存在，每种商品类型只能有一个default配置");
            }
        }
        
        config.setCreateTime(new Date());
        config.setUpdateTime(new Date());
        productConfigMapper.insertProductConfig(config);
        return config.getId();
    }
    
    @Override
    @Transactional
    public boolean updateProductConfig(PriceProductConfig config) {
        config.setUpdateTime(new Date());
        return productConfigMapper.updateProductConfig(config) > 0;
    }
    
    @Override
    @Transactional
    public Long createTierConfig(PriceTierConfig config) {
        // 校验：如果是default配置，检查是否可以创建
        if ("default".equals(config.getProductId())) {
            // 对于阶梯配置，可以有多个default配置（不同数量区间），不需要限制
            log.info("创建default阶梯配置: productType={}, quantity range: {}-{}", 
                    config.getProductType(), config.getMinQuantity(), config.getMaxQuantity());
        }
        
        config.setCreateTime(new Date());
        config.setUpdateTime(new Date());
        tierConfigMapper.insertTierConfig(config);
        return config.getId();
    }
    
    @Override
    @Transactional
    public boolean updateTierConfig(PriceTierConfig config) {
        config.setUpdateTime(new Date());
        return tierConfigMapper.updateTierConfig(config) > 0;
    }
    
    @Override
    @Transactional
    public Long createCouponConfig(PriceCouponConfig config) {
        config.setCreateTime(new Date());
        config.setUpdateTime(new Date());
        couponConfigMapper.insertCoupon(config);
        return config.getId();
    }
    
    @Override
    @Transactional
    public boolean updateCouponConfig(PriceCouponConfig config) {
        config.setUpdateTime(new Date());
        return couponConfigMapper.updateCoupon(config) > 0;
    }
    
    @Override
    @Transactional
    public Long createCouponClaimRecord(PriceCouponClaimRecord record) {
        record.setClaimTime(new Date());
        record.setCreateTime(new Date());
        record.setUpdateTime(new Date());
        couponClaimRecordMapper.insertClaimRecord(record);
        return record.getId();
    }
    
    @Override
    @Transactional
    public boolean updateCouponClaimRecord(PriceCouponClaimRecord record) {
        record.setUpdateTime(new Date());
        return couponClaimRecordMapper.updateClaimRecord(record) > 0;
    }
    
    @Override
    @Transactional
    public Long createBundleConfig(PriceBundleConfig config) {
        config.setCreateTime(new Date());
        config.setUpdateTime(new Date());
        bundleConfigMapper.insertBundleConfig(config);
        return config.getId();
    }
    
    @Override
    @Transactional
    public boolean updateBundleConfig(PriceBundleConfig config) {
        config.setUpdateTime(new Date());
        return bundleConfigMapper.updateBundleConfig(config) > 0;
    }
    
    // ==================== 状态管理 ====================
    
    @Override
    @Transactional
    public boolean updateProductConfigStatus(Long id, Boolean isActive) {
        log.info("更新商品配置状态: id={}, isActive={}", id, isActive);
        return productConfigMapper.updateProductConfigStatus(id, isActive) > 0;
    }
    
    @Override
    @Transactional
    public boolean updateTierConfigStatus(Long id, Boolean isActive) {
        log.info("更新阶梯配置状态: id={}, isActive={}", id, isActive);
        return tierConfigMapper.updateTierConfigStatus(id, isActive) > 0;
    }
    
    @Override
    @Transactional
    public boolean updateBundleConfigStatus(Long id, Boolean isActive) {
        log.info("更新一口价配置状态: id={}, isActive={}", id, isActive);
        return bundleConfigMapper.updateBundleConfigStatus(id, isActive) > 0;
    }
    
    // ==================== 删除操作 ====================
    
    @Override
    @Transactional
    public boolean deleteProductConfig(Long id) {
        log.info("删除商品配置: id={}", id);
        return productConfigMapper.deleteById(id) > 0;
    }
    
    @Override
    @Transactional
    public boolean deleteTierConfig(Long id) {
        log.info("删除阶梯配置: id={}", id);
        return tierConfigMapper.deleteById(id) > 0;
    }
    
    @Override
    @Transactional
    public boolean deleteBundleConfig(Long id) {
        log.info("删除一口价配置: id={}", id);
        return bundleConfigMapper.deleteById(id) > 0;
    }
    
    // ==================== 快速设置价格 ====================
    
    @Override
    @Transactional
    public Long quickSetupProductPrice(String productType, String productId, String scenicId, 
                                     String productName, BigDecimal basePrice, 
                                     BigDecimal originalPrice, String unit) {
        log.info("快速设置商品价格: productType={}, productId={}, scenicId={}, basePrice={}", 
                productType, productId, scenicId, basePrice);
        
        // 查询是否已存在配置
        PriceProductConfig existingConfig = productConfigMapper.selectByProductTypeAndId(productType, productId);
        
        if (existingConfig != null) {
            // 存在则更新
            existingConfig.setScenicId(scenicId);
            existingConfig.setProductName(productName);
            existingConfig.setBasePrice(basePrice);
            existingConfig.setOriginalPrice(originalPrice);
            existingConfig.setUnit(unit != null ? unit : "元");
            existingConfig.setUpdateTime(new Date());
            
            productConfigMapper.updateProductConfig(existingConfig);
            log.info("更新商品价格配置: id={}", existingConfig.getId());
            return existingConfig.getId();
        } else {
            // 不存在则新增
            PriceProductConfig newConfig = new PriceProductConfig();
            newConfig.setProductType(productType);
            newConfig.setProductId(productId);
            newConfig.setScenicId(scenicId);
            newConfig.setProductName(productName);
            newConfig.setBasePrice(basePrice);
            newConfig.setOriginalPrice(originalPrice);
            newConfig.setUnit(unit != null ? unit : "元");
            newConfig.setIsActive(true);
            newConfig.setCreateTime(new Date());
            newConfig.setUpdateTime(new Date());
            
            productConfigMapper.insertProductConfig(newConfig);
            log.info("创建新商品价格配置: id={}", newConfig.getId());
            return newConfig.getId();
        }
    }
}