package com.ylx.massage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ylx.common.constant.MassageConstants;
import com.ylx.common.exception.ServiceException;
import com.ylx.common.utils.uuid.IdUtils;
import com.ylx.massage.domain.TLbt;
import com.ylx.massage.mapper.TLbtMapper;
import com.ylx.massage.service.TLbtService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 轮播图 服务实现类
 */
@Service
public class TLbtServiceImpl extends ServiceImpl<TLbtMapper, TLbt> implements TLbtService {

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

    private void batchLbt(Integer i) {
        LambdaQueryWrapper<TLbt> query1 = new LambdaQueryWrapper<TLbt>().ge(TLbt::getcSort, i);
        List<TLbt> lbts = list(query1);
        lbts.forEach(tLbt1 -> tLbt1.setcSort(tLbt1.getcSort() + 1));
        updateBatchById(lbts);
    }

    @Override
    public Boolean del(TLbt tLbt) {
        if (StringUtils.isBlank(tLbt.getcId())) {
            throw new ServiceException("ID不能为空");
        }
        return this.removeById(tLbt.getcId());
    }
}
