package com.sunda.spmsweb.wmscontroller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.sunda.spmscommon.Constans;
import com.sunda.spmscommon.ResponseResult;
import com.sunda.spmsweb.util.JWTUtil;
import com.sunda.spmswms.entity.ShelfOnTask;
import com.sunda.spmswms.service.ISapDeliveryNoteLogService;
import com.sunda.spmswms.service.IShelfOnTaskDtlService;
import com.sunda.spmswms.service.IShelfOnTaskService;
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;
import java.util.Map;

/**
 * <p>
 * 上架任务表 前端控制器
 * </p>
 *
 * @author Wayne
 * @since 2021-03-19
 */
@RestController
@RequestMapping("/shelfOnTask")
@Api(tags = "上架下架任务", description = "上架下架任务接口")
public class ShelfOnTaskController {

    @Autowired
    IShelfOnTaskService iShelfOnTaskService;
    @Autowired
    IShelfOnTaskDtlService iShelfOnTaskDtlService;

    @Autowired
    ISapDeliveryNoteLogService iSapDeliveryNoteLogService;

    @PostMapping("/completeShelfOnTask")
    @ApiOperation(value = "完成上架任务(备件货),只更新ShelfOnTask,不更新ShelfOnTaskDtl", notes = "完成上架任务(备件货),只更新ShelfOnTask,不更新ShelfOnTaskDtl\n" +
            "    \"pdaSn\": \"WebClient\",\n" +
            "    \"currentTaskStatus\": \"1\",\n" +
            "    \"deliveryNoteSap\":\"deliveryNoteSap\"\n")
    public ResponseResult completeShelfOnTask(String deliveryNoteSap, String pdaSn, String currentTaskStatus) {
        try {
            String userId = JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
            ShelfOnTask shelfOnTask = iShelfOnTaskService.completeShelfOnTask(userId, deliveryNoteSap, pdaSn, "1", currentTaskStatus, "3");
            if (null != shelfOnTask) {
                iSapDeliveryNoteLogService.insertSapDeliveryNoteLogM(deliveryNoteSap, userId, Constans.COMPLETE_SHELF_TASK);
                return ResponseResult.success().add("shelfOnTask", shelfOnTask);
            } else {
                return ResponseResult.error("Error when update Shelf On tasks");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("Error when update Shelf On tasks");
        }
    }

    @PostMapping("/completeShelfOnTaskWithDtls")
    @ApiOperation(value = "完成上架任务(备件货)，一步完成接口，更新ShelfOnTask和ShelfOnTaskDtl", notes = "完成上架任务(备件货),一步完成接口，更新ShelfOnTask和ShelfOnTaskDtl, 返回更新过后的ShelfOnTask\n" +
            "{\n" +
            "  \"shelfOnTask\": {\n" +
            "    \"pdaSn\": \"WebClient\",\n" +
            "    \"uuid\": \"shelfONTask's UUID\",\n" +
            "    \"currentTaskStatus\": \"1\",\n" +
            "    \"deliveryNoteSap\": \"deliveryNoteSap\"\n" +
            "  },\n" +
            "  \"shelfOnTaskDtls\": [\n" +
            "    {\n" +
            "      \"uuid\": \"shelfONTask UUID\",\n" +
            "      \"taskRowId\": \"10\",\n" +
            "      \"targetStorage\": \"储位UUID\",\n" +
            "      \"quantity\": 1.0,\n" +
            "    },\n" +
            "    {\n" +
            "      \"uuid\": \"shelfONTask UUID\",\n" +
            "      \"taskRowId\": \"20\",\n" +
            "      \"targetStorage\": \"储位UUID\",\n" +
            "      \"quantity\": 1.0,\n" +
            "    }\n" +
            "  ]\n" +
            "}")
    @RequiresPermissions("shelfOnTask-completeShelfOnTaskWithDtls")
    public ResponseResult completeShelfOnTaskWithDtls(@RequestBody JSONObject jsonObject) {
        try {
            String userId = JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
            JSONObject shelfOnTask = jsonObject.getJSONObject("shelfOnTask");
            JSONArray shelfOnTaskDtls = jsonObject.getJSONArray("shelfOnTaskDtls");
            if (null == shelfOnTask || shelfOnTaskDtls == null) {
                return ResponseResult.error("shelfOnTask and shelfOnTaskDtls are mandatory required, please refer to required params");
            }
            String pdaSn = shelfOnTask.getString("pdaSn");
            String uuid = shelfOnTask.getString("uuid");
            String deliveryNoteSap = shelfOnTask.getString("deliveryNoteSap");
            String currentTaskStatus = shelfOnTask.getString("currentTaskStatus");
            if (null == pdaSn || uuid == null || deliveryNoteSap == null || currentTaskStatus == null) {
                return ResponseResult.error("pdaSN,deliveryNoteSap,deliveryNoteSap and uuid are mandatory required, please refer to required params");
            }

            // 完成ShelfOnTask
            ShelfOnTask shOnTask = iShelfOnTaskService.completeShelfOnTaskByUuid(userId, uuid, pdaSn, currentTaskStatus, "3");
            if (null != shOnTask) {
                iSapDeliveryNoteLogService.insertSapDeliveryNoteLogM(deliveryNoteSap, userId, Constans.COMPLETE_SHELF_TASK);
            } else {
                return ResponseResult.error("Error when update Shelf On tasks");
            }

            // 完成ShelfOnTaskDtl
            ResponseResult res = iShelfOnTaskDtlService.completeShelfOnTaskDtlByRowID(uuid, shelfOnTaskDtls, userId);

            if (res.getCode() == 200) {
                return ResponseResult.success().add("ShelfOnTask", iShelfOnTaskService.getShelfOnTaskByUuid(uuid));
            } else {
                return res;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("Error when update Shelf On tasks");
        }
    }

    @PostMapping("/queryShelfOnTasks")
    @ApiOperation(value = "根据条件查询上、下架任务",notes = "根据条件查询上、下架任务" +
            "{\n" +
            "  \"werks\": \"CN01\",\n" +
            "  \"whsLocationCode\": \"1061\",\n" +
            "  \"beginDate\": \"20210512\",\n" +
            "  \"endDate\": \"20210530\",\n" +
            "  \"taskStatus\": \"3\",\n" +
            "  \"taskType\": \"1\",\n" +
            "  \"xQuery\": {\n" +
            "    \"documentType\": \"SAPDN\",\n" +
            "    \"documentSpmsId\": \"1180066354\"\n" +
            "  }\n" +
            "} \n")
    @RequiresPermissions("shelfOnTask-queryShelfOnTasks")
    public ResponseResult queryShelfOnTasks(@RequestBody JSONObject queryObj) {
        if (null == queryObj) {
            return ResponseResult.error();
        }
        return iShelfOnTaskService.queryShelfOnTasks(queryObj);
    }

    @PostMapping("/getShelfOnTask")
    @ApiOperation(value = "johnny 获得上架下架任务", notes = "johnny 获得上架任务\n" +
            "任务状态码值：1待上架；2上架中；3已完成；4待下架；5下架中；6出库待下架；7出库下架中；只有完成状态才更新储位库存。\n" +
            "请求参数示例：werks = CN01；\n仓库地点代码可传多个，逗号分割：whsLocationCode = 1011,1061；\n任务状态传空默认查待办任务，状态1，2，4，5，6，7.传值状态逗号分割，示例：taskStatus = 3,4,5；\n" +
            "其他参数可选输入。\n")
    public ResponseResult getShelfOnTask(String taskId, String createUserId, String werks, String whsLocationCode, String taskStatus, String updateUsername, String deliveryNoteSap, String pdaSN, String taskType) {
        List<Map<String, Object>> list = iShelfOnTaskService.getShelfOnTask(taskId, createUserId, werks, whsLocationCode, taskStatus, updateUsername, deliveryNoteSap, pdaSN, taskType);
        return ResponseResult.success().add("ShelfOnTask", list);
    }

    @GetMapping("getShelfOnTaskByUuid")
    @ApiOperation(value = "根据上架下架任务Uuid获取详情", notes = "根据上架下架任务Uuid任务详情" +
            "/shelfOnTask/getShelfOnTaskByUuid?uuid=please your uuid here\n" +
            "uuid = 3e74fd02509f4e0b900c6c5433bc19b7")
    @RequiresPermissions("shelfOnTask-getShelfOnTaskByUuid")
    public ResponseResult getShelfOnTaskByUuid(@RequestParam String uuid) {
        if (StringUtils.isEmpty(uuid)) {
            return ResponseResult.error("ShelfOnTask UUID is mandatory required");
        }

        Map<String, Object> shelfOnTaskObj = iShelfOnTaskService.getShelfOnTaskByUuid(uuid);

        if (null == shelfOnTaskObj) {
            return ResponseResult.error("The UUID:  " + uuid + "is not exist");
        }

        return ResponseResult.success().add("ShelfOnTask", shelfOnTaskObj);
    }

    @PostMapping("/updateShelfOnTask")
    @ApiOperation(value = "更新上架任务状态", notes = "更新上架任务状态")
    public ResponseResult updateShelfOnTask(String uuid, String currentTaskStatus, String targetTaskStatus) {
        if (StringUtils.isEmpty(uuid) || StringUtils.isEmpty(currentTaskStatus) || StringUtils.isEmpty(targetTaskStatus)) {
            return ResponseResult.error("uuid and taskStatus is mandatory required");
        }

        return ResponseResult.success().add("ShelfOnTask", iShelfOnTaskService.updateShelfOnTask(uuid, currentTaskStatus, targetTaskStatus));
    }

    @PostMapping("/tempSaveShelfOnTaskDtls")
    @ApiOperation(value = "保存下架任务过程，不计算库存", notes = "保存下架任务过程。更新下架任务表头状态为 7下架中，更新下架任务明细，不计算储位库存，不计算仓库库存。\n" +
            "{\n" +
            "\t\"shelfOnTask\": {\n" +
            "\t\t\"uuid\": \"3e74fd02509f4e0b900c6c5433bc19b7\",\n" +
            "\t\t\"currentStatus\": \"6\",\n" +
            "\t\t\"targetStatus\": \"7\",\n" +
            "\t\t\"userId\": \"999947\",\n" +
            "\t\t\"pdaSN\": \"1234567890\"\n" +
            "\t},\n" +
            "\t\"shelfOnTaskDtls\": [{\n" +
            "\t\t\"uuid\": \"3e74fd02509f4e0b900c6c5433bc19b7\",\n" +
            "\t\t\"taskRowId\": 10,\n" +
            "\t\t\"boxNote\": \"TEST-1009-0101\",\n" +
            "\t\t\"actualOperateQty\": \"1\",\n" +
            "\t\t\"targetStorage\": \"b95946ac1dab42b79ade3438acb0b513\",\n" +
            "\t\t\"unplanned\": \"\"\n" +
            "\t}, {\n" +
            "\t\t\"uuid\": \"3e74fd02509f4e0b900c6c5433bc19b7\",\n" +
            "\t\t\"taskRowId\": 20,\n" +
            "\t\t\"boxNote\": \"TEST-1009-0102\",\n" +
            "\t\t\"actualOperateQty\": \"1\",\n" +
            "\t\t\"targetStorage\": \"b95946ac1dab42b79ade3438acb0b513\",\n" +
            "\t\t\"unplanned\": \"\"\n" +
            "\t}]\n" +
            "}")
    public ResponseResult tempSaveShelfOnTaskDtls(@RequestBody JSONObject jsonObject) {
        try {
            String userId = JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
            int resp = iShelfOnTaskService.tempSaveShelfOnTaskDtls(userId, jsonObject);
            if (resp > 0) {
                return ResponseResult.success("下架任务表头及明细保存成功");
            } else if (resp == -1) {
                return ResponseResult.error("请求参数错误请重试");
            } else {
                return ResponseResult.error("更新下架任务表头失败");
            }
        } catch (Exception e) {
            return ResponseResult.error("更新下架任务表头失败").add("error", e.getMessage());
        }


    }


}
