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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ycwl.basic.pricing.enums.ProductCategory;
import com.ycwl.basic.pricing.enums.ProductType;
import com.ycwl.basic.product.capability.DuplicateCheckStrategy;
import com.ycwl.basic.product.capability.PricingMode;
import com.ycwl.basic.product.capability.ProductTypeCapability;
import com.ycwl.basic.product.dto.ProductTypeCapabilityRequest;
import com.ycwl.basic.product.mapper.ProductTypeCapabilityMapper;
import com.ycwl.basic.product.service.IProductTypeCapabilityManagementService;
import com.ycwl.basic.product.service.IProductTypeCapabilityService;
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.ArrayList;
import java.util.List;

/**
 * 商品类型能力配置管理服务实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ProductTypeCapabilityManagementServiceImpl implements IProductTypeCapabilityManagementService {

    private final ProductTypeCapabilityMapper mapper;
    private final IProductTypeCapabilityService capabilityService;

    @Override
    public Page<ProductTypeCapability> queryByPage(int pageNum, int pageSize,
                                                   String productType, String category, Boolean isActive) {
        Page<ProductTypeCapability> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<ProductTypeCapability> queryWrapper = new LambdaQueryWrapper<>();

        if (productType != null && !productType.trim().isEmpty()) {
            queryWrapper.like(ProductTypeCapability::getProductType, productType);
        }

        if (category != null && !category.trim().isEmpty()) {
            queryWrapper.eq(ProductTypeCapability::getCategory, category);
        }

        if (isActive != null) {
            queryWrapper.eq(ProductTypeCapability::getIsActive, isActive);
        }

        queryWrapper.orderByDesc(ProductTypeCapability::getCreatedAt);

        return mapper.selectPage(page, queryWrapper);
    }

    @Override
    public List<ProductTypeCapability> queryAll(boolean includeInactive) {
        LambdaQueryWrapper<ProductTypeCapability> queryWrapper = new LambdaQueryWrapper<>();

        if (!includeInactive) {
            queryWrapper.eq(ProductTypeCapability::getIsActive, true);
        }

        queryWrapper.orderBy(true, true, ProductTypeCapability::getCategory, ProductTypeCapability::getProductType);

        return mapper.selectList(queryWrapper);
    }

    @Override
    public List<ProductTypeCapability> queryByCategory(String category) {
        if (category == null || category.trim().isEmpty()) {
            return new ArrayList<>();
        }

        LambdaQueryWrapper<ProductTypeCapability> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProductTypeCapability::getCategory, category);
        queryWrapper.eq(ProductTypeCapability::getIsActive, true);
        queryWrapper.orderByAsc(ProductTypeCapability::getProductType);

        return mapper.selectList(queryWrapper);
    }

    @Override
    public ProductTypeCapability getById(Long id) {
        if (id == null) {
            throw new IllegalArgumentException("配置ID不能为空");
        }

        ProductTypeCapability capability = mapper.selectById(id);
        if (capability == null) {
            throw new IllegalArgumentException("配置不存在: " + id);
        }

        return capability;
    }

    @Override
    public ProductTypeCapability getByProductType(String productType) {
        if (productType == null || productType.trim().isEmpty()) {
            throw new IllegalArgumentException("商品类型代码不能为空");
        }

        return mapper.selectByProductType(productType);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ProductTypeCapability create(ProductTypeCapabilityRequest request) {
        validateRequest(request, true);

        // 检查商品类型代码是否已存在
        ProductTypeCapability existing = mapper.selectByProductType(request.getProductType());
        if (existing != null) {
            throw new IllegalArgumentException("商品类型代码已存在: " + request.getProductType());
        }

        ProductTypeCapability capability = convertToEntity(request);
        capability.setCreatedAt(LocalDateTime.now());
        capability.setUpdatedAt(LocalDateTime.now());

        mapper.insert(capability);

        // 刷新缓存
        capabilityService.refreshCache(capability.getProductType());

        log.info("创建商品类型能力配置成功: {}", capability.getProductType());
        return capability;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ProductTypeCapability update(Long id, ProductTypeCapabilityRequest request) {
        validateRequest(request, false);

        ProductTypeCapability capability = getById(id);

        // 如果修改了商品类型代码，检查新代码是否已被使用
        if (request.getProductType() != null &&
            !request.getProductType().equals(capability.getProductType())) {
            ProductTypeCapability existing = mapper.selectByProductType(request.getProductType());
            if (existing != null && !existing.getId().equals(id)) {
                throw new IllegalArgumentException("商品类型代码已被使用: " + request.getProductType());
            }
        }

        String oldProductType = capability.getProductType();
        updateEntityFromRequest(capability, request);
        capability.setUpdatedAt(LocalDateTime.now());

        mapper.updateById(capability);

        // 刷新缓存（如果商品类型代码改变了，需要刷新两个缓存）
        capabilityService.refreshCache(capability.getProductType());
        if (!oldProductType.equals(capability.getProductType())) {
            capabilityService.refreshCache(oldProductType);
        }

        log.info("更新商品类型能力配置成功: {}", capability.getProductType());
        return capability;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(Long id) {
        ProductTypeCapability capability = getById(id);

        mapper.deleteById(id);

        // 刷新缓存
        capabilityService.refreshCache(capability.getProductType());

        log.info("删除商品类型能力配置成功: {}", capability.getProductType());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateStatus(Long id, Boolean isActive) {
        if (isActive == null) {
            throw new IllegalArgumentException("状态不能为空");
        }

        ProductTypeCapability capability = getById(id);
        capability.setIsActive(isActive);
        capability.setUpdatedAt(LocalDateTime.now());

        mapper.updateById(capability);

        // 刷新缓存
        capabilityService.refreshCache(capability.getProductType());

        log.info("更新商品类型能力配置状态成功: {}, isActive={}", capability.getProductType(), isActive);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int initializeDefaultCapabilities() {
        int count = 0;

        for (ProductType productType : ProductType.values()) {
            // 检查是否已存在配置
            ProductTypeCapability existing = mapper.selectByProductType(productType.getCode());
            if (existing != null) {
                log.debug("商品类型 {} 已存在配置，跳过初始化", productType.getCode());
                continue;
            }

            // 创建默认配置
            ProductTypeCapability capability = createDefaultCapability(productType);
            mapper.insert(capability);
            count++;

            log.info("初始化商品类型能力配置: {}", productType.getCode());
        }

        // 刷新所有缓存
        capabilityService.refreshCache();

        log.info("商品类型能力配置批量初始化完成，共初始化 {} 个配置", count);
        return count;
    }

    /**
     * 创建默认配置
     */
    private ProductTypeCapability createDefaultCapability(ProductType productType) {
        ProductTypeCapability capability = new ProductTypeCapability();
        capability.setProductType(productType.getCode());
        capability.setDisplayName(productType.getDescription());
        capability.setCategory(productType.getCategoryCode());

        // 根据分类设置默认的定价模式和去重策略
        if (ProductCategory.PRINT == productType.getCategory()) {
            // 打印类:基于数量定价,允许重复购买
            capability.setPricingMode(PricingMode.QUANTITY_BASED.getCode());
            capability.setSupportsTierPricing(true);
            capability.setAllowDuplicatePurchase(true);
            capability.setDuplicateCheckStrategy(DuplicateCheckStrategy.NO_CHECK.getCode());
        } else if (ProductCategory.PHOTO == productType.getCategory()
                || ProductCategory.VIDEO == productType.getCategory()
                || ProductCategory.VLOG == productType.getCategory()) {
            // 照片类、视频类、Vlog类:固定价格,检查唯一资源
            capability.setPricingMode(PricingMode.FIXED.getCode());
            capability.setSupportsTierPricing(false);
            capability.setAllowDuplicatePurchase(false);

            // 判断是套餐类还是独立资源类
            if (productType.getCode().endsWith("_SET")) {
                capability.setDuplicateCheckStrategy(DuplicateCheckStrategy.PARENT_RESOURCE.getCode());
            } else {
                capability.setDuplicateCheckStrategy(DuplicateCheckStrategy.UNIQUE_RESOURCE.getCode());
            }
        } else {
            // 其他类:默认不检查
            capability.setPricingMode(PricingMode.FIXED.getCode());
            capability.setSupportsTierPricing(false);
            capability.setAllowDuplicatePurchase(true);
            capability.setDuplicateCheckStrategy(DuplicateCheckStrategy.NO_CHECK.getCode());
        }

        // 优惠能力默认全部开启
        capability.setCanUseCoupon(true);
        capability.setCanUseVoucher(true);
        capability.setCanUseOnePrice(true);
        capability.setCanUseBundle(true);

        capability.setIsActive(true);
        capability.setCreatedAt(LocalDateTime.now());
        capability.setUpdatedAt(LocalDateTime.now());

        return capability;
    }

    /**
     * 验证请求参数
     */
    private void validateRequest(ProductTypeCapabilityRequest request, boolean isCreate) {
        if (request == null) {
            throw new IllegalArgumentException("请求参数不能为空");
        }

        if (isCreate || request.getProductType() != null) {
            if (request.getProductType() == null || request.getProductType().trim().isEmpty()) {
                throw new IllegalArgumentException("商品类型代码不能为空");
            }
        }

        if (request.getDisplayName() != null && request.getDisplayName().trim().isEmpty()) {
            throw new IllegalArgumentException("显示名称不能为空字符串");
        }

        // 验证枚举值有效性
        if (request.getPricingMode() != null) {
            try {
                PricingMode.fromCode(request.getPricingMode());
            } catch (IllegalArgumentException e) {
                throw new IllegalArgumentException("无效的定价模式: " + request.getPricingMode());
            }
        }

        if (request.getDuplicateCheckStrategy() != null) {
            try {
                DuplicateCheckStrategy.fromCode(request.getDuplicateCheckStrategy());
            } catch (IllegalArgumentException e) {
                throw new IllegalArgumentException("无效的重复检查策略: " + request.getDuplicateCheckStrategy());
            }
        }

        if (request.getCategory() != null) {
            try {
                ProductCategory.fromCode(request.getCategory());
            } catch (IllegalArgumentException e) {
                throw new IllegalArgumentException("无效的商品分类: " + request.getCategory());
            }
        }
    }

    /**
     * 将请求转换为实体
     */
    private ProductTypeCapability convertToEntity(ProductTypeCapabilityRequest request) {
        ProductTypeCapability capability = new ProductTypeCapability();
        updateEntityFromRequest(capability, request);
        return capability;
    }

    /**
     * 从请求更新实体
     */
    private void updateEntityFromRequest(ProductTypeCapability capability, ProductTypeCapabilityRequest request) {
        if (request.getProductType() != null) {
            capability.setProductType(request.getProductType());
        }
        if (request.getDisplayName() != null) {
            capability.setDisplayName(request.getDisplayName());
        }
        if (request.getCategory() != null) {
            capability.setCategory(request.getCategory());
        }
        if (request.getPricingMode() != null) {
            capability.setPricingMode(request.getPricingMode());
        }
        if (request.getSupportsTierPricing() != null) {
            capability.setSupportsTierPricing(request.getSupportsTierPricing());
        }
        if (request.getAllowDuplicatePurchase() != null) {
            capability.setAllowDuplicatePurchase(request.getAllowDuplicatePurchase());
        }
        if (request.getDuplicateCheckStrategy() != null) {
            capability.setDuplicateCheckStrategy(request.getDuplicateCheckStrategy());
        }
        if (request.getCanUseCoupon() != null) {
            capability.setCanUseCoupon(request.getCanUseCoupon());
        }
        if (request.getCanUseVoucher() != null) {
            capability.setCanUseVoucher(request.getCanUseVoucher());
        }
        if (request.getCanUseOnePrice() != null) {
            capability.setCanUseOnePrice(request.getCanUseOnePrice());
        }
        if (request.getCanUseBundle() != null) {
            capability.setCanUseBundle(request.getCanUseBundle());
        }
        if (request.getMetadata() != null) {
            capability.setMetadata(request.getMetadata());
        }
        if (request.getIsActive() != null) {
            capability.setIsActive(request.getIsActive());
        }
    }
}
