package com.kcim.dao.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kcim.common.util.UserContext;
import com.kcim.dao.mapper.CostReportMapper;
import com.kcim.dao.model.CostReport;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.OptionalLong;

/**
 * @program: CostAccount
 * @description: 成本报表管理
 * @author: Wang.YS
 * @create: 2023-11-01 10:44
 **/
@Repository
public class CostReportRepository extends ServiceImpl<CostReportMapper, CostReport> {
    public List<CostReport> getList(String reportName, String reportType) {
        LambdaQueryWrapper<CostReport> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CostReport::getHospId, UserContext.getHospId());
        if(!StringUtils.isEmpty(reportType)){
            queryWrapper.eq(CostReport::getType,reportName);
        }
        if(!StringUtils.isEmpty(reportName)){
            queryWrapper.like(CostReport::getName,reportName);
        }
        return this.list(queryWrapper);

    }
    public Long getCode() {
        LambdaQueryWrapper<CostReport> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CostReport::getHospId, UserContext.getHospId());
        List<CostReport> list = this.list(queryWrapper);
        if(CollectionUtils.isEmpty(list)){
            return  1L;
        }else {
            OptionalLong max = list.stream().mapToLong(CostReport::getCode).max();
            if(max.isPresent()){
                long asLong = max.getAsLong();
                return asLong + 1L;
            }else {
                return  1L;
            }
        }
    }
    public void deleteReport(Integer id) {
        CostReport costReport = this.getById(id);
        if(Objects.nonNull(costReport)){
            costReport.setDeleteUser(String.valueOf(UserContext.getCurrentUser().getId()));
            costReport.setDeleteTime(new Date());
            this.updateById(costReport);
            this.removeById(id);
        }
    }

    public CostReport getReportByReportCode(Long reportCode) {
        LambdaQueryWrapper<CostReport> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CostReport::getHospId, UserContext.getCurrentLoginHospId());
        queryWrapper.eq(CostReport::getCode,reportCode);
        return this.getOne(queryWrapper);
    }
}
