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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ycwl.basic.pricing.dto.OnePriceConfigFilterRequest;
import com.ycwl.basic.pricing.dto.OnePriceInfo;
import com.ycwl.basic.pricing.entity.PriceOnePriceConfig;
import com.ycwl.basic.pricing.mapper.PriceOnePriceConfigMapper;
import com.ycwl.basic.pricing.service.IOnePricePurchaseService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;

/**
 * 一口价购买服务实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OnePricePurchaseServiceImpl implements IOnePricePurchaseService {
    
    private final PriceOnePriceConfigMapper onePriceConfigMapper;
    
    @Override
    public boolean isOnePriceApplicable(Long scenicId) {
        PriceOnePriceConfig config = findConfigByScenic(scenicId);
        return config != null;
    }
    
    @Override
    public OnePriceInfo getOnePriceInfo(Long scenicId, BigDecimal currentAmount) {
        PriceOnePriceConfig config = findConfigByScenic(scenicId);
        
        if (config == null) {
            return null;
        }
        
        OnePriceInfo info = new OnePriceInfo();
        info.setConfigId(config.getId());
        info.setConfigName(config.getConfigName());
        info.setScenicId(scenicId);
        info.setOnePrice(config.getOnePrice());
        info.setOriginalPrice(config.getOriginalPrice());
        info.setDescription(config.getDescription());
        info.setCanUseCoupon(config.getCanUseCoupon());
        info.setCanUseVoucher(config.getCanUseVoucher());
        
        // 计算实际优惠金额
        if (currentAmount != null && config.getOnePrice().compareTo(currentAmount) < 0) {
            BigDecimal discountAmount = currentAmount.subtract(config.getOnePrice());
            info.setActualDiscountAmount(discountAmount);
        } else {
            info.setActualDiscountAmount(BigDecimal.ZERO);
        }
        
        return info;
    }
    
    @Override
    public List<PriceOnePriceConfig> getActiveConfigs() {
        return onePriceConfigMapper.selectActiveConfigs();
    }
    
    @Override
    public List<PriceOnePriceConfig> getActiveConfigsByScenic(Long scenicId) {
        return onePriceConfigMapper.selectConfigsByScenic(scenicId);
    }
    
    @Override
    public PriceOnePriceConfig getActiveConfigByScenic(Long scenicId) {
        return onePriceConfigMapper.selectConfigByScenic(scenicId);
    }
    
    // ==================== 管理端接口实现 ====================
    
    @Override
    public Long createConfig(PriceOnePriceConfig config) {
        try {
            // 设置默认值
            if (config.getIsActive() == null) {
                config.setIsActive(true);
            }
            if (config.getCanUseCoupon() == null) {
                config.setCanUseCoupon(true);
            }
            if (config.getCanUseVoucher() == null) {
                config.setCanUseVoucher(true);
            }
            if (config.getDeleted() == null) {
                config.setDeleted(0);
            }
            
            int result = onePriceConfigMapper.insertConfig(config);
            if (result > 0) {
                log.info("创建一口价配置成功: id={}, name={}", config.getId(), config.getConfigName());
                return config.getId();
            }
            return null;
        } catch (Exception e) {
            log.error("创建一口价配置失败", e);
            throw new RuntimeException("创建一口价配置失败: " + e.getMessage());
        }
    }
    
    @Override
    public boolean updateConfig(PriceOnePriceConfig config) {
        try {
            int result = onePriceConfigMapper.updateConfig(config);
            if (result > 0) {
                log.info("更新一口价配置成功: id={}", config.getId());
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("更新一口价配置失败: id={}", config.getId(), e);
            throw new RuntimeException("更新一口价配置失败: " + e.getMessage());
        }
    }
    
    @Override
    public boolean deleteConfig(Long id) {
        try {
            int result = onePriceConfigMapper.deleteConfig(id);
            if (result > 0) {
                log.info("删除一口价配置成功: id={}", id);
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("删除一口价配置失败: id={}", id, e);
            throw new RuntimeException("删除一口价配置失败: " + e.getMessage());
        }
    }
    
    @Override
    public boolean updateConfigStatus(Long id, Boolean isActive) {
        try {
            int result = onePriceConfigMapper.updateConfigStatus(id, isActive);
            if (result > 0) {
                log.info("更新一口价配置状态成功: id={}, isActive={}", id, isActive);
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("更新一口价配置状态失败: id={}", id, e);
            throw new RuntimeException("更新一口价配置状态失败: " + e.getMessage());
        }
    }
    
    @Override
    public PriceOnePriceConfig getConfigById(Long id) {
        return onePriceConfigMapper.selectById(id);
    }
    
    @Override
    public PageInfo<PriceOnePriceConfig> pageConfigs(OnePriceConfigFilterRequest request) {
        // 开启分页
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        
        // 构建查询条件
        QueryWrapper<PriceOnePriceConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0); // 未删除的记录
        
        // 添加筛选条件
        if (request.getScenicId() != null) {
            queryWrapper.eq("scenic_id", request.getScenicId());
        }
        if (StringUtils.hasText(request.getConfigName())) {
            queryWrapper.like("config_name", request.getConfigName()); // 模糊查询
        }
        if (request.getIsActive() != null) {
            queryWrapper.eq("is_active", request.getIsActive());
        }
        
        // 按创建时间降序排列
        queryWrapper.orderByDesc("create_time");
        
        // 执行查询
        List<PriceOnePriceConfig> list = onePriceConfigMapper.selectList(queryWrapper);
        
        // 返回分页结果
        return new PageInfo<>(list);
    }
    
    @Override
    public List<PriceOnePriceConfig> getAllConfigsForAdmin() {
        return onePriceConfigMapper.selectAllConfigsForAdmin();
    }
    
    // ==================== 私有方法 ====================
    
    /**
     * 根据景区查找配置
     */
    private PriceOnePriceConfig findConfigByScenic(Long scenicId) {
        if (scenicId == null) {
            return null;
        }
        
        // 查询匹配的配置
        PriceOnePriceConfig config = onePriceConfigMapper.selectConfigByScenic(scenicId);
        
        if (config == null) {
            return null;
        }
        
        // 检查时间有效性
        if (!config.isTimeValid()) {
            return null;
        }
        
        // 检查景区匹配性
        if (!config.isScenicMatch(scenicId)) {
            return null;
        }
        
        return config;
    }
}