/**
 * 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>
 * Author: Chill Zhuang (bladejava@qq.com)
 */
package org.springblade.transport.controller;

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 lombok.AllArgsConstructor;
import org.springblade.common.excel.ImportFailureExcelUtil;
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.WaybillExcel;
import org.springblade.transport.excel.WaybillImportBatchExcel;
import org.springblade.transport.pojo.entity.ContractManage;
import org.springblade.transport.pojo.entity.CustomerArchive;
import org.springblade.transport.pojo.entity.ProjectApply;
import org.springblade.transport.pojo.entity.TransportPlan;
import org.springblade.transport.pojo.entity.Waybill;
import org.springblade.transport.pojo.vo.BusinessRemoveResultVO;
import org.springblade.transport.pojo.vo.WaybillVO;
import org.springblade.transport.service.IContractManageService;
import org.springblade.transport.service.ICustomerArchiveService;
import org.springblade.transport.service.IProjectApplyService;
import org.springblade.transport.service.ITransportPlanService;
import org.springblade.transport.service.IWaybillService;
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.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 运单管理 控制器
 *
 * @author Chill
 */
@RestController
@AllArgsConstructor
@PreAuth(menu = "waybill_manage")
@RequestMapping("/waybill-manage")
@Tag(name = "运单管理", description = "运单管理")
public class WaybillController extends BladeController {

	private final IWaybillService waybillService;
	private final IProjectApplyService projectApplyService;
	private final IContractManageService contractManageService;
	private final ICustomerArchiveService customerArchiveService;
	private final ITransportPlanService transportPlanService;

	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@Operation(summary = "详情", description = "传入id")
	public R<WaybillVO> detail(@Parameter(description = "主键", required = true) @RequestParam Long id) {
		return R.data(waybillService.detail(id));
	}

	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@Operation(summary = "分页", description = "传入waybill")
	public R<IPage<WaybillVO>> list(WaybillVO waybill, Query query) {
		return R.data(waybillService.selectWaybillPage(Condition.getPage(query), waybill));
	}

	@GetMapping("/import-batch/options")
	@ApiOperationSupport(order = 3)
	@Operation(summary = "运单批量导入选项")
	public R<Map<String, List<Map<String, Object>>>> importBatchOptions() {
		Map<String, List<Map<String, Object>>> options = new LinkedHashMap<>();
		options.put("projects", projectApplyService.list().stream()
			.filter(project -> "approved".equals(project.getApprovalStatus()))
			.map(project -> option(project.getId(), "projectName", project.getProjectName(), "customerName", project.getCustomerNames()))
			.toList());
		options.put("contracts", contractManageService.list().stream()
			.filter(contract -> "approved".equals(contract.getApprovalStatus()))
			.map(contract -> option(contract.getId(), "contractName", contract.getContractName(), "projectId", contract.getProjectId()))
			.toList());
		options.put("carriers", customerArchiveService.list().stream()
			.filter(customer -> "承运商".equals(customer.getCustomerType()) && Integer.valueOf(1).equals(customer.getStatus()))
			.map(customer -> option(customer.getId(), "name", customer.getFullName(), null, null))
			.toList());
		options.put("creators", new ArrayList<>());
		options.put("plans", transportPlanService.list().stream()
			.map(plan -> option(plan.getId(), "planName", plan.getPlanName(), "projectId", plan.getProjectId()))
			.toList());
		return R.data(options);
	}

	@PostMapping("/submit")
	@ApiOperationSupport(order = 4)
	@Operation(summary = "新增或修改", description = "传入waybill")
	public R submit(@RequestBody Waybill waybill) {
		return R.status(waybillService.submit(waybill));
	}

	@PostMapping("/remove")
	@ApiOperationSupport(order = 5)
	@Operation(summary = "逻辑删除", description = "传入ids")
	public R<BusinessRemoveResultVO> remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) {
		return R.data(waybillService.removeWaybill(ids));
	}

	@GetMapping("/export-waybill-manage")
	@ApiOperationSupport(order = 6)
	@Operation(summary = "导出运单管理")
	public void exportWaybill(WaybillVO waybill, @RequestParam(required = false) String ids, HttpServletResponse response) {
		List<WaybillExcel> list = waybillService.exportWaybill(waybill, ids);
		ExcelUtil.export(response, "运单管理" + DateUtil.time(), "运单管理", list, WaybillExcel.class);
	}

	@PostMapping("/import-waybill-manage")
	@ApiOperationSupport(order = 7)
	@Operation(summary = "导入运单管理", description = "传入excel")
	public R importWaybill(MultipartFile file, HttpServletResponse response) {
		List<WaybillExcel> failureList = waybillService.importWaybill(ExcelUtil.read(file, WaybillExcel.class));
		if (Func.isNotEmpty(failureList)) {
			ImportFailureExcelUtil.export(response, "运单管理导入失败明细" + DateUtil.time(), "导入失败明细", failureList, WaybillExcel.class);
			return null;
		}
		return R.success("导入数据成功");
	}

	@GetMapping("/export-template")
	@ApiOperationSupport(order = 8)
	@Operation(summary = "导出模板")
	public void exportTemplate(HttpServletResponse response) {
		ExcelUtil.export(response, "运单管理模板", "运单管理导入模板", new ArrayList<WaybillExcel>(), WaybillExcel.class);
	}

	@GetMapping("/import-batch/export-template")
	@ApiOperationSupport(order = 9)
	@Operation(summary = "导出运单批量导入模板")
	public void exportImportBatchTemplate(HttpServletResponse response) {
		ExcelUtil.export(response, "运单批量导入模板", "运单批量导入模板", new ArrayList<WaybillImportBatchExcel>(), WaybillImportBatchExcel.class);
	}

	@PostMapping("/copy")
	@ApiOperationSupport(order = 10)
	@Operation(summary = "复制", description = "传入id")
	public R<WaybillVO> copy(@Parameter(description = "主键", required = true) @RequestParam Long id) {
		return R.data(waybillService.copy(id));
	}

	@PostMapping("/cancel")
	@ApiOperationSupport(order = 11)
	@Operation(summary = "取消", description = "传入id")
	public R cancel(@Parameter(description = "主键", required = true) @RequestParam Long id) {
		return R.status(waybillService.cancel(id));
	}

	@PostMapping("/reassign")
	@ApiOperationSupport(order = 12)
	@Operation(summary = "重新派单", description = "传入id")
	public R reassign(@Parameter(description = "主键", required = true) @RequestParam Long id) {
		return R.status(waybillService.reassign(id));
	}

	@PostMapping("/complete")
	@ApiOperationSupport(order = 13)
	@Operation(summary = "完成", description = "传入id")
	public R complete(@Parameter(description = "主键", required = true) @RequestParam Long id) {
		return R.status(waybillService.complete(id));
	}

	@PostMapping("/batch-complete")
	@ApiOperationSupport(order = 14)
	@Operation(summary = "批量完成", description = "传入ids")
	public R<BusinessRemoveResultVO> batchComplete(@Parameter(description = "主键集合", required = true) @RequestParam String ids) {
		return R.data(waybillService.batchComplete(ids));
	}

	private Map<String, Object> option(Long id, String nameKey, String name, String extraKey, Object extraValue) {
		Map<String, Object> option = new LinkedHashMap<>();
		option.put("id", id);
		option.put(nameKey, name);
		if (Func.isNotEmpty(extraKey)) {
			option.put(extraKey, extraValue);
		}
		return option;
	}

}
