package com.sunda.spmsweb.overseacontroller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.sunda.spmscommon.ResponseResult;
import com.sunda.spmsorder.entity.OrderKeyValueConfig;
import com.sunda.spmsorder.service.IOrderKeyValueConfigService;
import com.sunda.spmsoversea.dto.OverseaInvCheckActionSearchDTO;
import com.sunda.spmsoversea.service.IOverseaInvCheckActionDtlService;
import com.sunda.spmsoversea.service.IOverseaInvCheckActionService;
import com.sunda.spmsoversea.service.IOverseaInvCheckService;
import com.sunda.spmsuser.entity.SpmsUser;
import com.sunda.spmsuser.service.ISpmsUserService;
import com.sunda.spmsweb.util.JWTUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.*;

import java.util.List;


/**
 * <p>
 * 仓库盘盈盘亏 前端控制器
 * </p>
 *
 * @author Wayne
 * @since 2021-05-10
 */
@RestController
@RequestMapping("/ovinvcheckac")
@Api(tags = "仓库盘点盘盈盘亏接口", description = "仓库盘点盘盈盘亏接口")
public class OverseaInvCheckActionController {

    @Autowired
    IOverseaInvCheckActionService iOverseaInvCheckActionService;

    @Autowired
    IOverseaInvCheckActionDtlService iOverseaInvCheckActionDtlService;

    @Autowired
    IOverseaInvCheckService iOverseaInvCheckService;
    @Autowired
    ISpmsUserService iSpmsUserService;
    @Autowired
    IOrderKeyValueConfigService iOrderKeyValueConfigService;

    @PostMapping("/getInvCheckAcList")
    @ApiOperation(value="获取库存盘点盘盈盘亏列表",notes="获取库存盘点盘盈盘亏列表" +
            "{\n" +
            "  \"werks\":[\"CN01\",\"CM31\"],\n" +
            "  \"whsLocationCode\":[\"1011\",\"1061\"],\n" +
            "  \"inventoryCheckCategory\":\"1\", //盘点类别 1-日常盘点 2-月度盘点 3-动态盘点 4-其它盘点\n" +
            "  \"createDate\":[\"20210401\",\"20210501\"],\n" +
            "  \"inventoryCheckId\":\"CN01-20210511-INV\",\n" +
            "  \"spmsId\":\"CN01-1061-20210708-002\",\n" +
            "  \"spmsStatus\":\"1\", //任务状态：1-待盘点；2-盘点中；3-复盘中；4-处理中；5-关闭(完成)\n" +
            "}", httpMethod = "POST")
    @RequiresPermissions("ovinvcheckac-getInvCheckAcList")
    public ResponseResult getInvCheckAcList(@RequestBody JSONObject InvCheckFilter){
        return iOverseaInvCheckActionService.getInvCheckAcList(InvCheckFilter);
    }

    @GetMapping("/getInvCheckAcWithDtl")
    @ApiOperation(value = "根据uuid获取盘点单据详情数据", notes = "根据uuid获取盘点单据详情数据")
    @RequiresPermissions("ovinvcheckac-getInvCheckAcWithDtl")
    public ResponseResult getInvCheckAcWithDtl(@RequestParam(required = true) String uuid) {
        try {
            return iOverseaInvCheckActionService.getInvCheckAcWithDtl(uuid);
        }catch (Exception e){
            return ResponseResult.error("请求数据失败").add("error", e.getMessage());
        }
    }

    @PostMapping("/updateInvCheckAc")
    @ApiOperation(value="新建或更新盘盈盘亏单",notes = "新建或更新盘盈盘亏单" +
            "{\n" +
            "  \"invCheckAc\": {\n" +
            "    \"uuid\": \"盘盈盘亏任务UUID\",\n" +
            "    \"spmsId\": \"盘盈盘亏单号\",\n" +
            "    \"inventoryActionType\": \"盘盈盘亏类别 1-盘盈 2-盘亏\",\n" +
            "    \"werks\": \"工厂\",\n" +
            "    \"whsLocationCode\": \"仓库\",\n" +
            "    \"inventoryCheckId\": \"盘点单号\",\n" +
            "    \"inventoryCheckResult\": \"盘点结果 1-账实相符 2-盘盈 3-盘亏 4-盘盈盘亏\",\n" +
            "    \"inventoryCheckCategory\": \"盘点类别 1-日常盘点 2-月度盘点 3-动态盘点 4-其它盘点\",\n" +
            "    \"inventoryCheckMold\": \"盘点类型 1-明盘 2-暗盘\",\n" +
            "    \"createDate\": \"创建日期\",\n" +
            "    \"spmsStatus\": \"任务状态：1-草稿 2-审批中 3-审批通过(待上传SAP) 4-关闭(完成) 5-审批不通过\",\n" +
            "    \"requester\": \"创建人工号\",\n" +
            "    \"operator\": \"盘点人\",\n" +
            "    \"reviewer\": \"复核人\",\n" +
            "    \"approver\": \"审批人\",\n" +
            "    \"createTime\": \"创建时间\",\n" +
            "    \"updateUsername\": \"更新人\",\n" +
            "    \"updateTime\": \"更新时间\",\n" +
            "    \"justification\": \"申请原因\",\n" +
            "    \"remarks\":\"备注\",\n" +
            "    \"currentStatus\":\"1\",\n" +
            "    \"targetStatus\":\"2\"\n" +
            "  },\n" +
            "  \"invCheckAcDtls\": [\n" +
            "    {\n" +
            "      \"uuid\": \"盘盈盘亏任务UUID\",\n" +
            "      \"taskRowId\": \"盘盈盘亏任务行号\",\n" +
            "      \"materialNo\": \"物料编号\",\n" +
            "      \"inventoryQuantity\": \"库存数量\",\n" +
            "      \"checkQuantity\": \"实盘数量\",\n" +
            "      \"discrepancy\": \"差异数量\",\n" +
            "      \"basicUnit\": \"基本单位\",\n" +
            "      \"storageUuid\": \"储位UUID\",\n" +
            "      \"remarks\": \"备注\",\n" +
            "    }\n" +
            "  ]\n" +
            "}", httpMethod = "POST")
    @RequiresPermissions("ovinvcheckac-updateInvCheckAc")
    public ResponseResult updateInvCheckAc(@RequestBody JSONObject InvCheckDoc){
        String userId = JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
        try {
            return iOverseaInvCheckActionService.updateInvCheckAc(InvCheckDoc, userId);
        }catch (Exception e){
            return ResponseResult.error("请求数据失败").add("error", e.getMessage());
        }
    }

    @PostMapping("/invAcSaveAndSap")
    @ApiOperation(value="保存盘盈盘亏单，并且发送到SAP",notes = "保存盘盈盘亏单，并且发送到SAP" +
            "{\n" +
            "    \"uuid\": \"盘盈盘亏任务UUID\",\n" +
            "    \"inventoryCheckId\": \"盘盈盘亏任务所关联的盘点单spmsID,用于检查关联的盘点单据是否可以关闭\",\n" +
            "    \"postingDate\":\"过帐日期\",\n" +
            "    \"currentStatus\":\"5\",\n" +
            "    \"remarks\":\"备注\",\n" +
            "}\n" +
            "单据执行过程：由5提交成功状态7,失败为6；" +
            "状态首次由5提交SAP时计算库存，重新提交6不计算库存；", httpMethod = "POST")
    @RequiresPermissions("ovinvcheckac-invAcSaveAndSap")
    public ResponseResult invAcSaveAndSap(@RequestBody JSONObject invCheckDoc){
        
        try {
            String userId = JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
            String uuid=invCheckDoc.getString("uuid");
            String postingDate=invCheckDoc.getString("postingDate");
            String currentStatus=invCheckDoc.getString("currentStatus");
            String inventoryCheckId=invCheckDoc.getString("inventoryCheckId");
            if(StringUtils.isEmpty(uuid) || StringUtils.isEmpty(postingDate) || StringUtils.isEmpty(currentStatus) || StringUtils.isEmpty(inventoryCheckId)){
                return ResponseResult.error("inventoryCheckId,currentStatus,UUID or Posting Date is blank");
            }
            String remarks = invCheckDoc.getString("remarks");
            ResponseResult resp = iOverseaInvCheckActionService.getInventoryCheckActionToSap(uuid, postingDate, userId, remarks, currentStatus);
            if (null != resp && resp.getCode() == 200){
                /**检查并关闭盘点单*/
                ResponseResult invChkRes=iOverseaInvCheckService.checkAndCloseInvChk(inventoryCheckId);
                if(invChkRes.getCode()==200){
                    return resp.add("inventoryCheck",invChkRes.getObject("inventoryCheck",Object.class));
                }
            }
            return resp;
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("Failed when update or send data to SAP");
        }

    }

    @PostMapping("/getICALogs")
    @ApiOperation(value="获取盘盈盘亏操作日志",notes="获取盘盈盘亏关联日志\n" +
            "示例 uuid = 2bd35b830798445991e4f6c3adc3bde4 或 b860d9902dd84760af7ab62bf7b7e7eb ", httpMethod = "POST")
    public ResponseResult getICALogs(String uuid){
        return ResponseResult.success().add("inventoryCheckActionLogs", iOverseaInvCheckActionService.getICALogs(uuid));
    }

    
    @PostMapping("/invAcSaveAndOA")
    @ApiOperation(value="保存盘盈盘亏单，提交OA审批",notes = "保存盘盈盘亏单，提交OA审批" +
            "{\n" +
            "  \"invCheckAc\": {\n" +
            "    \"uuid\": \"盘盈盘亏任务UUID\",\n" +
            "    \"remarks\":\"备注\",\n" +
            "    \"postingDate\":\"过帐日期\",\n" +
            "    \"submitOaDate\":\"提交OA日期\",\n" +
            "  },\n" +
            "  \"invCheckAcDtls\": [\n" +
            "    {\n" +
            "      \"uuid\": \"盘盈盘亏任务UUID\",\n" +
            "      \"taskRowId\": \"盘盈盘亏任务行号\",\n" +
            "      \"remarks\": \"备注\",\n" +
            "    }\n" +
            "  ]\n" +
            "}\n" +
            "单据执行过程：提交成功状态2,失败为3；", httpMethod = "POST")
    @RequiresPermissions("ovinvcheckac-invAcSaveAndOA")
    public ResponseResult invAcSaveAndOA(@RequestBody JSONObject InvCheckDoc){
        try {
            String userId = JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
            SpmsUser spmsUser = iSpmsUserService.getByUserId(userId);
            JSONObject invCheckAc = InvCheckDoc.containsKey("invCheckAc") ? InvCheckDoc.getJSONObject("invCheckAc") : null;
            JSONArray invCheckAcDtls = InvCheckDoc.containsKey("invCheckAcDtls") ? InvCheckDoc.getJSONArray("invCheckAcDtls") : null;
            if (null == invCheckAc || null == invCheckAcDtls) {
                return ResponseResult.error("Error, invCheckAc or invCheckAcDtls missed from the parameters, please double check");
            }
            List<OrderKeyValueConfig> orderKeyValueConfigs = iOrderKeyValueConfigService.getByFieldKey("oaConfig");
            boolean newOa = false;
            if(orderKeyValueConfigs!=null && orderKeyValueConfigs.size()>0){
                String oaConfig = orderKeyValueConfigs.get(0).getKeyCode();
                if("0".equals(oaConfig)){//0:启用新OA接口
                    newOa = true;
                }
            }
            ResponseResult resp=iOverseaInvCheckActionService.overseaInvChkAcToOa(invCheckAc,spmsUser,invCheckAcDtls,newOa);
            return resp;
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("Failed when update or send data to SAP");
        }

    }

    @RequestMapping("/getOverseaInvCheckAction")
    @ApiOperation(value = "获取海外仓盘盈盘亏任务带明细不分页报表", notes = "获取海外仓盘盈盘亏任务带明细不分页报表\n" +
            "示例参数：\n" +
            "{\n" +
            "\t\"beginDate\": \"2021-12-01\",\n" +
            "\t\"endDate\": \"2022-01-20\",\n" +
            "\t\"inventoryActionType\": \"702\",\n" +
            "\t\"inventoryCheckCategory\": \"\",\n" +
            "\t\"inventoryCheckMold\": \"\",\n" +
            "\t\"spmsStatus\": \"\",\n" +
            "\t\"storageArea\": \"\",\n" +
            "\t\"werks\": \"TF01\",\n" +
            "\t\"whsLocationCode\": \"2002\"\n" +
            "}", httpMethod = "POST")
    @RequiresPermissions("ovinvcheckac-getOverseaInvCheckAction")
    public ResponseResult getOverseaInvCheckAction(@RequestBody OverseaInvCheckActionSearchDTO overseaInvCheckActionSearchDTO){
        try {
            String userId = JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
            return iOverseaInvCheckActionService.getOverseaInvCheckAction(overseaInvCheckActionSearchDTO);
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("请求数据失败").add("error", e.getMessage());
        }
    }
    
    @RequestMapping("/getOverseaInvCheckHead")
    @ApiOperation(value = "获取海外盘盈盘亏详情", notes = "获取海外盘盈盘亏详情\n" +
            "示例参数：\n" +
            "spmsId = TF01-2002-20211221-001 \n" +
            "\n", httpMethod = "POST")
    public ResponseResult getOverseaInvCheckHead(String spmsId){
        try {
            return iOverseaInvCheckActionService.getOverseaInvCheckHead(spmsId);
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("请求数据失败").add("error", e.getMessage());
        }
    }
    
    @PostMapping("/cancelOverseaInvCheck")
    @ApiOperation(value="撤销盘亏盘盈单",notes = "撤销盘亏盘盈单" +
            "{\n" +
            "    \"uuid\": \"盘盈盘亏任务UUID\"\n" +
            "}\n", httpMethod = "POST")
    public ResponseResult cancelOverseaInvCheck(@RequestBody JSONObject invCheckDoc){
        try {
            String userId = JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
            ResponseResult resp = iOverseaInvCheckActionService.cancel(userId, invCheckDoc);
            return resp;
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("Failed when update or send data to SAP"+e.getLocalizedMessage());
        }

    }
    
    @PostMapping("/closeOverseaInvCheck")
    @ApiOperation(value="关闭盘亏盘盈单",notes = "关闭盘亏盘盈单" +
    		"{\n" +
    		"    \"uuid\": \"盘盈盘亏任务UUID\" ,\n" +
    		"    \"cancelReason\": \"关闭原因\"\n" +
    		"}\n", httpMethod = "POST")
    public ResponseResult closeOverseaInvCheck(@RequestBody JSONObject invCheckDoc){
    	try {
    		String userId = JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
    		ResponseResult resp = iOverseaInvCheckActionService.closeInvCheck(userId, invCheckDoc);
    		return resp;
    	}catch (Exception e){
    		e.printStackTrace();
    		return ResponseResult.error("Failed when close OverseaInvCheck："+e.getMessage());
    	}
    	
    }

}
