package com.sptg.ad.biz.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.sptg.ad.api.entity.DeviceAdvert;
import com.sptg.ad.api.entity.DeviceAdvertStatistics;
import com.sptg.ad.api.feigns.DeviceAdvertFeign;
import com.sptg.ad.biz.service.DeviceAdvertService;
import com.sptg.ad.biz.service.DeviceAdvertStatisticsService;
import com.sptg.common.core.beans.PageBean;
import com.sptg.common.core.beans.ResultBean;
import com.sptg.common.core.entity.DispatchTask;
import com.sptg.device.api.feigns.DeviceFeign;
import lombok.RequiredArgsConstructor;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 *            
 *               
 * description:
 */
@RestController
@RequiredArgsConstructor
public class DeviceAdvertController implements DeviceAdvertFeign {

    private final DeviceAdvertStatisticsService deviceAdvertStatisticsService;
    private final DeviceAdvertService deviceAdvertService;
    private final DeviceFeign deviceFeign;

    @Override
    @PostMapping(value = "/device/advert/statistics/pagingQuery")
    public Page<DeviceAdvertStatistics> pagingQueryStatistics(@RequestBody PageBean<DeviceAdvertStatistics, DeviceAdvertStatistics> pageBean) {
        return this.deviceAdvertStatisticsService.pagingQuery(pageBean);
    }

    @Override
    @PostMapping(value = "/device/advert/pagingQuery")
    public Page<DeviceAdvert> pagingQuery(@RequestBody PageBean<DeviceAdvert, DeviceAdvert> pageBean) {
        return this.deviceAdvertService.pagingQuery(pageBean);
    }

    @Override
    @PostMapping(value = "/device/advert/delete")
    public ResultBean<Boolean> deleteAdvert(@RequestBody DeviceAdvert advert) {
        DeviceAdvert dbAdvert = this.deviceAdvertService.selectById(advert.getId());
        Assert.notNull(dbAdvert,"Id不存在");
        //  判断广告是否已被删除或已结束投放
        if (dbAdvert.getStatus() == -1 || System.currentTimeMillis() > dbAdvert.getEndTime().getTime()){
            return ResultBean.ok(true);
        }
        //  删除广告
        dbAdvert.setStatus(-1);
        boolean result = this.deviceAdvertService.updateById(dbAdvert);
        if (result){
            //  下发指令
            this.deviceFeign.deleteAdvert(new DispatchTask(dbAdvert.getSerialNumber(),dbAdvert));
        }
        return ResultBean.ok(result);
    }
}
