package com.youchain.appupdate.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.youchain.appupdate.inputJson.ContainerIn;
import com.youchain.appupdate.service.ContainerService;
import com.youchain.basicdata.domain.Item;
import com.youchain.basicdata.domain.Point;
import com.youchain.basicdata.domain.Stock;
import com.youchain.basicdata.service.BoxService;
import com.youchain.basicdata.service.ItemService;
import com.youchain.basicdata.service.PointService;
import com.youchain.basicdata.service.StockService;
import com.youchain.businessdata.domain.Inventory;
import com.youchain.businessdata.domain.Task;
import com.youchain.businessdata.service.*;
import com.youchain.businessdata.service.impl.InventoryLogServiceImpl;
import com.youchain.modules.system.service.DictService;
import com.youchain.utils.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class ContainerServiceImpl implements ContainerService {
    private final ItemService itemService;
    private final PointService pointService;
    private final StockService stockService;
    private final DictService dictService;
    private final AgvTaskService agvTaskService;
    private final InventoryService inventoryService;
    private final InventoryLogServiceImpl invLogImpl;
    private final BoxService boxService;

    @Override
    public Boolean ContainerOut(ContainerIn containerIn) {
        String containerCode = containerIn.getContainerCode();
        String position = containerIn.getPosition();
        Stock stock = stockService.findByCode(containerCode, null);
        if (stock == null) {
            log.error("请扫描正确容器，操作失败！");
            return false;
        }
        Point point = pointService.findByCode(position, null, null, null, null,null);
        if (point == null) {
            log.error("请扫描正确点位，操作失败！");
            return false;
        }
        //出场查询是否有库存 有则出库存，没有则直接出场
        List<Inventory> inventoryList = inventoryService.queryInventory(stock);
        for (Inventory inventory : inventoryList) {
//            if(inventory.getQueuedQty()>0){
//                return new ResponseEntity<>(ApiResult.fail(BAD_REQUEST.value(), "容器对应库存锁定", ""), HttpStatus.BAD_REQUEST);
//            }
            invLogImpl.storeInventoryLog(BizStatus.INVENTORY_ADJUST, BizStatus.REDUCE, "容器出场", inventory.getItemKey(), inventory.getPoint(),
                    null, inventory.getStock(), null, inventory.getQuantity(), inventory.getQuantity(), null, null, inventory.getId(), "容器出场库存扣减");
            inventory.setQuantity(0d);
            inventory.setQueuedQty(0d);
            inventoryService.update(inventory);
        }
        //调用容器出场接口
        String jsonObject = "";

        String agv_on_off = "OFF";
        agv_on_off = dictService.getDictDescription("agv_on_off").getDescription();
        String code = "0";
        String message = null;
        if (agv_on_off.equals("ON")) {
            String resultJson = HttpPostUtil.sendPostReq(UrlApi.containerOut(), jsonObject.toString());
//            String resultJson = "{\n" +
//                    "  \"data\": null,\n" +
//                    "  \"code\": 0,\n" +
//                    "  \"message\": null,\n" +
//                    "  \"success\": true\n" +
//                    "}";
            JSONObject resulObject = JSON.parseObject(resultJson);
            code = resulObject.getString("code") == null ? "" : resulObject.getString("code");
            message = resulObject.getString("message") == null ? "" : resulObject.getString("message");
        }
        if (code.equals("0")) {
            stock.setPoint(null);
            stock.setStatus(BaseStatus.FREE);
            stockService.update(stock);
            point.setStatus(BaseStatus.FREE);
            pointService.update(point);
        } else {
            log.error("出场失败{}", message);
            return false;
        }

        return true;
    }

    @Override
    public Boolean ContainerIn(ContainerIn containerIn) {
        String containerCode = containerIn.getContainerCode();//容器号
        String position = containerIn.getPosition();//点位
        //int checkCode = containerIn.getCheckCode();
        Stock stock = stockService.findByCode(containerCode, null);
        if (stock == null) {
            log.error("请扫描正确容器，操作失败!");
            return false;
        }
        Point point = pointService.findByCode(position, null, null, null, null,null);
        if (point == null) {
            log.error("请扫描正确点位，操作失败！");
            return false;
        }
        String areaName = point.getArea().getName();//库区名称
        String code = "0";
        String message = null;
        String agv_on_off = "OFF";
        String jsonObject = "";
        agv_on_off = dictService.getDictDescription("agv_on_off") == null ? "OFF" : dictService.getDictDescription("agv_on_off").getDescription();
        //空车入场和满车入场
        if (areaName.equals(AreaNameDic.CPRKQ) || areaName.equals(AreaNameDic.FBQ)) {
            //是否调用AGV
            if (agv_on_off.equals("ON")) {
                //调用容器入场接口
                String resultJson = HttpPostUtil.sendPostReq(UrlApi.containerIn(), jsonObject.toString());
                JSONObject resulObject = JSON.parseObject(resultJson);
                code = resulObject.getString("code") == null ? "" : resulObject.getString("code");
                message = resulObject.getString("message") == null ? "" : resulObject.getString("message");
            }
            //空车入场
            if (code.equals("0")) {
                stock.setPoint(point);
                stockService.update(stock);
                point.setStatus(BaseStatus.USED);
                pointService.update(point);
            } else {
                log.error("容器入场失败:{}", message);
                return false;
            }
        } else if (areaName.equals(AreaNameDic.DJQ) || areaName.equals(AreaNameDic.XJQ)) {
            //满车入场，需要物料号且生成库存信息
            String itemCode = containerIn.getItemCode();//物料
            Item item = itemService.existItem(itemCode);
            if (item == null) {
                log.error("{}区入场请物料编号!", areaName);
                return false;
            }
            if ((point.getDescription() != null && !item.getGoodType().equals(point.getDescription()))) {
                log.error("物料类型和点位对应的类型不匹配!");
                return false;
            }
            //是否调用AGV
            if (agv_on_off.equals("ON")) {
                //调用容器入场接口
                String resultJson = HttpPostUtil.sendPostReq(UrlApi.containerIn(), jsonObject.toString());
                JSONObject resulObject = JSON.parseObject(resultJson);
                code = resulObject.getString("code") == null ? "" : resulObject.getString("code");
                message = resulObject.getString("message") == null ? "" : resulObject.getString("message");
            }
            if (code.equals("0")) {
                List<Inventory> inventoryList = inventoryService.queryInventory(stock);
                for (Inventory inventory : inventoryList) {
                    Long[] ids = new Long[1];
                    ids[0] = inventory.getId();
                    inventoryService.deleteAll(ids);
                }
                Task task = boxService.createTask(item, stock, point);
                Inventory inventory = inventoryService.getInventory(task.getItemKey(), task.getDstPoint(), task.getSrcStock(), task.getDept(), BizStatus.RECEIVING_UP);
                inventory.addQty(inventory, task.getPlanQty());
                inventoryService.update(inventory);
                stock.setStatus(BaseStatus.USED);
                stock.setPoint(inventory.getPoint());
                stockService.update(stock);
                point.setStatus(BaseStatus.USED);
                pointService.update(point);
            } else {
                log.error("失败{}", message);
                return false;
            }
        } else {
            log.error("{}不能入场", areaName);
            return false;
        }
        return true;
    }
}
