package com.youchain.appupdate.rest;

import com.youchain.annotation.AnonymousAccess;
import com.youchain.annotation.Log;
import com.youchain.appupdate.inputJson.LineScanStock;
import com.youchain.appupdate.inputJson.Mo;
import com.youchain.appupdate.inputJson.SmallCallStock;
import com.youchain.basicdata.domain.Box;
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.basicdata.service.dto.BoxDto;
import com.youchain.businessdata.domain.*;
import com.youchain.businessdata.service.*;
import com.youchain.exception.handler.ApiResult;
import com.youchain.modules.system.service.DictService;
import com.youchain.utils.BaseStatus;
import com.youchain.utils.BizStatus;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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.RestController;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static org.springframework.http.HttpStatus.BAD_REQUEST;
import static org.springframework.http.HttpStatus.OK;


@RestController
@RequiredArgsConstructor
@Api(tags = "小件场景管理")
@RequestMapping("/api/appSmall")
@Slf4j
public class SmallAppController {

    private final BoxService boxService;

    private final ItemService itemService;

    private final StockService stockService;

    private final PointService pointService;

    private final AsnDetailService asnDetailService;

    private final PickDetailService pickDetailService;

    private final ItemKeyService itemKeyService;

    private final TaskService taskService;

    private final AgvTaskService agvTaskService;

    private final InventoryService inventoryService;

    @PostMapping("/bindStock")
    @Log("满料入库-小件")
    @ApiOperation("满料入库-小件")
    @AnonymousAccess
    public ResponseEntity<Object> bindStock(@RequestBody Mo mo) {
        /*String Mo = mo.getMo();//MO票
        String stockCode = mo.getStockCode();//料箱号
        //MO票解析规则 LB]A0008157]231129]2238100000506]20]230729283171]]
        String[] str = Mo.split("]");
        if (str.length <= 5) {
            return new ResponseEntity<>(ApiResult.success(BAD_REQUEST.value(), mo + "格式不正确!", ""), HttpStatus.BAD_REQUEST);
        }
        String itemCode = str[3];//物料编号
        Double qty = Double.parseDouble(str[4]);//数量
        String propC1 = str[2];//批次号
        String propC3 = str[1];//厂家编号

        Item item = itemService.existItem(itemCode);
        if (item == null) {
            return new ResponseEntity<>(ApiResult.success(BAD_REQUEST.value(), itemCode + "物料不存在!", ""), HttpStatus.BAD_REQUEST);
        }

        Stock stock = stockService.findByCode(stockCode, null);
        if (stock == null) {
            return new ResponseEntity<>(ApiResult.success(BAD_REQUEST.value(), stockCode + "容器不存在!", ""), HttpStatus.BAD_REQUEST);
        }
        if (stock.getStatus().equals(BaseStatus.USED)) {
            return new ResponseEntity<>(ApiResult.success(BAD_REQUEST.value(), stockCode + "容器已占用,请更换容器!", ""), HttpStatus.BAD_REQUEST);
        }
        //起点写死
        Point srcPoint = pointService.getPoint(null, BaseStatus.FREE, BaseStatus.BOX, "入库输送线满箱接驳口");
        if (srcPoint == null) {
            return new ResponseEntity<>(ApiResult.success(BAD_REQUEST.value(), " 请维护入库输送线接驳口点位!", ""), HttpStatus.BAD_REQUEST);
        }

        if (asnDetailService.findByMo(Mo)) {
            return new ResponseEntity<>(ApiResult.success(BAD_REQUEST.value(), "该" + Mo + "MO票已绑定,请勿重复操作!", ""), HttpStatus.BAD_REQUEST);
        } else {
            //生成入库料箱任务
            AgvTask agvTask = new AgvTask(BizStatus.ASN, stock.getCode(), srcPoint.getCode(), null, BizStatus.OPEN, "PICKER_MOVE");
            agvTaskService.create(agvTask);

            //生成入库任务
            AsnDetail asnDetail = asnDetailService.createAsnDetail(item, stock, srcPoint, propC1, null);
            asnDetail.setOrderQty(qty);
            asnDetail.setPo(Mo);
            asnDetail.setPropC3(propC3);
            asnDetailService.create(asnDetail);
            //生成Itemkey
            ItemKey itemKey = itemKeyService.getItemKey(item, asnDetail.getPropC1(), asnDetail.getOrderNumber());

            //生成入库记录
            Task task = new Task(item, itemKey, asnDetail.getOrderNumber(), BizStatus.ASN, asnDetail, null, null, null, stock, stock, srcPoint, null, stock.getCode(), stock.getCode(), srcPoint.getCode(), null, null, BizStatus.OPEN, asnDetail.getOrderQty(), null, null, item.getDept(), agvTask);
            taskService.create(task);

            //容器改为占用,目标点位占用
            stock.setStatus(BaseStatus.USED);
            stockService.update(stock);
        }

*/
        return new ResponseEntity<>(ApiResult.success(OK.value(), "绑定成功!", ""), HttpStatus.OK);
    }


    @PostMapping("/callStock")
    @Log("满料出库-小件")
    @ApiOperation("满料出库-小件")
    @AnonymousAccess
    public ResponseEntity<Object> callStock(@RequestBody SmallCallStock smallCallStock) {
        BoxDto boxDto = boxService.findById(smallCallStock.getId());//按钮盒
        Box box = boxService.toEntity(boxDto);//转实体
        Point endPoint = box.getPoint();
        if (endPoint.getStatus().equals(BaseStatus.FREE)) {
            if (box == null) {
                return new ResponseEntity<>(ApiResult.success(BAD_REQUEST.value(), "请至少选中一条数据!", ""), HttpStatus.BAD_REQUEST);
            }
            String itemCode = smallCallStock.getItemCode();//物料编号
            int quantity = smallCallStock.getQuantity();//箱数


            Item item = itemService.existItem(itemCode);
            if (item == null) {
                return new ResponseEntity<>(ApiResult.success(BAD_REQUEST.value(), itemCode + "物料不存在!", ""), HttpStatus.BAD_REQUEST);
            }

            List<Inventory> inventoryList = inventoryService.queryInventory(item.getId());
            if (inventoryList.size() == 0) {
                return new ResponseEntity<>(ApiResult.success(BAD_REQUEST.value(), "无库存,呼叫失败!", ""), HttpStatus.BAD_REQUEST);
            }

            //如果呼叫的个数大于库存的个数则取库存个数，否则取呼叫个数
            if (quantity > inventoryList.size()) {
                return new ResponseEntity<>(ApiResult.success(BAD_REQUEST.value(), "输入的箱数不能大于库存数，库存数为" + inventoryList.size() + "箱数", ""), HttpStatus.BAD_REQUEST);
            }

            List<Inventory> newList = inventoryList.subList(0, quantity);//根据数量呼叫料箱
            for (Inventory inventory : newList) {
                PickDetail pickDetail = pickDetailService.createPickDetail(inventory.getItemKey().getItem(), null);
                try {
                    pickDetailService.xjAllocateAll(pickDetail.getId(), box.getPoint());
                } catch (Exception e) {
                    return new ResponseEntity<>(ApiResult.success(BAD_REQUEST.value(), e.getMessage(), ""), HttpStatus.BAD_REQUEST);
                }

            }
            //按钮盒点位占用
            endPoint.setStatus(BaseStatus.USED);
            pointService.update(endPoint);
        } else {
            return new ResponseEntity<>(ApiResult.success(BAD_REQUEST.value(), endPoint.getCode() + "点位已有任务，请勿重复操作!", ""), HttpStatus.BAD_REQUEST);
        }
        return new ResponseEntity<>(ApiResult.success(OK.value(), "呼叫成功!", ""), HttpStatus.OK);
    }

    @PostMapping("/callEmptyStock")
    @Log("空箱出库-小件")
    @ApiOperation("空箱出库-小件")
    @AnonymousAccess
    public ResponseEntity<Object> callEmptyStock(@RequestBody SmallCallStock smallCallStock) {
        BoxDto boxDto = boxService.findById(smallCallStock.getId());//按钮盒
        Box box = boxService.toEntity(boxDto);//转实体
        Point endPoint = box.getPoint();
        if (box == null) {
            return new ResponseEntity<>(ApiResult.success(BAD_REQUEST.value(), "请至少选中一条数据!", ""), HttpStatus.BAD_REQUEST);
        }
        int quantity = smallCallStock.getQuantity();//箱数

        //查询空料箱
        List<Stock> stockList = new ArrayList<>();
        if (stockList.size() > 0) {
            //如果呼叫的个数大于空料箱的个数则取空料箱个数，否则取呼叫个数
            if (quantity > stockList.size()) {
                quantity = stockList.size();
            }

            List<Stock> newList = stockList.subList(0, quantity);//根据数量呼叫空料箱
            for (Stock stock : newList) {
                AgvTask agvTask = new AgvTask(BizStatus.EMPTY_OUT, stock.getCode(), stock.getPoint().getCode(), endPoint.getCode(), BizStatus.OPEN, "RACK_MOVE");
                agvTaskService.create(agvTask);
            }
        } else {
            return new ResponseEntity<>(ApiResult.success(BAD_REQUEST.value(), "无空料箱,请稍后操作!", ""), HttpStatus.BAD_REQUEST);
        }


        return new ResponseEntity<>(ApiResult.success(OK.value(), "呼叫成功!", ""), HttpStatus.OK);
    }

}
