package com.kcim.dao.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kcim.common.util.UserContext;
import com.kcim.dao.mapper.CostReportRedirectMapper;
import com.kcim.dao.model.CostReportRedirect;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @program: CostAccount
 * @description: 报表重定向数据库交互
 * @author: Wang.YS
 * @create: 2023-11-01 10:51
 **/
@Repository
public class CostReportRedirectRepository extends ServiceImpl<CostReportRedirectMapper, CostReportRedirect> {
    public Page<CostReportRedirect> getPage(Integer current, Integer pageSize, String reportName) {

        Page<CostReportRedirect> reportRedirectPage = new Page<>(current,pageSize);
        LambdaQueryWrapper<CostReportRedirect> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CostReportRedirect::getHospId, UserContext.getCurrentLoginHospId());
        if(!StringUtils.isEmpty(reportName)){
            queryWrapper.like(CostReportRedirect::getReportName,reportName);
        }
        return this.page(reportRedirectPage, queryWrapper);

    }

    public Long getCode() {
        LambdaQueryWrapper<CostReportRedirect> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CostReportRedirect::getHospId, UserContext.getHospId());
        List<CostReportRedirect> list = this.list(queryWrapper);
        if(CollectionUtils.isEmpty(list)){
            return  1L;
        }else {
            OptionalLong max = list.stream().mapToLong(CostReportRedirect::getCode).max();
            if(max.isPresent()){
                long asLong = max.getAsLong();
                return asLong + 1L;
            }else {
                return  1L;
            }
        }
    }

    public void deleteRedirect(Integer id) {
        CostReportRedirect reportRedirect = this.getById(id);
        if(Objects.nonNull(reportRedirect)){
            reportRedirect.setDeleteTime(new Date());
            reportRedirect.setDeleteUser(String.valueOf(UserContext.getCurrentUser().getId()));
            this.updateById(reportRedirect);
            this.removeById(id);
        }

    }

    public List<CostReportRedirect> getRedirectByReportCode(Long reportCode) {
        LambdaQueryWrapper<CostReportRedirect> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CostReportRedirect::getHospId, UserContext.getCurrentLoginHospId());
        queryWrapper.eq(CostReportRedirect::getReportCode, reportCode);
        return this.list(queryWrapper);
    }
}
