package com.erp.tenant.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.common.core.exception.BusinessException;
import com.erp.common.core.model.PageResponse;
import com.erp.tenant.entity.PricePlan;
import com.erp.tenant.repository.PricePlanRepository;
import com.erp.tenant.service.PricePlanService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 价格方案服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PricePlanServiceImpl implements PricePlanService {
    
    private final PricePlanRepository pricePlanRepository;
    
    @Override
    public PageResponse<PricePlan> listPricePlans(String periodType, Boolean isActive, Integer page, Integer pageSize) {
        Page<PricePlan> pageParam = new Page<>(page, pageSize);
        
        LambdaQueryWrapper<PricePlan> queryWrapper = new LambdaQueryWrapper<>();
        
        if (StringUtils.hasText(periodType)) {
            queryWrapper.eq(PricePlan::getPeriodType, periodType);
        }
        
        if (isActive != null) {
            queryWrapper.eq(PricePlan::getIsActive, isActive);
        }
        
        queryWrapper.orderByAsc(PricePlan::getSortOrder).orderByAsc(PricePlan::getId);
        
        IPage<PricePlan> pageResult = pricePlanRepository.findPage(pageParam);
        
        return PageResponse.of(pageResult.getRecords(), pageResult.getTotal(), (int) pageResult.getCurrent(), (int) pageResult.getSize());
    }
    
    @Override
    public PricePlan getPricePlanById(Long id) {
        PricePlan pricePlan = pricePlanRepository.findById(id);
        if (pricePlan == null) {
            throw new BusinessException("价格方案不存在");
        }
        return pricePlan;
    }
    
    @Override
    @Transactional
    public PricePlan createPricePlan(PricePlan pricePlan) {
        // 检查名称是否已存在
        if (pricePlanRepository.existsByName(pricePlan.getName())) {
            throw new BusinessException("价格方案名称已存在");
        }
        
        // 如果是默认方案，先清除其他默认标识
        if (Boolean.TRUE.equals(pricePlan.getIsDefault())) {
            pricePlanRepository.clearDefaultFlag();
        }
        
        pricePlanRepository.insert(pricePlan);
        log.info("创建价格方案成功: {}", pricePlan.getName());
        return pricePlan;
    }
    
    @Override
    @Transactional
    public PricePlan updatePricePlan(Long id, PricePlan pricePlan) {
        PricePlan existingPlan = getPricePlanById(id);
        
        // 检查名称是否已存在（排除自身）
        if (pricePlanRepository.existsByNameExclude(pricePlan.getName(), id)) {
            throw new BusinessException("价格方案名称已存在");
        }
        
        // 如果设置为默认方案，先清除其他默认标识
        if (Boolean.TRUE.equals(pricePlan.getIsDefault()) && !Boolean.TRUE.equals(existingPlan.getIsDefault())) {
            pricePlanRepository.clearDefaultFlag();
        }
        
        pricePlan.setId(id);
        pricePlanRepository.updateById(pricePlan);
        log.info("更新价格方案成功: {}", pricePlan.getName());
        return pricePlan;
    }
    
    @Override
    @Transactional
    public void deletePricePlan(Long id) {
        PricePlan pricePlan = getPricePlanById(id);
        
        // 不能删除默认方案
        if (Boolean.TRUE.equals(pricePlan.getIsDefault())) {
            throw new BusinessException("不能删除默认价格方案");
        }
        
        pricePlanRepository.deleteById(id);
        log.info("删除价格方案成功: {}", pricePlan.getName());
    }
    
    @Override
    @Transactional
    public boolean togglePricePlanStatus(Long id) {
        PricePlan pricePlan = getPricePlanById(id);
        
        // 不能禁用默认方案
        if (Boolean.TRUE.equals(pricePlan.getIsDefault()) && Boolean.TRUE.equals(pricePlan.getIsActive())) {
            throw new BusinessException("不能禁用默认价格方案");
        }
        
        int result = pricePlanRepository.toggleStatus(id);
        log.info("切换价格方案状态: {} -> {}", pricePlan.getName(), result > 0 ? "启用" : "禁用");
        return result > 0;
    }
    
    @Override
    @Transactional
    public void setDefaultPricePlan(Long id) {
        PricePlan pricePlan = getPricePlanById(id);
        
        // 不能将禁用的方案设为默认
        if (!Boolean.TRUE.equals(pricePlan.getIsActive())) {
            throw new BusinessException("不能将禁用的方案设为默认");
        }
        
        pricePlanRepository.clearDefaultFlag();
        pricePlanRepository.setDefault(id);
        log.info("设置默认价格方案: {}", pricePlan.getName());
    }
    
    @Override
    public List<PricePlan> getActivePricePlans() {
        return pricePlanRepository.findActive();
    }
}
