package com.sunda.spmsweb.overseacontroller;


import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
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 com.alibaba.fastjson.JSONObject;
import com.sunda.spmscommon.ResponseResult;
import com.sunda.spmsorder.service.IFileOperationService;
import com.sunda.spmsoversea.dto.OverseaBatchReceiptSearchDto;
import com.sunda.spmsoversea.service.IOverseaOtherBatchReceiptService;
import com.sunda.spmsweb.util.JWTUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * <p>
 * 其他收货分批收货表头 前端控制器
 * </p>
 *
 * @author Wayne
 * @since 2023-02-10
 */
@RestController
@RequestMapping("/overseaOtherBatchReceipt")
@Api(tags = "海外仓其他收货分批收货", description = "海外仓其他收货分批收货")
public class OverseaOtherBatchReceiptController {
	
	@Autowired
	IOverseaOtherBatchReceiptService iOverseaOtherBatchReceiptService;
	
	@Autowired
	IFileOperationService iFileOperationService;
	
	@RequestMapping("/findOverseaBatchReceiptionList")
    @ApiOperation(value = "查询海外仓其他收货分批收货列表", notes = "查询海外仓其他收货分批收货列表\n" +
            "示例参数如下：\n" +
            "{\n" +
            "\t\"sapDeliveryNote\": \"0700442993\",\n" +
            "}", httpMethod = "POST")
    public ResponseResult findOverseaBatchReceiptionList(@RequestBody OverseaBatchReceiptSearchDto overseaDnSearchDTO){
        try {
            return ResponseResult.success().add("batchReceiptionList", iOverseaOtherBatchReceiptService.selectList(overseaDnSearchDTO));
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("请求数据失败").add("error", e.getMessage());
        }
    }
	
	@RequestMapping("/findOverseaBatchReceiptionDtlList")
	@ApiOperation(value = "查询海外仓其他收货分批收货行列表", notes = "查询海外仓其他收货分批收货行列表\n" +
			"示例参数如下：\n" +
			"{\n" +
			"\t\"spmsId\": \"0700442993\",\n" +
			"}", httpMethod = "POST")
	@RequiresPermissions("overseaOtherBatchReceipt-findOverseaBatchReceiptionDtlList")
	public ResponseResult findOverseaBatchReceiptionDtlList(@RequestBody OverseaBatchReceiptSearchDto overseaDnSearchDTO){
		try {
			return ResponseResult.success().add("batchReceiptionDtlList", iOverseaOtherBatchReceiptService.selectDtlList(overseaDnSearchDTO));
		}catch (Exception e){
			e.printStackTrace();
			return ResponseResult.error("请求数据失败").add("error", e.getMessage());
		}
	}
	
	@PostMapping("/saveOverseaBatchReceipt")
    @ApiOperation(value="保存其他收货分批收货数据",notes = "保存其他收货分批收货数据" +
            "{\n" +
            "  \"batchReceiptHead\": {\n" +
            "    \"uuid\": \"UUID\",\n" +
            "    \"operateTitle\": \"标题\",\n" +
            "    \"spmsId\": \"单据号\",\n" +
            "    \"werks\": \"工厂\",\n" +
            "    \"whsLocationCode\": \"仓库\",\n" +
            "    \"spmsStatus\": \"单据状态：0删除，1保存，2提交，3提交SAP，4提交SAP失败，5提交SAP成功\",\n" +
            "    \"sapRelationNumber\": \"关联的SAP凭证号\",\n" +
            "    \"sapDeliveryNoteRelation\": \"关联的SAP交货单号\",\n" +
            "    \"sapPurchaseOrder\": \"采购凭证号PO\",\n" +
            "    \"businessType\": \"出库类型(01空运人带;02本地采购;03海外转储;)\",\n" +
            "    \"remark\": \"备注\"\n" +
            "  },\n" +
            "  \"batchReceiptDtl\": [\n" +
            "    {\n" +
            "      \"uuid\": \"UUID\",\n" +
            "      \"itemNumber\": \"行号\",\n" +
            "      \"spmsId\": \"单据号\",\n" +
            "      \"materialNo\": \"物料编号\",\n" +
            "      \"basicUnit\": \"基本单位\",\n" +
            "      \"quantity\": \"应收数量\",\n" +
            "      \"actualQuantity\": \"实收数量\",\n" +
            "      \"storageInfo\": \"[{\\\"storageUuid\\\":\\\"cbd9576a4e53461fe0530101007f3e24\\\",\\\"qty\\\":3,\\\"storageNo\\\":\\\"A010101\\\",\\\"unitValue\\\":3}]\",\n" +
            "      \"costCenter\": \"行成本\",\n" +
            "      \"remark\": \"备注\",\n" +
            "      \"itemRelation\": \"关联的行号\",\n" +
            "      \"demandApplicant\": \"需求申请人\",\n" +
            "      \"demandWorkshop\": \"需求车间\",\n" +
            "      \"sapPurchaseOrder\": \"采购凭证号PO\",\n" +
            "      \"sapPurchaseOrderItem\": \"采购凭证号PO行号\"\n" +
            "    }\n" +
            "  ]\n" +
            "}", httpMethod = "POST")
	@RequiresPermissions("overseaOtherBatchReceipt-saveOverseaBatchReceipt")
    public ResponseResult saveOverseaBatchReceipt(@RequestBody JSONObject obj){
        try {
        	String userId = JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
			return iOverseaOtherBatchReceiptService.saveOverseaBatchReceipt(obj, userId);
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseResult.error("收货保存错误："+e.getMessage());
		}
    }
	
	@PostMapping("/submitOverseaBatchReceipt")
    @ApiOperation(value="提交其他收货分批收货数据",notes = "提交其他收货分批收货数据" +
            "{\n" +
            "  \"batchReceiptHead\": {\n" +
            "    \"uuid\": \"UUID\",\n" +
            "    \"operateTitle\": \"标题\",\n" +
            "    \"spmsId\": \"单据号\",\n" +
            "    \"werks\": \"工厂\",\n" +
            "    \"whsLocationCode\": \"仓库\",\n" +
            "    \"spmsStatus\": \"单据状态：0删除，1保存，2提交，3提交SAP，4提交SAP失败，5提交SAP成功\",\n" +
            "    \"sapRelationNumber\": \"关联的SAP凭证号\",\n" +
            "    \"sapDeliveryNoteRelation\": \"关联的SAP交货单号\",\n" +
            "    \"sapPurchaseOrder\": \"采购凭证号PO\",\n" +
            "    \"businessType\": \"出库类型(01空运人带;02本地采购;03海外转储;)\",\n" +
            "    \"remark\": \"备注\"\n" +
            "  },\n" +
            "  \"batchReceiptDtl\": [\n" +
            "    {\n" +
            "      \"uuid\": \"UUID\",\n" +
            "      \"itemNumber\": \"行号\",\n" +
            "      \"spmsId\": \"单据号\",\n" +
            "      \"materialNo\": \"物料编号\",\n" +
            "      \"basicUnit\": \"基本单位\",\n" +
            "      \"quantity\": \"应收数量\",\n" +
            "      \"actualQuantity\": \"实收数量\",\n" +
            "      \"storageInfo\": \"[{\\\"storageUuid\\\":\\\"cbd9576a4e53461fe0530101007f3e24\\\",\\\"qty\\\":3,\\\"storageNo\\\":\\\"A010101\\\",\\\"unitValue\\\":3}]\",\n" +
            "      \"costCenter\": \"行成本\",\n" +
            "      \"remark\": \"备注\",\n" +
            "      \"itemRelation\": \"关联的行号\",\n" +
            "      \"demandApplicant\": \"需求申请人\",\n" +
            "      \"demandWorkshop\": \"需求车间\",\n" +
            "      \"sapPurchaseOrder\": \"采购凭证号PO\",\n" +
            "      \"sapPurchaseOrderItem\": \"采购凭证号PO行号\"\n" +
            "    }\n" +
            "  ]\n" +
            "}", httpMethod = "POST")
	@RequiresPermissions("overseaOtherBatchReceipt-submitOverseaBatchReceipt")
    public ResponseResult submitOverseaBatchReceipt(@RequestBody JSONObject obj){
        try {
        	String userId = JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
			return iOverseaOtherBatchReceiptService.submitOverseaBatchReceipt(obj, userId);
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseResult.error("收货提交错误："+e.getMessage());
		}
    }
	
	@PostMapping("/submitToSap")
    @ApiOperation(value="提交SAP",notes = "提交SAP" +
            "{\n" +
            "  \"batchReceiptHead\": {\n" +
            "    \"uuid\": \"UUID\",\n" +
            "    \"operateTitle\": \"标题\",\n" +
            "    \"spmsId\": \"单据号\",\n" +
            "    \"werks\": \"工厂\",\n" +
            "    \"whsLocationCode\": \"仓库\",\n" +
            "    \"spmsStatus\": \"单据状态：0删除，1保存，2提交，3提交SAP，4提交SAP失败，5提交SAP成功\",\n" +
            "    \"postingDate\": \"过账日期\",\n" +
            "    \"sapRelationNumber\": \"关联的SAP凭证号\",\n" +
            "    \"sapDeliveryNoteRelation\": \"关联的SAP交货单号\",\n" +
            "    \"remark\": \"备注\"\n" +
            "  }\n" +
            "}", httpMethod = "POST")
	@RequiresPermissions("overseaOtherBatchReceipt-submitToSap")
    public ResponseResult submitToSap(@RequestBody JSONObject obj){
		try {
			String userId = JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
			return iOverseaOtherBatchReceiptService.submitToSap(obj, userId);
		} catch (Exception e) {
			return ResponseResult.error("提交SAP失败："+ e.getMessage());
		}
    }
	
	@PostMapping("/cancelDn")
	@ApiOperation(value="撤销",notes = "撤销" +
			"{\n" +
			"  \"batchReceiptHead\": {\n" +
			"    \"uuid\": \"UUID\",\n" +
			"    \"operateTitle\": \"标题\",\n" +
			"    \"spmsId\": \"单据号\",\n" +
			"    \"werks\": \"工厂\",\n" +
			"    \"whsLocationCode\": \"仓库\",\n" +
			"    \"spmsStatus\": \"单据状态：0删除，1保存，2提交，3提交SAP，4提交SAP失败，5提交SAP成功\",\n" +
			"    \"cancelPostingDate\": \"撤销日期\",\n" +
			"    \"sapRelationNumber\": \"关联的SAP凭证号\",\n" +
			"    \"sapDeliveryNoteRelation\": \"关联的SAP交货单号\",\n" +
			"    \"remark\": \"备注\"\n" +
			"  }\n" +
			"}", httpMethod = "POST")
	@RequiresPermissions("overseaOtherBatchReceipt-cancelDn")
	public ResponseResult cancelDn(@RequestBody JSONObject obj){
		try {
			String userId = JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
			return iOverseaOtherBatchReceiptService.cancelDn(obj, userId);
		} catch (Exception e) {
			return ResponseResult.error("撤销失败："+ e.getMessage());
		}
	}
	
	@PostMapping("/deleteReceipt")
	@ApiOperation(value="删除",notes = "删除" +
			"{\n" +
			"  \"batchReceiptHead\": {\n" +
			"    \"uuid\": \"UUID\",\n" +
			"    \"operateTitle\": \"标题\",\n" +
			"    \"spmsId\": \"单据号\",\n" +
			"    \"werks\": \"工厂\",\n" +
			"    \"whsLocationCode\": \"仓库\",\n" +
			"    \"spmsStatus\": \"单据状态：0删除，1保存，2提交，3提交SAP，4提交SAP失败，5提交SAP成功\",\n" +
			"    \"sapRelationNumber\": \"关联的SAP凭证号\",\n" +
			"    \"sapDeliveryNoteRelation\": \"关联的SAP交货单号\",\n" +
			"    \"remark\": \"备注\"\n" +
			"  }\n" +
			"}", httpMethod = "POST")
	@RequiresPermissions("overseaOtherBatchReceipt-deleteReceipt")
	public ResponseResult deleteReceipt(@RequestBody JSONObject obj){
		String userId = JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
		return iOverseaOtherBatchReceiptService.deleteReceipt(obj, userId);
	}
	
	@RequestMapping("/exportOverseaReceiptDtl")
    @ApiOperation(value = "导出分批收货明细", notes = "导出分批收货明细\n" +
            "示例参数：0700443049", httpMethod = "POST")
	@RequiresPermissions("overseaOtherBatchReceipt-exportOverseaReceiptDtl")
    public ResponseResult exportOverseaReceiptDtl(@RequestBody JSONObject obj){
        try {
        	if (!obj.containsKey("spmsId") || StringUtils.isBlank(obj.getString("spmsId"))) {
        		return ResponseResult.error("导出明细失败，所传单据号为空");
        	}
        	OverseaBatchReceiptSearchDto dto = new OverseaBatchReceiptSearchDto();
        	dto.setSpmsId(obj.getString("spmsId"));
            String filename = "oversea_Receipt_" + System.currentTimeMillis()+".xlsx";
            // 1.附件缓存路径
            String excelPath = iFileOperationService.saveOverseaReceiptDtlExcel(iOverseaOtherBatchReceiptService.selectDtlList(dto), filename);
            if (excelPath.isEmpty()){
                return ResponseResult.error("附件创建失败");
            }
            // 2.上传附件至minIO文件服务器
            String fileUrl = iFileOperationService.fileUploader(filename, excelPath);
            if (fileUrl.isEmpty()){
                return ResponseResult.error("附件上传失败:" + excelPath + "--" + fileUrl);
            }
            // 3.返回附件地址，上传OA
            return ResponseResult.success().add("fileUrl",fileUrl);
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("请求数据失败").add("error", e.getMessage());
        }
    }
}
