package com.cf.imes.module.system.dal.mysql.funds.advertisement;

import cn.hutool.core.collection.CollUtil;
import com.cf.imes.framework.common.pojo.PageResult;
import com.cf.imes.framework.mybatis.core.mapper.BaseMapperX;
import com.cf.imes.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.cf.imes.module.system.controller.admin.funds.advertisement.vo.AdvertisementPageReqVO;
import com.cf.imes.module.system.controller.admin.funds.advertisement.vo.AdvertisementRespVO;
import com.cf.imes.module.system.dal.dataobject.funds.advertisement.AdvertisementDO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 广告信息表 Mapper
 *
 * @author 晨丰科技
 */
@Mapper
public interface AdvertisementMapper extends BaseMapperX<AdvertisementDO> {

    default PageResult<AdvertisementDO> selectPage(AdvertisementPageReqVO reqVO) {

        LambdaQueryWrapperX<AdvertisementDO> queryWrapper = new LambdaQueryWrapperX<AdvertisementDO>()
                .likeIfPresent(AdvertisementDO::getAdName, reqVO.getAdName())
                .eqIfPresent(AdvertisementDO::getStatus, reqVO.getStatus())
                .eqIfPresent(AdvertisementDO::getDeleted, false);

        List<Integer> adPosition = reqVO.getAdPosition();
        if (CollUtil.isNotEmpty(adPosition)) {
            queryWrapper.and(wrapper -> {
                adPosition.stream().distinct().forEach(pos -> wrapper.or().apply("FIND_IN_SET({0}, ad_position)", pos));
            });
        }

        return selectPage(reqVO, queryWrapper);

    }

    default List<AdvertisementDO> selectList(LocalDateTime now, Integer status) {
        return selectList(new LambdaQueryWrapperX<AdvertisementDO>()
                .le(AdvertisementDO::getStartTime, now)
                .eq(AdvertisementDO::getStatus, status));

    }



    default AdvertisementDO selectAdByAdName(String adName,Long id) {

        LambdaQueryWrapperX<AdvertisementDO> queryWrapper = new LambdaQueryWrapperX<>();
        queryWrapper.eq(AdvertisementDO::getAdName, adName);

        if(id != null){
            queryWrapper.ne(AdvertisementDO::getId, id);
        }

        return selectOne(queryWrapper);

    }



    void updateAdStatusIsPublish(@Param("now") LocalDate now,@Param("status") Integer status);



    void updateAdStatusIsEndPublished(@Param("now") LocalDate now,@Param("status") Integer status);


    /**
     * 查询广告位置下的广告列表
     *
     * @param adPosition
     * @param status
     * @param now
     * @return
     */
    List<AdvertisementRespVO> selectAdList(@Param("adPosition") Integer adPosition,@Param("status") Integer status,@Param("now") LocalDate now);

}
