package com.kcim.dao.repository;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kcim.dao.mapper.ComputeDrugCostDetailMapper;
import com.kcim.dao.model.ComputeDrugCostDetail;
import com.kcim.vo.SessionUserVO;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @program: CostAccount
 * @description: 药材成本计算明细表数据库交互
 * @author: Wang.YS
 * @create: 2024-01-11 20:06
 **/
@Repository
public class ComputeDrugCostDetailRepository extends ServiceImpl<ComputeDrugCostDetailMapper, ComputeDrugCostDetail> {
    static Integer MAX_NUMBER = 500;

    private static Integer countStep(Integer size) {
        return (size + MAX_NUMBER - 1) / MAX_NUMBER;
    }

    public void removeByItemCostId(List<Integer> costIds, SessionUserVO currentUser) {
        if (!CollectionUtils.isEmpty(costIds)) {
            int limit = countStep(costIds.size());
            //方法一：使用流遍历操作
            List<List<Integer>> mglist = new ArrayList<>();
            Stream.iterate(0, n -> n + 1).limit(limit).forEach(i -> {
                mglist.add(costIds.stream().skip(i * MAX_NUMBER).limit(MAX_NUMBER).collect(Collectors.toList()));
            });
            for (List<Integer> integers : mglist) {
                UpdateWrapper<ComputeDrugCostDetail> updateWrapper = new UpdateWrapper<>();
                updateWrapper.lambda().eq(ComputeDrugCostDetail::getDelFlag, 0)
                        .eq(ComputeDrugCostDetail::getHospId, currentUser.getHospId())
                        .in(ComputeDrugCostDetail::getDrugCostId, integers)
                        .set(ComputeDrugCostDetail::getDelFlag, 1);

                this.update(updateWrapper);
            }
        }
    }

    public void removeByComputeDate(String computeDate, SessionUserVO currentUser) {
        UpdateWrapper<ComputeDrugCostDetail> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(ComputeDrugCostDetail::getDelFlag, 0)
                .eq(ComputeDrugCostDetail::getHospId, currentUser.getHospId())
                .eq(ComputeDrugCostDetail::getComputeDate, computeDate)
                .set(ComputeDrugCostDetail::getDeleteTime,new Date())
                .set(ComputeDrugCostDetail::getDeleteUser,String.valueOf(currentUser.getId()))
                .set(ComputeDrugCostDetail::getDelFlag, 1);

        this.update(updateWrapper);
    }
}
