package com.ruoyi.info.ad.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.BeanCopyUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.info.ad.domain.Ad;
import com.ruoyi.info.ad.domain.bo.AdBo;
import com.ruoyi.info.ad.domain.vo.AdVo;
import com.ruoyi.info.ad.exception.AdExceptionEnum;
import com.ruoyi.info.ad.mapper.AdMapper;
import com.ruoyi.info.ad.service.IAdService;
import com.ruoyi.info.quicklink.domain.QuickLink;
import com.ruoyi.info.quicklink.enums.ResourceModel;
import com.ruoyi.info.quicklink.exception.QuiclLinkExceptionEnum;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

/**
 * 广告Service业务层处理
 *
 * @author lubo
 * @date 2023-12-21
 */
@RequiredArgsConstructor
@Service
public class AdServiceImpl implements IAdService {

    private final AdMapper baseMapper;

    /**
     * 查询广告分页
     *
     * @param bo 广告
     * @return 广告
     */
    @Override
    public TableDataInfo<AdVo> queryPageList(AdBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Ad> lqw = buildQueryWrapper(bo);
        Page<AdVo> result = this.baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询广告列表
     *
     * @param bo 广告
     * @return 广告
     */
    @Override
    public List<AdVo> queryList(AdBo bo) {
        LambdaQueryWrapper<Ad> lqw = buildQueryWrapper(bo);
        return this.baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Ad> buildQueryWrapper(AdBo bo) {
        LambdaQueryWrapper<Ad> lqw = Wrappers.lambdaQuery();
        lqw.like(StrUtil.isNotBlank(bo.getAdName()), Ad::getAdName, bo.getAdName());
        lqw.eq(ObjectUtil.isNotNull(bo.getLocationCode()), Ad::getLocationCode, bo.getLocationCode());
        lqw.eq(ObjectUtil.isNotNull(bo.getStatus()), Ad::getStatus, bo.getStatus());
        lqw.ge(ObjectUtil.isNotNull(bo.getCreateTimeStart()), Ad::getCreateTime, bo.getCreateTimeStart());
        lqw.le(ObjectUtil.isNotNull(bo.getCreateTimeEnd()), Ad::getCreateTime, bo.getCreateTimeEnd());

        lqw.orderByAsc(Ad::getOrderIndex);
        lqw.orderByDesc(Ad::getCreateTime);
        return lqw;
    }

    /**
     * 查询广告列表
     *
     * @param locationCode 广告
     * @return 广告
     */
    @Override
    public List<AdVo> queryListForApi(String locationCode) {
        List<AdVo> list = this.baseMapper.selectVoList(new LambdaQueryWrapper<Ad>()
            .eq(Ad::getLocationCode, locationCode)
            .eq(Ad::getStatus, true)
            .orderByAsc(Ad::getOrderIndex)
            .orderByDesc(Ad::getCreateTime)
        );
        return list;
    }

    /**
     * 查询广告
     *
     * @param adId 广告主键
     * @return 广告
     */
    @Override
    public AdVo queryById(Long adId){
        return this.baseMapper.selectVoById(adId);
    }

    /**
     * 详情广告
     *
     * @param adId 广告主键
     * @return 广告
     */
    @Override
    public Ad loadById(Long adId, Boolean tw){
        Ad info = this.baseMapper.selectById(adId);
        if(ObjectUtil.isEmpty(info) && tw){
            throw new ServiceException(AdExceptionEnum.AD_IS_NOT_EXISTS);
        }
        return info;
    }

    /**
     * 新增广告
     *
     * @param bo 广告
     * @return 结果
     */
    @Override
    public Boolean insertByBo(AdBo bo) {
        validEntityBeforeSave(bo);
        Ad add = BeanUtil.toBean(bo, Ad.class);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setAdId(add.getAdId());
        }
        return flag;
    }

    /**
     * 修改广告
     *
     * @param bo 广告
     * @return 结果
     */
    @Override
    public Boolean updateByBo(AdBo bo) {
        validEntityBeforeSave(bo);
        Ad ad = baseMapper.selectById(bo.getAdId());
        Ad copy = BeanCopyUtils.copy(bo, ad);
        return baseMapper.updateById(copy) > 0;
    }

    /**
     * 保存前的数据校验
     *
     * @param bo 实体类数据
     */
    private void validEntityBeforeSave(AdBo bo){
        switch (bo.getJumpType()) {
            case OUTER:
                bo.setInnerPageCode(null);
                bo.setResourceModel(ResourceModel.NO);
                bo.setResourceModelId(null);
                bo.setResourceModelTitle(null);

                if(StringUtils.isEmpty(bo.getOutsideAddress())) {
                    throw new ServiceException(QuiclLinkExceptionEnum.OUTER_ADDRESS_EMPTY);
                }
                break;
            case INNER:
                bo.setOutsideAddress(null);
                bo.setResourceModel(ResourceModel.NO);
                bo.setResourceModelId(null);
                bo.setResourceModelTitle(null);

                if(StringUtils.isEmpty(bo.getInnerPageCode())) {
                    throw new ServiceException(QuiclLinkExceptionEnum.INNER_PAGE_CODE_EMPTY);
                }
                break;
            case INNER_RESOURCE:
                bo.setInnerPageCode(null);
                bo.setOutsideAddress(null);

                if(ObjectUtil.isNull(bo.getResourceModel())) {
                    throw new ServiceException(QuiclLinkExceptionEnum.RESOURCE_MODEL_EMPTY);
                }
                if(ObjectUtil.isNull(bo.getResourceModelId())) {
                    throw new ServiceException(QuiclLinkExceptionEnum.RESOURCE_MODEL_ID_EMPTY);
                }
                if(ObjectUtil.isNull(bo.getResourceModelTitle())) {
                    throw new ServiceException(QuiclLinkExceptionEnum.RESOURCE_MODEL_TITLE_EMPTY);
                }
                break;
            default:
                break;
        }

    }

    /**
     * 批量删除广告
     *
     * @param ids 需要删除的广告主键
     * @return 结果
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public boolean setStatus(Long id) {
        Ad ad = loadById(id, true);
        this.baseMapper.update(null, new LambdaUpdateWrapper<Ad>()
            .set(Ad::getStatus,!ad.getStatus())
            .eq(Ad::getAdId,id)
        );
        return true;
    }

    @Override
    public boolean delSingle(Long id) {
        Ad ad = loadById(id, true);
        this.baseMapper.deleteById(id);
        return true;
    }

    @Override
    public Long countAd(String locationCode) {
        Long aLong = this.baseMapper.selectCount(new LambdaQueryWrapper<Ad>()
            .eq(Ad::getLocationCode, locationCode)
        );
        return aLong;
    }

}
