package com.reading.platform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.reading.platform.common.exception.BusinessException;
import com.reading.platform.entity.TenantProductBundle;
import com.reading.platform.mapper.TenantProductBundleMapper;
import com.reading.platform.service.TenantProductBundleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 学校套餐购买记录服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TenantProductBundleServiceImpl extends ServiceImpl<TenantProductBundleMapper, TenantProductBundle> implements TenantProductBundleService {

    private final TenantProductBundleMapper tenantProductBundleMapper;

    @Override
    public Page<TenantProductBundle> getTenantBundlePage(int pageNum, int pageSize, String tenantId, String status) {
        log.debug("查询学校套餐购买记录分页，页码：{}，每页大小：{}，租户 ID: {}, 状态：{}", pageNum, pageSize, tenantId, status);

        Page<TenantProductBundle> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<TenantProductBundle> wrapper = new LambdaQueryWrapper<>();

        if (tenantId != null && !tenantId.isEmpty()) {
            wrapper.eq(TenantProductBundle::getTenantId, tenantId);
        }
        if (status != null && !status.isEmpty()) {
            wrapper.eq(TenantProductBundle::getStatus, status);
        }
        wrapper.orderByDesc(TenantProductBundle::getCreatedAt);

        Page<TenantProductBundle> result = tenantProductBundleMapper.selectPage(page, wrapper);
        log.info("查询学校套餐购买记录分页成功，共{}条", result.getTotal());
        return result;
    }

    @Override
    public TenantProductBundle getTenantBundleById(String id) {
        log.debug("查询学校套餐购买记录，ID: {}", id);

        TenantProductBundle record = tenantProductBundleMapper.selectById(id);
        if (record == null) {
            log.warn("学校套餐购买记录不存在，ID: {}", id);
            throw new BusinessException("学校套餐购买记录不存在");
        }
        log.info("查询学校套餐购买记录成功，ID: {}", id);
        return record;
    }

    @Override
    public List<TenantProductBundle> getTenantBundlesByTenantId(String tenantId) {
        log.debug("查询学校的套餐列表，租户 ID: {}", tenantId);

        LambdaQueryWrapper<TenantProductBundle> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TenantProductBundle::getTenantId, tenantId);
        wrapper.orderByDesc(TenantProductBundle::getPurchaseTime);

        List<TenantProductBundle> result = tenantProductBundleMapper.selectList(wrapper);
        log.info("查询学校的套餐列表成功，租户 ID: {}, 数量：{}", tenantId, result.size());
        return result;
    }

    @Override
    public TenantProductBundle getActiveTenantBundle(String tenantId) {
        log.debug("查询学校当前有效的套餐，租户 ID: {}", tenantId);

        LambdaQueryWrapper<TenantProductBundle> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TenantProductBundle::getTenantId, tenantId);
        wrapper.eq(TenantProductBundle::getStatus, "ACTIVE");
        wrapper.le(TenantProductBundle::getEndDate, LocalDateTime.now());
        wrapper.orderByDesc(TenantProductBundle::getPurchaseTime);

        TenantProductBundle result = tenantProductBundleMapper.selectOne(wrapper);
        if (result != null) {
            log.info("查询学校当前有效的套餐成功，租户 ID: {}, 套餐 ID: {}", tenantId, result.getProductBundleId());
        } else {
            log.info("学校当前无有效套餐，租户 ID: {}", tenantId);
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TenantProductBundle createTenantBundle(TenantProductBundle record) {
        log.info("开始创建学校套餐购买记录，租户 ID: {}, 套餐 ID: {}", record.getTenantId(), record.getProductBundleId());

        tenantProductBundleMapper.insert(record);
        log.info("学校套餐购买记录创建成功，ID: {}", record.getId());
        return record;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TenantProductBundle updateTenantBundle(String id, TenantProductBundle record) {
        log.info("开始更新学校套餐购买记录，ID: {}", id);

        TenantProductBundle existing = getTenantBundleById(id);
        record.setId(id);
        tenantProductBundleMapper.updateById(record);

        log.info("学校套餐购买记录更新成功，ID: {}", id);
        return tenantProductBundleMapper.selectById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void activateBundle(String id) {
        log.info("开始激活套餐，ID: {}", id);

        TenantProductBundle record = getTenantBundleById(id);
        record.setStatus("ACTIVE");
        tenantProductBundleMapper.updateById(record);

        log.info("套餐激活成功，ID: {}", id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void expireBundle(String id) {
        log.info("开始过期套餐，ID: {}", id);

        TenantProductBundle record = getTenantBundleById(id);
        record.setStatus("EXPIRED");
        tenantProductBundleMapper.updateById(record);

        log.info("套餐过期成功，ID: {}", id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void suspendBundle(String id) {
        log.info("开始暂停套餐，ID: {}", id);

        TenantProductBundle record = getTenantBundleById(id);
        record.setStatus("SUSPENDED");
        tenantProductBundleMapper.updateById(record);

        log.info("套餐暂停成功，ID: {}", id);
    }
}
