package com.iformall.controller.market;

import com.github.pagehelper.PageInfo;
import com.iformall.annotation.SystemControllerLog;
import com.iformall.common.ResultData;
import com.iformall.controller.base.BaseController;
import com.iformall.domain.po.*;
import com.iformall.enums.EnumWxTopicStatus;
import com.iformall.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Date;

@RestController
@RequestMapping("topic")
@Api(description = "专题相关接口")
public class WxTopicController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private WxTopicService wxTopicService;

    @GetMapping("list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页数", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", paramType = "query", required = true)})
    @SystemControllerLog(description = "专题-列表")
    public ResultData list(WxTopic wxTopic, Integer pageNum, Integer pageSize) {
        logger.debug("[" + getIpAddr() + "] WxTopicController::list");
        String tenantId = getTenantId();
        wxTopic.setTenantId(tenantId);
        PageInfo<WxTopic> page = wxTopicService.listAsPage(wxTopic, pageNum, pageSize);

        //可投放、已上线，时间区间查的是活动开始时间
        //已下线、已作为，时间区间查的是活动结束时间

        //设置正在上架的专题
        Date now = new Date();
        page.getList().stream().forEach(cc->{
            if (cc.getStatus().equals(EnumWxTopicStatus.VAILD.getCode()) && cc.getEndTime()!=null && cc.getBeginTime()!=null && now.getTime() >= cc.getBeginTime().getTime() && now.getTime() <= cc.getEndTime().getTime()) {
                cc.setIsOnline(1);
            }
        });
        return new ResultData(page);
    }

    @GetMapping("findById")
    @SystemControllerLog(description = "专题-获取详情")
    public ResultData findById(WxTopic wxTopic) {
        logger.debug("[" + getIpAddr() + "] WxTopicController::findById");
        String tenantId = getTenantId();
        wxTopic.setTenantId(tenantId);
        WxTopic queryTopic = wxTopicService.findById(wxTopic);
        return new ResultData(queryTopic);
    }

    @PostMapping("saveOrUpdate")
    @SystemControllerLog(description = "专题-保存更新")
    public ResultData saveOrUpdate(@RequestBody WxTopic wxTopic) {
        logger.debug("[" + getIpAddr() + "] WxTopicController::saveOrUpdate");
        wxTopic.setTenantId(super.getTenantId());
        return wxTopicService.saveOrUpdate(wxTopic);
    }


}
