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.OrderMapper;
import com.kcim.dao.model.Order;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

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-11-15 13:59
 **/
@Repository
public class OrderRepository extends ServiceImpl<OrderMapper, Order> {
    public List<Order> getList() {
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getHospId, UserContext.getHospId());
        return this.list();
    }
    public List<Order> getList(String orderType, String orderName) {
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getHospId, UserContext.getHospId());
        if(!StringUtils.isEmpty(orderType)){
            queryWrapper.eq(Order::getType,orderType);
        }
        if(!StringUtils.isEmpty(orderName)){
            queryWrapper.like(Order::getName,orderName);
        }
        return this.list(queryWrapper);
    }

    public List<Order> getByCode(String code) {
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getHospId, UserContext.getHospId());
        queryWrapper.eq(Order::getCode,code);
        return this.list(queryWrapper);
    }

    public Order getOneByCode(String code) {

        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getHospId, UserContext.getHospId());
        queryWrapper.eq(Order::getCode,code);
        return this.getOne(queryWrapper);
    }

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

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