package com.yc.ship.module.miniapplet.service.advert;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.yc.ship.framework.common.pojo.PageResult;
import com.yc.ship.framework.common.util.object.BeanUtils;
import com.yc.ship.module.miniapplet.controller.admin.advert.vo.AdvertPageReqVO;
import com.yc.ship.module.miniapplet.controller.admin.advert.vo.AdvertSaveReqVO;
import com.yc.ship.module.miniapplet.dal.dataobject.advert.AdvertDO;
import com.yc.ship.module.miniapplet.dal.mysql.advert.AdvertMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

import static com.yc.ship.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.yc.ship.module.miniapplet.enums.ErrorCodeConstants.ADVERT_NOT_EXISTS;


/**
 * 广告管理 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class AdvertServiceImpl implements AdvertService {

    @Resource
    private AdvertMapper advertMapper;

    @Override
    public Long createAdvert(AdvertSaveReqVO createReqVO) {
        if (createReqVO.getValidType() == 1) {
            LocalDateTime endDate = createReqVO.getEndDate();
            endDate = endDate.withHour(23).withMinute(59).withSecond(59);
            createReqVO.setEndDate(endDate);
        }
        // 插入
        AdvertDO advert = BeanUtils.toBean(createReqVO, AdvertDO.class);
        advert.setId(IdWorker.getId(advert));
        advertMapper.insert(advert);
        // 返回
        return advert.getId();
    }

    @Override
    public void updateAdvert(AdvertSaveReqVO updateReqVO) {
        // 校验存在
        validateAdvertExists(updateReqVO.getId());
        if (updateReqVO.getValidType() == 1) {
            LocalDateTime endDate = updateReqVO.getEndDate();
            endDate = endDate.withHour(23).withMinute(59).withSecond(59);
            updateReqVO.setEndDate(endDate);
        }
        // 更新
        AdvertDO updateObj = BeanUtils.toBean(updateReqVO, AdvertDO.class);
        advertMapper.updateById(updateObj);
    }

    @Override
    public void deleteAdvert(Long id) {
        // 校验存在
        validateAdvertExists(id);
        // 删除
        advertMapper.deleteById(id);
    }

    private void validateAdvertExists(Long id) {
        if (advertMapper.selectById(id) == null) {
            throw exception(ADVERT_NOT_EXISTS);
        }
    }

    @Override
    public AdvertDO getAdvert(Long id) {
        return advertMapper.selectById(id);
    }

    @Override
    public PageResult<AdvertDO> getAdvertPage(AdvertPageReqVO pageReqVO) {
        return advertMapper.selectPage(pageReqVO);
    }

    @Override
    public List<AdvertDO> getAdvertList(Long adsenseId) {
        return advertMapper.selectAdvertList(adsenseId);
    }

    @Override
    public List<AdvertDO> getCanUseAdvertList(Long adsenseId) {
        return advertMapper.selectCanUseAdvertList(adsenseId);
    }

}
