package com.zcloud.primeport.persistence.repository.impl;

import com.alibaba.cola.dto.PageResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jjb.saas.framework.repository.common.PageHelper;
import com.jjb.saas.framework.repository.repo.impl.BaseRepositoryImpl;
import com.zcloud.gbscommon.utils.PageQueryHelper;
import com.zcloud.gbscommon.utils.Query;
import com.zcloud.primeport.persistence.dataobject.VideoDO;
import com.zcloud.primeport.persistence.mapper.VideoMapper;
import com.zcloud.primeport.persistence.repository.VideoRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
@RequiredArgsConstructor
public class VideoRepositoryImpl extends BaseRepositoryImpl<VideoMapper, VideoDO> implements VideoRepository {
    private final VideoMapper videoMapper;

    @Override
    public PageResponse<VideoDO> listPageWithOnline(Map<String, Object> params) {
        Page<Map<String, Object>> page = new Page<>(Integer.parseInt(params.get("pageIndex").toString()), Integer.parseInt(params.get("pageSize").toString()));
        page.setOptimizeJoinOfCountSql(false);
        IPage<VideoDO> result = videoMapper.listPageWithOnline(page, params);
        return PageHelper.pageToResponse(result, result.getRecords());
    }

    @Override
    public PageResponse<VideoDO> listPage(Map<String, Object> params) {
        IPage<VideoDO> iPage = new Query<VideoDO>().getPage(params);
        QueryWrapper<VideoDO> queryWrapper = new QueryWrapper<>();
        queryWrapper = PageQueryHelper.createPageQueryWrapper(queryWrapper, params);
        queryWrapper.orderByDesc("create_time");
        IPage<VideoDO> result = videoMapper.selectPage(iPage, queryWrapper);
        return PageHelper.pageToResponse(result, result.getRecords());
    }

    @Override
    public Integer countByForeignIdAndDeviceType(Long foreignId, Integer deviceType) {
        QueryWrapper<VideoDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("foreign_id", foreignId);
        queryWrapper.eq("device_type", deviceType);
        queryWrapper.eq("delete_enum", "false");
        return Math.toIntExact(videoMapper.selectCount(queryWrapper));
    }

    @Override
    public Integer countByForeignId(Long foreignId) {
        QueryWrapper<VideoDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("foreign_id", foreignId);
        queryWrapper.eq("delete_enum", "false");
        return Math.toIntExact(videoMapper.selectCount(queryWrapper));
    }
}

