package com.bonus.canteen.core.nutrition.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bonus.canteen.core.nutrition.common.mapper.HealthInfoChronicMapper;
import com.bonus.canteen.core.nutrition.common.model.HealthInfoChronic;
import com.bonus.canteen.core.nutrition.common.service.HealthChronicService;
import com.bonus.canteen.core.nutrition.common.service.HealthInfoChronicService;
import com.bonus.common.houqin.utils.id.Id;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.invoke.SerializedLambda;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class HealthInfoChronicServiceImpl extends ServiceImpl<HealthInfoChronicMapper, HealthInfoChronic> implements HealthInfoChronicService {
   @Autowired
   private HealthChronicService healthChronicService;

   @Transactional(
      rollbackFor = {Exception.class}
   )
   public void insertAssociateBatch(Long custId, List<Long> chronicIds) {
      List<HealthInfoChronic> healthInfoChronics = (List)chronicIds.stream().map((chronicId) -> {
         return HealthInfoChronic.builder().id(Id.next()).custId(custId).chronicId(chronicId).chronicName(this.healthChronicService.selectNameById(chronicId)).build();
      }).collect(Collectors.toList());
      this.saveBatch(healthInfoChronics);
   }

   public List<Long> listChronicIdByCustId(Long custId) {
      //LambdaQueryWrapper<HealthInfoChronic> queryWrapper = (LambdaQueryWrapper)Wrappers.lambdaQuery(HealthInfoChronic.class).select(new SFunction[]{HealthInfoChronic::getChronicId}).eq(HealthInfoChronic::getCustId, custId);
      LambdaQueryWrapper<HealthInfoChronic> queryWrapper = Wrappers.lambdaQuery(HealthInfoChronic.class)
                                                           .select(HealthInfoChronic::getChronicId)
                                                           .eq(HealthInfoChronic::getCustId, custId);
      return (List)((HealthInfoChronicMapper)this.baseMapper).selectList(queryWrapper).stream().map(HealthInfoChronic::getChronicId).collect(Collectors.toList());
   }

   public List<HealthInfoChronic> listChronicByCustIds(List<Long> custIds) {
      return ((HealthInfoChronicMapper)this.baseMapper).selectList((Wrapper)Wrappers.lambdaQuery(HealthInfoChronic.class).in(HealthInfoChronic::getCustId, custIds));
   }

}
