package shop.alien.store.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.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import shop.alien.entity.result.R;
import shop.alien.entity.store.StoreBanner;
import shop.alien.entity.store.dto.StoreBannerDto;
import shop.alien.entity.store.vo.StoreBannerVo;
import shop.alien.mapper.StoreBannerMapper;
import shop.alien.store.service.StoreBannerService;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Banner表 服务实现类
 *
 * @author gpt
 * @since 2025-12-16
 */
@Service
public class StoreBannerServiceImpl extends ServiceImpl<StoreBannerMapper, StoreBanner> implements StoreBannerService {

//    @Transactional
//    @Override
//    public R<String> saveBanner(StoreBannerDto storeBannerDto) {
//        StoreBanner storeBanner = new StoreBanner();
//        BeanUtils.copyProperties(storeBannerDto, storeBanner);
//        boolean update = storeBanner.getId() != null;
//        boolean result = this.saveOrUpdate(storeBanner);
//        if (result) {
//            return R.success(update ? "修改成功" : "新增成功");
//        }
//        return R.fail(update ? "修改失败" : "新增失败");
//    }


    @Transactional
    @Override
    public R<String> saveBanner(StoreBannerDto storeBannerDto) {
        // 先检查 moduleName 是否已存在
        LambdaQueryWrapper<StoreBanner> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StoreBanner::getModuleName, storeBannerDto.getModuleName());

        // 如果是更新操作，需要排除当前记录本身
        if (storeBannerDto.getId() != null) {
            queryWrapper.ne(StoreBanner::getId, storeBannerDto.getId());
        }

//        long count = this.count(queryWrapper);
//        if (count > 0) {
//            return R.fail("该模块名称已存在，不能重复添加或修改");
//        }

        StoreBanner storeBanner = new StoreBanner();
        BeanUtils.copyProperties(storeBannerDto, storeBanner);
        boolean update = storeBanner.getId() != null;
        boolean result = this.saveOrUpdate(storeBanner);
        if (result) {
            return R.success(update ? "修改成功" : "新增成功");
        }
        return R.fail(update ? "修改失败" : "新增失败");
    }

    @Override
    public IPage<StoreBannerVo> pageList(String moduleCode, String moduleName, String status, Integer pageNum, Integer pageSize) {
        int current = pageNum == null || pageNum <= 0 ? 1 : pageNum;
        int size = pageSize == null || pageSize <= 0 ? 10 : pageSize;
        Page<StoreBanner> page = new Page<>(current, size);
        LambdaQueryWrapper<StoreBanner> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(moduleCode), StoreBanner::getModuleCode, moduleCode);
        wrapper.like(StringUtils.isNotBlank(moduleName), StoreBanner::getModuleName, moduleName);
        wrapper.eq(StringUtils.isNotBlank(status), StoreBanner::getStatus, status);
        wrapper.orderByAsc(StoreBanner::getSort).orderByDesc(StoreBanner::getCreatedTime);
        return this.page(page, wrapper).convert(this::toVo);
    }

    @Override
    public List<StoreBannerVo> getBannerByAISearch(List<String> keyword) {
        // 去重：过滤空白并按关键词去重
        List<String> distinctKeywords = (keyword == null || keyword.isEmpty())
                ? Collections.emptyList()
                : keyword.stream().filter(StringUtils::isNotBlank).distinct().collect(Collectors.toList());

        LambdaQueryWrapper<StoreBanner> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StoreBanner::getStatus, "1")
                .orderByAsc(StoreBanner::getSort)
                .orderByDesc(StoreBanner::getCreatedTime);
        // 无关键词时查全部 banner，有关键词时按 module_name 过滤
        if (distinctKeywords != null && !distinctKeywords.isEmpty()) {
            wrapper.in(StoreBanner::getModuleName, distinctKeywords);
        }
        return this.list(wrapper).stream().map(this::toVo).collect(Collectors.toList());
    }

    private StoreBannerVo toVo(StoreBanner banner) {
        StoreBannerVo vo = new StoreBannerVo();
        BeanUtils.copyProperties(banner, vo);
        if (StringUtils.isNotBlank(banner.getStatus())) {
            vo.setStatusText("1".equals(banner.getStatus()) ? "启用" : "禁用");
        }
        return vo;
    }
}

