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.StandItemSpaceMapMapper;
import com.kcim.dao.model.StandItemSpaceMap;
import com.kcim.vo.SessionUserVO;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @program: CostAccount
 * @description: 标准项目与空间对照数据库交互
 * @author: Wang.YS
 * @create: 2023-10-26 10:44
 **/
@Repository
public class StandItemSpaceMapRepository extends ServiceImpl<StandItemSpaceMapMapper, StandItemSpaceMap> {
    /**
     * 获取空间与标准项目对照列表
     * @return  对照列表
     */
    public List<StandItemSpaceMap> getList() {
        LambdaQueryWrapper<StandItemSpaceMap> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StandItemSpaceMap::getHospId, UserContext.getHospId());
        return this.list(queryWrapper);
    }

    public void removeByStandCodes(List<String> standCodes) {
        LambdaQueryWrapper<StandItemSpaceMap> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StandItemSpaceMap::getHospId, UserContext.getHospId());
        queryWrapper.in(StandItemSpaceMap::getStandItemCode, standCodes);
        List<StandItemSpaceMap> list = this.list(queryWrapper);
        for (StandItemSpaceMap standItemEmpMap : list) {
            standItemEmpMap.setDeleteTime(new Date());
            standItemEmpMap.setDeleteUser(String.valueOf(UserContext.getCurrentUser().getId()));
        }
        this.updateBatchById(list,100);
        List<Integer> collect = list.stream().map(StandItemSpaceMap::getId).collect(Collectors.toList());
        this.removeBatchByIds(collect,100);
    }

    public List<StandItemSpaceMap> getByStandCode(String standCode) {
        LambdaQueryWrapper<StandItemSpaceMap> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StandItemSpaceMap::getHospId, UserContext.getHospId());
        queryWrapper.eq(StandItemSpaceMap::getStandItemCode, standCode);

        return this.list(queryWrapper);
    }


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

    public List<StandItemSpaceMap> getList(SessionUserVO currentUser) {
        LambdaQueryWrapper<StandItemSpaceMap> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StandItemSpaceMap::getHospId, currentUser.getHospId());
        return this.list(queryWrapper);
    }
}
