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.DiseaseTypeMapper;
import com.kcim.dao.model.DiseaseType;
import com.kcim.dao.model.StandItem;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @program: CostAccount
 * @description: 病种字典管理数据库交互
 * @author: Wang.YS
 * @create: 2023-10-31 11:20
 **/
@Repository
@Slf4j
public class DiseaseTypeRepository extends ServiceImpl<DiseaseTypeMapper, DiseaseType> {

    public Map<String, String> getDiseaseNameMap(){
        LambdaQueryWrapper<DiseaseType> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DiseaseType::getHospId, UserContext.getHospId());
        List<DiseaseType> list = this.list(queryWrapper);
        if(!CollectionUtils.isEmpty(list)){
            return list.stream().collect(Collectors.toMap(DiseaseType::getCode, DiseaseType::getName, (a, b) -> b));
        }
        log.error("当前院区未添加病种字典");
        return new HashMap<>();
    }

    public Page<DiseaseType> getPage(Integer current, Integer pageSize, String name) {
        Page<DiseaseType> page = new Page<>(current,pageSize);
        LambdaQueryWrapper<DiseaseType> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DiseaseType::getHospId, UserContext.getHospId());

        if(!StringUtils.isEmpty(name)){
            queryWrapper.and(q->q.like(DiseaseType::getName,name).or().like(DiseaseType::getCode,name));
//            queryWrapper.like(DiseaseType::getName,name);
        }

        return this.page(page,queryWrapper);
    }

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

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

    public void removeList(List<DiseaseType> list) {
        for (DiseaseType drug : list) {
            drug.setDeleteTime(new Date());
            drug.setDeleteUser(String.valueOf(UserContext.getCurrentUser().getId()));
        }
        this.updateBatchById(list);
        List<Integer> collect = list.stream().map(DiseaseType::getId).collect(Collectors.toList());
        this.removeBatchByIds(collect);
    }
}
