/**
 * BladeX Commercial License Agreement
 * Copyright (c) 2018-2099, https://bladex.cn. All rights reserved.
 * <p>
 * Use of this software is governed by the Commercial License Agreement
 * obtained after purchasing a license from BladeX.
 * <p>
 * 1. This software is for development use only under a valid license
 * from BladeX.
 * <p>
 * 2. Redistribution of this software's source code to any third party
 * without a commercial license is strictly prohibited.
 * <p>
 * 3. Licensees may copyright their own code but cannot use segments
 * from this software for such purposes. Copyright of this software
 * remains with BladeX.
 * <p>
 * Using this software signifies agreement to this License, and the software
 * must not be used for illegal purposes.
 * <p>
 * THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY. The author is
 * not liable for any claims arising from secondary or illegal development.
 * <p>
 * Author: Chill Zhuang (bladejava@qq.com)
 */
package org.springblade.transport.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.excel.util.ExcelUtil;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.annotation.PreAuth;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.transport.excel.TransportVehicleExcel;
import org.springblade.transport.pojo.entity.TransportVehicle;
import org.springblade.transport.pojo.vo.TransportVehicleExpiryStatVO;
import org.springblade.transport.pojo.vo.TransportVehicleVO;
import org.springblade.transport.service.ITransportVehicleService;
import org.springblade.transport.wrapper.TransportVehicleWrapper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * 车辆管理 控制器
 *
 * @author Chill
 */
@RestController
@AllArgsConstructor
@PreAuth(menu = "transport_vehicle")
@RequestMapping("/transport-vehicle")
@Tag(name = "车辆管理", description = "车辆管理")
public class TransportVehicleController extends BladeController {

	private static final int DEFAULT_CURRENT = 1;
	private static final int DEFAULT_SIZE = 10;
	private static final int MAX_SIZE = 100;

	private final ITransportVehicleService transportVehicleService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@Operation(summary = "详情", description = "传入transportVehicle")
	public R<TransportVehicleVO> detail(TransportVehicle vehicle) {
		TransportVehicle detail = transportVehicleService.getOne(Condition.getQueryWrapper(vehicle));
		return R.data(TransportVehicleWrapper.build().entityVO(detail));
	}

	/**
	 * 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@Operation(summary = "分页", description = "传入transportVehicle")
	public R<IPage<TransportVehicleVO>> list(TransportVehicleVO vehicle, Query query) {
		fillExpiryDate(vehicle);
		IPage<TransportVehicleVO> pages = transportVehicleService.selectTransportVehiclePage(Condition.getPage(normalizeQuery(query)), vehicle);
		return R.data(pages);
	}

	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 3)
	@Operation(summary = "新增或修改", description = "传入transportVehicle")
	public R submit(@Valid @RequestBody TransportVehicle vehicle) {
		return R.status(transportVehicleService.submit(vehicle));
	}

	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 4)
	@Operation(summary = "逻辑删除", description = "传入ids")
	public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) {
		return R.status(transportVehicleService.deleteLogic(Func.toLongList(ids)));
	}

	/**
	 * 修改状态
	 */
	@PostMapping("/status")
	@ApiOperationSupport(order = 5)
	@Operation(summary = "修改状态")
	public R status(@Parameter(description = "主键", required = true) @RequestParam Long id,
					@Parameter(description = "状态", required = true) @RequestParam Integer status) {
		return R.status(transportVehicleService.changeStatus(id, status));
	}

	@PostMapping("/audit-certification")
	@ApiOperationSupport(order = 6)
	@Operation(summary = "审核车辆认证")
	public R auditCertification(@RequestParam Long id, @RequestParam Integer certificationStatus,
							@RequestParam(required = false) String rejectReason) {
		return R.status(transportVehicleService.auditCertification(id, certificationStatus, rejectReason));
	}

	/**
	 * 证件有效期统计
	 */
	@GetMapping("/expiry-stat")
	@ApiOperationSupport(order = 6)
	@Operation(summary = "证件有效期统计", description = "传入transportVehicle")
	public R<TransportVehicleExpiryStatVO> expiryStat(TransportVehicleVO vehicle) {
		fillExpiryDate(vehicle);
		return R.data(transportVehicleService.expiryStat(vehicle));
	}

	/**
	 * 导出车辆
	 */
	@GetMapping("/export-transport-vehicle")
	@ApiOperationSupport(order = 7)
	@Operation(summary = "导出车辆")
	public void exportTransportVehicle(TransportVehicleVO vehicle,
									   @RequestParam(required = false) String ids,
									   HttpServletResponse response) {
		fillExpiryDate(vehicle);
		List<TransportVehicleExcel> list = transportVehicleService.exportTransportVehicle(buildExportQuery(vehicle, ids));
		ExcelUtil.export(response, "车辆管理" + DateUtil.time(), "车辆管理表", list, TransportVehicleExcel.class);
	}

	/**
	 * 导出模板
	 */
	@GetMapping("/export-template")
	@ApiOperationSupport(order = 8)
	@Operation(summary = "导出模板")
	public void exportTemplate(HttpServletResponse response) {
		List<TransportVehicleExcel> list = new ArrayList<>();
		ExcelUtil.export(response, "车辆管理模板", "车辆管理表", list, TransportVehicleExcel.class);
	}

	private Query normalizeQuery(Query query) {
		if (query == null) {
			query = new Query();
		}
		if (query.getCurrent() == null || query.getCurrent() < DEFAULT_CURRENT) {
			query.setCurrent(DEFAULT_CURRENT);
		}
		if (query.getSize() == null || query.getSize() <= 0) {
			query.setSize(DEFAULT_SIZE);
		}
		if (query.getSize() > MAX_SIZE) {
			query.setSize(MAX_SIZE);
		}
		return query;
	}

	private void fillExpiryDate(TransportVehicleVO vehicle) {
		if (vehicle.getToday() == null) {
			vehicle.setToday(LocalDate.now());
		}
		if (vehicle.getWarningDate() == null) {
			vehicle.setWarningDate(vehicle.getToday().plusDays(30));
		}
	}

	private LambdaQueryWrapper<TransportVehicle> buildExportQuery(TransportVehicleVO vehicle, String ids) {
		LambdaQueryWrapper<TransportVehicle> queryWrapper = Wrappers.<TransportVehicle>lambdaQuery()
			.eq(TransportVehicle::getIsDeleted, 0)
			.orderByDesc(TransportVehicle::getCreateTime);
		if (Func.isNotEmpty(ids)) {
			queryWrapper.in(TransportVehicle::getId, Func.toLongList(ids));
		}
		if (Func.isNotEmpty(vehicle.getOrganizationName())) {
			queryWrapper.like(TransportVehicle::getOrganizationName, vehicle.getOrganizationName());
		}
		if (Func.isNotEmpty(vehicle.getPlateNo())) {
			queryWrapper.like(TransportVehicle::getPlateNo, vehicle.getPlateNo());
		}
		if (Func.isNotEmpty(vehicle.getVehicleType())) {
			queryWrapper.eq(TransportVehicle::getVehicleType, vehicle.getVehicleType());
		}
		if (Func.isNotEmpty(vehicle.getBusinessRelation())) {
			queryWrapper.eq(TransportVehicle::getBusinessRelation, vehicle.getBusinessRelation());
		}
		if (Func.isNotEmpty(vehicle.getEnergyType())) {
			queryWrapper.eq(TransportVehicle::getEnergyType, vehicle.getEnergyType());
		}
		if (Func.isNotEmpty(vehicle.getStatus())) {
			queryWrapper.eq(TransportVehicle::getStatus, vehicle.getStatus());
		}
		if ("within30".equals(vehicle.getExpireStatus())) {
			queryWrapper.and(wrapper -> wrapper
				.and(item -> item.ne(TransportVehicle::getCompulsoryScrapLongTerm, 1)
					.between(TransportVehicle::getCompulsoryScrapDate, vehicle.getToday(), vehicle.getWarningDate()))
				.or(item -> item.ne(TransportVehicle::getDrivingLicenseLongTerm, 1)
					.between(TransportVehicle::getDrivingLicenseEndDate, vehicle.getToday(), vehicle.getWarningDate()))
				.or(item -> item.ne(TransportVehicle::getRoadTransportCertLongTerm, 1)
					.between(TransportVehicle::getRoadTransportCertEndDate, vehicle.getToday(), vehicle.getWarningDate()))
				.or(item -> item.ne(TransportVehicle::getAnnualReviewLongTerm, 1)
					.between(TransportVehicle::getAnnualReviewEndDate, vehicle.getToday(), vehicle.getWarningDate())));
		}
		if ("expired".equals(vehicle.getExpireStatus())) {
			queryWrapper.and(wrapper -> wrapper
				.and(item -> item.ne(TransportVehicle::getCompulsoryScrapLongTerm, 1)
					.lt(TransportVehicle::getCompulsoryScrapDate, vehicle.getToday()))
				.or(item -> item.ne(TransportVehicle::getDrivingLicenseLongTerm, 1)
					.lt(TransportVehicle::getDrivingLicenseEndDate, vehicle.getToday()))
				.or(item -> item.ne(TransportVehicle::getRoadTransportCertLongTerm, 1)
					.lt(TransportVehicle::getRoadTransportCertEndDate, vehicle.getToday()))
				.or(item -> item.ne(TransportVehicle::getAnnualReviewLongTerm, 1)
					.lt(TransportVehicle::getAnnualReviewEndDate, vehicle.getToday())));
		}
		return queryWrapper;
	}

}
