package com.cy.guoyan.admin.module.guoyan.service.banner;

import cn.hutool.core.collection.CollUtil;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import com.cy.guoyan.admin.module.guoyan.controller.admin.banner.vo.*;
import com.cy.guoyan.admin.module.guoyan.dal.dataobject.banner.BannerDO;
import com.cy.guoyan.admin.framework.common.pojo.PageResult;
import com.cy.guoyan.admin.framework.common.pojo.PageParam;
import com.cy.guoyan.admin.framework.common.util.object.BeanUtils;

import com.cy.guoyan.admin.module.guoyan.dal.mysql.banner.BannerMapper;

import static com.cy.guoyan.admin.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.cy.guoyan.admin.framework.common.util.collection.CollectionUtils.convertList;
import static com.cy.guoyan.admin.framework.common.util.collection.CollectionUtils.diffList;
import static com.cy.guoyan.admin.module.system.enums.ErrorCodeConstants.*;

/**
 * 横幅 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class BannerServiceImpl implements BannerService {

    @Resource
    private BannerMapper bannerMapper;

    @Override
    public Long createBanner(BannerSaveReqVO createReqVO) {
        // 插入
        BannerDO banner = BeanUtils.toBean(createReqVO, BannerDO.class);
        bannerMapper.insert(banner);
        // 返回
        return banner.getId();
    }

    @Override
    public void updateBanner(BannerSaveReqVO updateReqVO) {
        // 校验存在
        validateBannerExists(updateReqVO.getId());
        // 更新
        BannerDO updateObj = BeanUtils.toBean(updateReqVO, BannerDO.class);
        bannerMapper.updateById(updateObj);
    }

    @Override
    public void deleteBanner(Long id) {
        // 校验存在
        validateBannerExists(id);
        // 删除
        bannerMapper.deleteById(id);
    }

    @Override
        public void deleteBannerListByIds(List<Long> ids) {
        // 校验存在
        validateBannerExists(ids);
        // 删除
        bannerMapper.deleteByIds(ids);
        }

    private void validateBannerExists(List<Long> ids) {
        List<BannerDO> list = bannerMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(BANNER_NOT_EXISTS);
        }
    }

    private void validateBannerExists(Long id) {
        if (bannerMapper.selectById(id) == null) {
            throw exception(BANNER_NOT_EXISTS);
        }
    }

    @Override
    public BannerDO getBanner(Long id) {
        return bannerMapper.selectById(id);
    }

    @Override
    public PageResult<BannerDO> getBannerPage(BannerPageReqVO pageReqVO) {
        return bannerMapper.selectPage(pageReqVO);
    }

}