package com.cyksj.web.controller.manage.sys;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.model.entity.TicketAdvertiseConfig;
import com.cyksj.service.mange.ticket.TicketAdvertiseConfigService;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.SearchResult;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/*
 *项目名: netflix
 *文件名: TicketAdvertiseConfigController
 *创建者: JavaZou
 *创建时间:2023/7/12 12:24
 */
@RestController
@RequestMapping("/manage/ticket/config")
@RequiredArgsConstructor
public class TicketAdvertiseConfigController {
	private final TicketAdvertiseConfigService ticketAdvertiseConfigService;

	private final BeanSearcher beanSearcher;

	private final HttpServletRequest request;

	/**
	 * 新建车票 广告配置图
	 */
	@PostMapping("/advertise")
	public Result<String> saveTicketAdvertiseConfig(@RequestBody @Validated TicketAdvertiseConfig config) {
		ticketAdvertiseConfigService.saveOrUpdateAdvertiseConfig(config);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}


	/**
	 * 编辑广告配置
	 */
	@PutMapping("/advertise/update")
	public Result<String> updateTicketAdvertiseConfig(@RequestBody @Validated TicketAdvertiseConfig config) {
		ticketAdvertiseConfigService.saveOrUpdateAdvertiseConfig(config);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 删除
	 */
	@DeleteMapping("/advertise/delete/{id}")
	public Result<String> saveTicketAdvertiseConfig(@PathVariable Long id) {
		ticketAdvertiseConfigService.update(null, Wrappers.lambdaUpdate(TicketAdvertiseConfig.class)
				.set(TicketAdvertiseConfig::getDeleted, false)
				.eq(TicketAdvertiseConfig::getId, id));
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 广告配置列表
	 */
	@GetMapping("/advertise/get")
	public Result<SearchResult<TicketAdvertiseConfig>> getAdvertiseConfig() {
		SearchResult<TicketAdvertiseConfig> search = beanSearcher.search(TicketAdvertiseConfig.class, MapUtils.flatBuilder(request.getParameterMap())
				.orderBy(TicketAdvertiseConfig::getSorted).desc()
				.orderBy(TicketAdvertiseConfig::getId).desc()
				.build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 上下架广告配置
	 */
	@PutMapping("/advertise/updateStatus/{id}")
	public Result<String> updateStatusById(@PathVariable Long id) {
		TicketAdvertiseConfig ticketAdvertiseConfig = ticketAdvertiseConfigService.getById(id);
		Assert.notNull(ticketAdvertiseConfig, "该车票配置不存在");
		ticketAdvertiseConfig.setStatus(!ticketAdvertiseConfig.getStatus());
		ticketAdvertiseConfigService.updateById(ticketAdvertiseConfig);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}
}
