/**
 * 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.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
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.tenant.annotation.NonDS;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.system.excel.PortTerminalExcel;
import org.springblade.system.excel.PortTerminalImporter;
import org.springblade.system.pojo.entity.PortTerminal;
import org.springblade.system.pojo.vo.PortTerminalVO;
import org.springblade.system.service.IPortTerminalService;
import org.springblade.system.wrapper.PortTerminalWrapper;
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 org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 港口码头主数据 控制器
 *
 * @author Chill
 */
@NonDS
@RestController
@AllArgsConstructor
@PreAuth(menu = "port_terminal")
@RequestMapping("/port-terminal")
@Tag(name = "港口码头主数据", description = "港口码头主数据")
public class PortTerminalController 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 SOURCE_INITIAL = "初始化导入";

	private final IPortTerminalService portTerminalService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@Operation(summary = "详情", description = "传入portTerminal")
	public R<PortTerminalVO> detail(PortTerminal portTerminal) {
		if (Func.isEmpty(portTerminal.getId())) {
			return R.fail("主键不能为空");
		}
		PortTerminal detail = portTerminalService.getById(portTerminal.getId());
		if (Func.isEmpty(detail)) {
			return R.fail("港口码头不存在");
		}
		return R.data(PortTerminalWrapper.build().entityVO(detail));
	}

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

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

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

	/**
	 * 启用或停用
	 */
	@PostMapping("/status")
	@ApiOperationSupport(order = 5)
	@Operation(summary = "启用或停用", description = "传入id和status")
	public R status(@Parameter(description = "主键", required = true) @RequestParam Long id,
					@Parameter(description = "状态", required = true) @RequestParam Integer status) {
		return R.status(portTerminalService.changeStatus(id, status));
	}

	/**
	 * 上级港口下拉数据源
	 */
	@GetMapping("/port-select")
	@ApiOperationSupport(order = 6)
	@Operation(summary = "上级港口下拉数据源")
	public R<List<PortTerminal>> portSelect() {
		return R.data(portTerminalService.selectEnabledPorts());
	}

	/**
	 * 导入港口码头主数据
	 */
	@PostMapping("/import-port-terminal")
	@ApiOperationSupport(order = 7)
	@Operation(summary = "导入港口码头主数据", description = "传入excel")
	public R importPortTerminal(MultipartFile file) {
		if (file == null || file.isEmpty()) {
			return R.fail("上传文件不能为空");
		}
		String fileName = Func.toStrWithEmpty(file.getOriginalFilename(), "").toLowerCase();
		if (!fileName.endsWith(".xls") && !fileName.endsWith(".xlsx")) {
			return R.fail("请上传 .xls,.xlsx 标准格式文件");
		}
		PortTerminalImporter portTerminalImporter = new PortTerminalImporter(portTerminalService);
		ExcelUtil.save(file, portTerminalImporter, PortTerminalExcel.class);
		return R.success("操作成功");
	}

	/**
	 * 导出港口码头主数据
	 */
	@GetMapping("/export-port-terminal")
	@ApiOperationSupport(order = 8)
	@Operation(summary = "导出港口码头主数据")
	public void exportPortTerminal(@Parameter(hidden = true) @RequestParam Map<String, Object> portTerminal, HttpServletResponse response) {
		Object ids = portTerminal.remove("ids");
		Object dataSource = portTerminal.remove("dataSource");
		portTerminal.remove("Blade-Auth");
		portTerminal.remove("Authorization");
		portTerminal.remove("access_token");
		QueryWrapper<PortTerminal> queryWrapper = Condition.getQueryWrapper(portTerminal, PortTerminal.class);
		applyDataSourceCondition(queryWrapper, dataSource);
		if (Func.isNotEmpty(ids)) {
			queryWrapper.lambda().in(PortTerminal::getId, Func.toLongList(ids.toString()));
		}
		List<PortTerminalExcel> list = portTerminalService.exportPortTerminal(queryWrapper);
		ExcelUtil.export(response, "港口码头主数据" + DateUtil.time(), "港口码头主数据表", list, PortTerminalExcel.class);
	}

	/**
	 * 导出模板
	 */
	@GetMapping("/export-template")
	@ApiOperationSupport(order = 9)
	@Operation(summary = "导出模板")
	public void exportTemplate(HttpServletResponse response) {
		List<PortTerminalExcel> list = new ArrayList<>();
		ExcelUtil.export(response, "港口码头主数据模板", "港口码头主数据表", list, PortTerminalExcel.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 applyDataSourceCondition(QueryWrapper<PortTerminal> queryWrapper, Object dataSource) {
		String value = Func.toStrWithEmpty(dataSource, "");
		if (Func.isEmpty(value)) {
			return;
		}
		if (SOURCE_INITIAL.equals(value)) {
			queryWrapper.in("data_source", SOURCE_INITIAL, "初始导入");
		} else {
			queryWrapper.eq("data_source", value);
		}
	}

}
