/**
 * 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.DriverExcel;
import org.springblade.transport.pojo.entity.Driver;
import org.springblade.transport.pojo.vo.DriverExpiryStatVO;
import org.springblade.transport.pojo.vo.DriverVO;
import org.springblade.transport.service.IDriverService;
import org.springblade.transport.wrapper.DriverWrapper;
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 = "driver")
@RequestMapping("/driver")
@Tag(name = "司机管理", description = "司机管理")
public class DriverController extends BladeController {

	private static final int DEFAULT_CURRENT = 1;
	private static final int DEFAULT_SIZE = 10;
	private static final int MAX_SIZE = 100;
	private static final String EXPIRY_EXPIRED_SQL = """
		(
			((driving_license_long_term IS NULL OR driving_license_long_term != 1) AND driving_license_end_date < {0})
			OR ((qualification_long_term IS NULL OR qualification_long_term != 1) AND qualification_end_date < {0})
		)
		""";
	private static final String EXPIRY_WITHIN_30_SQL = """
		(
			NOT (
				((driving_license_long_term IS NULL OR driving_license_long_term != 1) AND driving_license_end_date < {0})
				OR ((qualification_long_term IS NULL OR qualification_long_term != 1) AND qualification_end_date < {0})
			)
			AND (
				((driving_license_long_term IS NULL OR driving_license_long_term != 1) AND driving_license_end_date BETWEEN {0} AND {1})
				OR ((qualification_long_term IS NULL OR qualification_long_term != 1) AND qualification_end_date BETWEEN {0} AND {1})
			)
		)
		""";

	private final IDriverService driverService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@Operation(summary = "详情", description = "传入driver")
	public R<DriverVO> detail(Driver driver) {
		Driver detail = driverService.getOne(Condition.getQueryWrapper(driver));
		return R.data(DriverWrapper.build().entityVO(detail));
	}

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

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

	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 4)
	@Operation(summary = "逻辑删除", description = "传入ids")
	public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) {
		return R.status(driverService.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(driverService.changeStatus(id, status));
	}

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

	/**
	 * 导出司机
	 */
	@GetMapping("/export-driver")
	@ApiOperationSupport(order = 7)
	@Operation(summary = "导出司机")
	public void exportDriver(DriverVO driver,
							 @RequestParam(required = false) String ids,
							 HttpServletResponse response) {
		fillExpiryDate(driver);
		List<DriverExcel> list = driverService.exportDriver(buildExportQuery(driver, ids));
		ExcelUtil.export(response, "司机管理" + DateUtil.time(), "司机管理表", list, DriverExcel.class);
	}

	/**
	 * 导出模板
	 */
	@GetMapping("/export-template")
	@ApiOperationSupport(order = 8)
	@Operation(summary = "导出模板")
	public void exportTemplate(HttpServletResponse response) {
		List<DriverExcel> list = new ArrayList<>();
		ExcelUtil.export(response, "司机管理模板", "司机管理表", list, DriverExcel.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(DriverVO driver) {
		if (driver.getToday() == null) {
			driver.setToday(LocalDate.now());
		}
		if (driver.getWarningDate() == null) {
			driver.setWarningDate(driver.getToday().plusDays(30));
		}
	}

	private LambdaQueryWrapper<Driver> buildExportQuery(DriverVO driver, String ids) {
		LambdaQueryWrapper<Driver> queryWrapper = Wrappers.<Driver>lambdaQuery()
			.eq(Driver::getIsDeleted, 0)
			.orderByDesc(Driver::getCreateTime);
		if (Func.isNotEmpty(ids)) {
			queryWrapper.in(Driver::getId, Func.toLongList(ids));
		}
		if (Func.isNotEmpty(driver.getDriverName())) {
			queryWrapper.like(Driver::getDriverName, driver.getDriverName());
		}
		if (Func.isNotEmpty(driver.getMobile())) {
			queryWrapper.like(Driver::getMobile, driver.getMobile());
		}
		if (Func.isNotEmpty(driver.getIdCardNo())) {
			queryWrapper.like(Driver::getIdCardNo, driver.getIdCardNo());
		}
		if (Func.isNotEmpty(driver.getDrivingType())) {
			queryWrapper.eq(Driver::getDrivingType, driver.getDrivingType());
		}
		if (Func.isNotEmpty(driver.getDriverType())) {
			queryWrapper.eq(Driver::getDriverType, driver.getDriverType());
		}
		if (Func.isNotEmpty(driver.getOrganizationName())) {
			queryWrapper.like(Driver::getOrganizationName, driver.getOrganizationName());
		}
		if (Func.isNotEmpty(driver.getStatus())) {
			queryWrapper.eq(Driver::getStatus, driver.getStatus());
		}
		if ("within30".equals(driver.getExpireStatus())) {
			queryWrapper.apply(EXPIRY_WITHIN_30_SQL, driver.getToday(), driver.getWarningDate());
		}
		if ("expired".equals(driver.getExpireStatus())) {
			queryWrapper.apply(EXPIRY_EXPIRED_SQL, driver.getToday());
		}
		return queryWrapper;
	}

}
