package com.yami.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.model.FreightFeeReduction;
import com.yami.shop.bean.param.FreightFeeReductionParam;
import com.yami.shop.common.exception.GlobalException;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.dao.FreightFeeReductionMapper;
import com.yami.shop.service.FreightFeeReductionService;
import org.springframework.beans.BeanUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author wy
 */
@Service
public class FreightFeeReductionServiceImpl extends ServiceImpl<FreightFeeReductionMapper, FreightFeeReduction> implements FreightFeeReductionService {

    @Override
    public ResponseEntity<Void> addOrUpdate(FreightFeeReductionParam param) {
        FreightFeeReduction reduction = new FreightFeeReduction();
        BeanUtils.copyProperties(param, reduction);
        LocalDateTime now = LocalDateTime.now();
        FreightFeeReduction exist = getOne(new LambdaQueryWrapper<FreightFeeReduction>()
                .eq(FreightFeeReduction::getStatus, 1)
                .ge(FreightFeeReduction::getEndTime, param.getEndTime()));
        if (Objects.nonNull(exist) && !exist.getId().equals(param.getId())) {
            throw new GlobalException("此时段已有活动");
        }
        if (Objects.isNull(param.getId())) {
            reduction.setCreateTime(now);
            reduction.setUpdateTime(now);
            save(reduction);
        } else {
            reduction.setUpdateTime(now);
            updateById(reduction);
        }
        return ResponseEntity.ok().build();
    }

    @Override
    public ResponseEntity<FreightFeeReduction> get(Integer id) {
        return ResponseEntity.ok(getById(id));
    }
}
