package com.ylx.banner.service.impl;

import cn.hutool.core.collection.CollectionUtil;
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.ylx.banner.domain.vo.BannerVO;
import com.ylx.common.exception.ServiceException;
import com.ylx.common.utils.uuid.IdUtils;
import com.ylx.banner.domain.Banner;
import com.ylx.giftCard.domain.GiftCard;
import com.ylx.giftCard.domain.vo.GiftCardVO;
import com.ylx.massage.domain.dto.TLbtStatusDTO;
import com.ylx.banner.mapper.BannerMapper;
import com.ylx.banner.service.BannerService;
import com.ylx.common.utils.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

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

/**
 * 轮播图 服务实现类
 */
@Service
public class BannerServiceImpl extends ServiceImpl<BannerMapper, Banner> implements BannerService {
    private static final int STATUS_HIDE = 0;
    private static final int STATUS_SHOW = 1;
    private static final long MAX_SHOW_COUNT = 5L;
    private static final long MIN_SHOW_COUNT = 1L;
    private static final int NOT_DELETE = 0;

    @Override
    public Boolean addOrUpdate(Banner lbt) {
        if (StringUtils.isBlank(lbt.getImgUrl())) {
            throw new ServiceException("图片不能为空");
        }
        if (lbt.getSort() == null) {
            throw new ServiceException("序号不能为空");
        }
        Integer i = lbt.getSort();
        LambdaQueryWrapper<Banner> query = new LambdaQueryWrapper<Banner>().eq(Banner::getSort, i);
        Banner one = getOne(query);
        if (StringUtils.isBlank(lbt.getId())) {
            //新增
            lbt.setId(IdUtils.simpleUUID());
            if (one != null) {
                batchLbt(i);
            }
        } else {
            //修改
            query.ne(Banner::getId, lbt.getId());
            if (getOne(query) != null) {
                batchLbt(i);
            }
        }
        return this.saveOrUpdate(lbt);
    }

    /**
     *
     * @param i
     */
    private void batchLbt(Integer i) {
        LambdaQueryWrapper<Banner> query1 = new LambdaQueryWrapper<Banner>().ge(Banner::getSort, i);
        List<Banner> lbts = list(query1);
        lbts.forEach(tLbt1 -> tLbt1.setSort(tLbt1.getSort() + 1));
        updateBatchById(lbts);
    }

    @Override
    public Boolean del(Banner banner) {
        if (banner == null) {
            throw new ServiceException("参数不能为空");
        }
        if (StringUtils.isBlank(banner.getId())) {
            throw new ServiceException("ID不能为空");
        }

        Banner exists = baseMapper.selectLbtById(banner.getId());
        if (exists == null) {
            throw new ServiceException("轮播图不存在");
        }
        if (Integer.valueOf(STATUS_SHOW).equals(exists.getStatus())) {
            throw new ServiceException("当前banner已显示，不可删除！");
        }

        boolean removed = this.removeById(banner.getId());
        if (!removed) {
            throw new ServiceException("轮播图删除失败");
        }
        return true;
    }

    @Override
    public Boolean updateStatus(TLbtStatusDTO dto) {
        if (dto == null) {
            throw new ServiceException("参数不能为空");
        }
        if (StringUtils.isBlank(dto.getId())) {
            throw new ServiceException("ID不能为空");
        }
        if (dto.getStatus() == null || (dto.getStatus() != STATUS_HIDE && dto.getStatus() != STATUS_SHOW)) {
            throw new ServiceException("显示状态值不正确");
        }

        Banner exists = baseMapper.selectLbtById(dto.getId());
        if (exists == null) {
            throw new ServiceException("轮播图不存在");
        }
        if (dto.getStatus().equals(exists.getStatus())) {
            return true;
        }

        Long showCount = baseMapper.countByStatus(STATUS_SHOW);
        if (STATUS_SHOW == dto.getStatus() && showCount >= MAX_SHOW_COUNT) {
            throw new ServiceException("当前显示数量已达5条上限！");
        }
        if (STATUS_HIDE == dto.getStatus() && showCount <= MIN_SHOW_COUNT) {
            throw new ServiceException("当前banner已是最后一条显示，不可关闭！");
        }

        Banner update = new Banner();
        update.setId(dto.getId());
        update.setStatus(dto.getStatus());
        update.setUpdateTime(DateUtils.getNowDate());
        int rows = baseMapper.updateLbtById(update);
        if (rows <= 0) {
            throw new ServiceException("轮播图显示状态修改失败");
        }
        return true;
    }

    @Override
    public Page<BannerVO> page(Page<Banner> page) {

        LambdaQueryWrapper<Banner> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Banner::getIsDelete, NOT_DELETE);
        wrapper.eq(Banner::getStatus, STATUS_SHOW);
        wrapper.orderByDesc(Banner::getSort);

        Page<Banner> bannerPage = this.baseMapper.selectPage(page, wrapper);
        Page<BannerVO> pageData = new Page<>(
                bannerPage.getCurrent(),
                bannerPage.getSize(),
                bannerPage.getTotal()
        );

        if (CollectionUtil.isNotEmpty(bannerPage.getRecords())) {
            List<BannerVO> voList = bannerPage.getRecords().stream()
                    .map(BannerVO::new)
                    .collect(Collectors.toList());
            pageData.setRecords(voList);
        }

        return pageData;
    }
}
