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

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bonus.canteen.core.nutrition.common.enums.YesOrNoEnum;
import com.bonus.canteen.core.nutrition.mapper.HealthBodyRecordMapper;
import com.bonus.canteen.core.nutrition.common.model.HealthBodyRecord;
import com.bonus.canteen.core.nutrition.service.HealthBodyRecordService;
import com.bonus.canteen.core.nutrition.common.utils.NuConvertUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
public class HealthBodyRecordServiceImpl extends ServiceImpl<HealthBodyRecordMapper, HealthBodyRecord> implements HealthBodyRecordService {
   @Transactional(
      rollbackFor = {Exception.class}
   )
   public void insertLatestRecord(HealthBodyRecord healthBodyRecord) {
      if (this.checkDate(healthBodyRecord)) {
         BigDecimal bmi = NuConvertUtil.getBMI(healthBodyRecord.getWeight(), healthBodyRecord.getHeight());
         healthBodyRecord.setBmi(bmi);
         LambdaUpdateWrapper<HealthBodyRecord> updateWrapper = Wrappers.lambdaUpdate(HealthBodyRecord.class)
                         .set(HealthBodyRecord::getIfLatest, YesOrNoEnum.NO.key())
                          .eq(HealthBodyRecord::getUserId, healthBodyRecord.getUserId())
                          .eq(HealthBodyRecord::getIfLatest, YesOrNoEnum.YES.key());
         this.update(updateWrapper);
         healthBodyRecord.setIfLatest(YesOrNoEnum.YES.key());
         this.save(healthBodyRecord);
      }
   }

   public Boolean checkDate(HealthBodyRecord healthBodyRecord) {
      return !ObjectUtil.isNull(healthBodyRecord.getHeight()) && !ObjectUtil.isNull(healthBodyRecord.getWeight());
   }

}
