package com.yami.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.model.AdvertInfo;
import com.yami.shop.bean.param.AdvertInfoParam;
import com.yami.shop.dao.AdvertInfoMapper;
import com.yami.shop.service.IAdvertInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @author wy
 */
@Service
public class AdvertInfoServiceImpl extends ServiceImpl<AdvertInfoMapper, AdvertInfo> implements IAdvertInfoService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<Void> addOrUpdate(AdvertInfoParam param) {
        AdvertInfo advertInfo = new AdvertInfo();
        BeanUtils.copyProperties(param, advertInfo);
        if (Objects.isNull(advertInfo.getId())) {
            advertInfo.setCreateTime(LocalDateTime.now());
        }
        saveOrUpdate(advertInfo);
        return ResponseEntity.ok().build();
    }

    @Override
    public ResponseEntity<AdvertInfoParam> get(Integer id) {
        AdvertInfo advertInfo = getById(id);
        if (Objects.nonNull(advertInfo)) {
            AdvertInfoParam param = new AdvertInfoParam();
            BeanUtils.copyProperties(advertInfo,param);
            return ResponseEntity.ok(param);
        }
        return ResponseEntity.ok(new AdvertInfoParam());
    }

    @Override
    public ResponseEntity<IPage<AdvertInfo>> search(String advertName, Integer status, Integer current, Integer size) {
        return ResponseEntity.ok(page(new Page<>(current, size), new LambdaQueryWrapper<AdvertInfo>()
                .like(Objects.nonNull(advertName), AdvertInfo::getAdvertName, advertName)
                .eq(Objects.nonNull(status), AdvertInfo::getStatus, status)
                .orderByDesc(AdvertInfo::getAdvertSort)
                .orderByDesc(AdvertInfo::getId)));
    }

    @Override
    public ResponseEntity<Void> del(Integer id) {
        removeById(id);
        return ResponseEntity.ok().build();
    }

    @Override
    public ResponseEntity<Void> operate(Integer id) {
        AdvertInfo advertInfo = getById(id);
        if (Objects.nonNull(advertInfo)) {
            Integer status = advertInfo.getStatus();
            if (status == 1) {
                advertInfo.setStatus(2);
            } else {
                advertInfo.setStatus(1);
            }
            updateById(advertInfo);
        }
        return ResponseEntity.ok().build();
    }
}
