/**
 * 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.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.log.exception.ServiceException;
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.common.excel.ImportFailureExcelUtil;
import org.springblade.system.excel.CargoTypeExcel;
import org.springblade.system.excel.CargoTypeExportExcel;
import org.springblade.system.excel.CargoTypeImportFailureExcel;
import org.springblade.system.pojo.entity.CargoType;
import org.springblade.system.pojo.vo.CargoTypeVO;
import org.springblade.system.service.ICargoTypeService;
import org.springblade.system.wrapper.CargoTypeWrapper;
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;

/**
 * 货物类型 控制器
 *
 * @author Chill
 */
@NonDS
@RestController
@AllArgsConstructor
@PreAuth(menu = "cargo_type")
@RequestMapping("/cargo-type")
@Tag(name = "货物类型", description = "货物类型")
public class CargoTypeController extends BladeController {

	private final ICargoTypeService cargoTypeService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@Operation(summary = "详情", description = "传入cargoType")
	public R<CargoTypeVO> detail(CargoType cargoType) {
		CargoType detail = cargoTypeService.getOne(Condition.getQueryWrapper(cargoType));
		if (detail == null) {
			throw new ServiceException("数据不存在");
		}
		CargoTypeVO cargoTypeVO = CargoTypeWrapper.build().entityVO(detail);
		if (Func.isNotEmpty(detail.getParentId())) {
			CargoType parent = cargoTypeService.getById(detail.getParentId());
			cargoTypeVO.setParentCargoName(parent == null ? "" : parent.getCargoName());
		}
		return R.data(cargoTypeVO);
	}

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

	/**
	 * 一级货物类型选项
	 */
	@GetMapping("/parent-options")
	@ApiOperationSupport(order = 3)
	@Operation(summary = "一级货物类型选项", description = "传入keyword")
	public R<List<CargoTypeVO>> parentOptions(@RequestParam(required = false) String keyword) {
		return R.data(cargoTypeService.parentOptions(keyword));
	}

	/**
	 * 二级货物类型建议编码
	 */
	@GetMapping("/next-code")
	@ApiOperationSupport(order = 4)
	@Operation(summary = "二级货物类型建议编码", description = "传入parentCargoCode")
	public R<String> nextCode(@Parameter(description = "上级货物类型编码", required = true) @RequestParam String parentCargoCode) {
		return R.data(cargoTypeService.nextChildCode(parentCargoCode));
	}

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

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

	/**
	 * 导入货物类型
	 */
	@PostMapping("/import-cargo-type")
	@ApiOperationSupport(order = 7)
	@Operation(summary = "导入货物类型", description = "传入excel")
	public R importCargoType(MultipartFile file, HttpServletResponse response) {
		List<CargoTypeExcel> data = ExcelUtil.read(file, CargoTypeExcel.class);
		List<CargoTypeImportFailureExcel> failureList = cargoTypeService.importCargoType(data);
		if (Func.isNotEmpty(failureList)) {
			ImportFailureExcelUtil.export(response, "货物类型导入失败明细" + DateUtil.time(), "导入失败明细", failureList, CargoTypeExcel.class);
			return null;
		}
		return R.success("导入数据成功");
	}

	/**
	 * 导出货物类型
	 */
	@GetMapping("/export-cargo-type")
	@ApiOperationSupport(order = 8)
	@Operation(summary = "导出货物类型")
	public void exportCargoType(CargoTypeVO cargoType,
								@RequestParam(required = false) String ids,
								HttpServletResponse response) {
		List<CargoTypeExportExcel> list = cargoTypeService.exportCargoType(buildExportQuery(cargoType, ids));
		ExcelUtil.export(response, "货物类型" + DateUtil.time(), "货物类型表", list, CargoTypeExportExcel.class);
	}

	/**
	 * 导出模板
	 */
	@GetMapping("/export-template")
	@ApiOperationSupport(order = 9)
	@Operation(summary = "导出模板")
	public void exportTemplate(HttpServletResponse response) {
		List<CargoTypeExcel> list = new ArrayList<>();
		ExcelUtil.export(response, "货物类型模板", "货物类型导入模板", list, CargoTypeExcel.class);
	}

	private LambdaQueryWrapper<CargoType> buildExportQuery(CargoTypeVO cargoType, String ids) {
		LambdaQueryWrapper<CargoType> queryWrapper = Wrappers.<CargoType>lambdaQuery()
			.eq(CargoType::getIsDeleted, 0)
			.orderByDesc(CargoType::getCreateTime);
		if (Func.isNotEmpty(ids)) {
			queryWrapper.in(CargoType::getId, Func.toLongList(ids));
		}
		if (Func.isNotEmpty(cargoType.getTypeLevel())) {
			queryWrapper.eq(CargoType::getTypeLevel, cargoType.getTypeLevel());
		}
		if (Func.isNotEmpty(cargoType.getCargoName())) {
			queryWrapper.like(CargoType::getCargoName, cargoType.getCargoName());
		}
		if (Func.isNotEmpty(cargoType.getCargoCode())) {
			queryWrapper.like(CargoType::getCargoCode, cargoType.getCargoCode());
		}
		if (Func.isNotEmpty(cargoType.getParentCargoCode())) {
			queryWrapper.like(CargoType::getParentCargoCode, cargoType.getParentCargoCode());
		}
		if (Func.isNotEmpty(cargoType.getParentCargoName())) {
			List<String> parentCodes = cargoTypeService.parentOptions(cargoType.getParentCargoName())
				.stream()
				.map(CargoTypeVO::getCargoCode)
				.toList();
			if (Func.isEmpty(parentCodes)) {
				queryWrapper.eq(CargoType::getParentCargoCode, "__none__");
			} else {
				queryWrapper.in(CargoType::getParentCargoCode, parentCodes);
			}
		}
		return queryWrapper;
	}

}
