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.enums.ErrorCode;
import com.reading.platform.common.exception.BusinessException;
import com.reading.platform.entity.ProductBundle;
import com.reading.platform.mapper.ProductBundleMapper;
import com.reading.platform.service.ProductBundleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 产品套餐服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ProductBundleServiceImpl extends ServiceImpl<ProductBundleMapper, ProductBundle> implements ProductBundleService {

    private final ProductBundleMapper productBundleMapper;

    @Override
    public Page<ProductBundle> getBundlePage(int pageNum, int pageSize, String keyword, String status) {
        log.debug("查询套餐分页，页码：{}，每页大小：{}，关键词：{}，状态：{}", pageNum, pageSize, keyword, status);

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

        if (keyword != null && !keyword.isEmpty()) {
            wrapper.like(ProductBundle::getName, keyword);
        }
        if (status != null && !status.isEmpty()) {
            wrapper.eq(ProductBundle::getStatus, status);
        }
        wrapper.orderByDesc(ProductBundle::getCreatedAt);

        Page<ProductBundle> result = productBundleMapper.selectPage(page, wrapper);
        log.info("查询套餐分页成功，共{}条", result.getTotal());
        return result;
    }

    @Override
    public ProductBundle getBundleById(String id) {
        log.debug("查询套餐，ID: {}", id);

        ProductBundle bundle = productBundleMapper.selectById(id);
        if (bundle == null) {
            log.warn("套餐不存在，ID: {}", id);
            throw new BusinessException(ErrorCode.DATA_NOT_FOUND, "套餐不存在");
        }
        log.info("查询套餐成功，名称：{}", bundle.getName());
        return bundle;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ProductBundle createBundle(ProductBundle bundle) {
        log.info("开始创建套餐，名称：{}", bundle.getName());

        productBundleMapper.insert(bundle);
        log.info("套餐创建成功，ID: {}", bundle.getId());
        return bundle;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ProductBundle updateBundle(String id, ProductBundle bundle) {
        log.info("开始更新套餐，ID: {}", id);

        ProductBundle existing = getBundleById(id);
        bundle.setId(id);
        productBundleMapper.updateById(bundle);

        log.info("套餐更新成功，ID: {}", id);
        return productBundleMapper.selectById(id);
    }

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

        getBundleById(id);
        productBundleMapper.deleteById(id);

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitBundle(String id) {
        log.info("开始提交套餐审核，ID: {}", id);

        ProductBundle bundle = getBundleById(id);
        bundle.setStatus("PENDING_REVIEW");
        productBundleMapper.updateById(bundle);

        log.info("套餐提交审核成功，ID: {}", id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void reviewBundle(String id, boolean approved, String comment) {
        log.info("开始审核套餐，ID: {}, 结果：{}", id, approved ? "通过" : "拒绝");

        ProductBundle bundle = getBundleById(id);
        bundle.setStatus(approved ? "APPROVED" : "REJECTED");
        productBundleMapper.updateById(bundle);

        log.info("套餐审核成功，ID: {}, 结果：{}", id, approved ? "通过" : "拒绝");
    }

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

        ProductBundle bundle = getBundleById(id);
        bundle.setStatus("PUBLISHED");
        bundle.setPublishedAt(LocalDateTime.now());
        productBundleMapper.updateById(bundle);

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

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

        ProductBundle bundle = getBundleById(id);
        bundle.setStatus("OFFLINE");
        productBundleMapper.updateById(bundle);

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

    @Override
    public Page<ProductBundle> getSystemBundles(int pageNum, int pageSize, String gradeLevel) {
        log.debug("查询系统套餐列表，页码：{}，每页大小：{}，年级：{}", pageNum, pageSize, gradeLevel);

        Page<ProductBundle> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<ProductBundle> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductBundle::getIsSystem, 1);
        wrapper.eq(ProductBundle::getStatus, "PUBLISHED");

        if (gradeLevel != null && !gradeLevel.isEmpty()) {
            wrapper.like(ProductBundle::getGradeLevels, gradeLevel);
        }
        wrapper.orderByDesc(ProductBundle::getCreatedAt);

        Page<ProductBundle> result = productBundleMapper.selectPage(page, wrapper);
        log.info("查询系统套餐列表成功，共{}条", result.getTotal());
        return result;
    }
}
