package com.hw.wms.controller;

import com.hw.common.core.constant.SecurityConstants;
import com.hw.common.core.constant.WmsConstants;
import com.hw.common.core.domain.R;
import com.hw.common.core.exception.ServiceException;
import com.hw.common.core.web.controller.BaseController;
import com.hw.common.core.web.domain.AjaxResult;
import com.hw.common.core.web.page.TableDataInfo;
import com.hw.common.log.annotation.Log;
import com.hw.common.log.enums.BusinessType;
import com.hw.mes.api.RemoteMesService;
import com.hw.mes.api.domain.MesBaseBarcodeInfo;
import com.hw.wms.domain.*;
import com.hw.wms.domain.vo.*;
import com.hw.wms.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 移动端手持Controller
 *
 * @author xs
 * @date 2023-12-20
 */
@RestController
@RequestMapping("/mobile")
public class WmsMobileController extends BaseController {
    @Autowired
    private IWmsRawInstockService wmsRawInstockService;

    @Autowired
    private IWmsRawOutstockService wmsRawOutstockService;

    @Autowired
    private IWmsRawReturnService wmsRawReturnService;

    @Autowired
    private IWmsProductInstockService wmsProductInstockService;

    @Autowired
    private IWmsProductOutstockService wmsProductOutstockService;

    @Autowired
    private IWmsProductOutstockDetailService wmsProductOutstockDetailService;

    @Autowired
    private IWmsMoveService wmsMoveService;

    @Autowired
    private IWmsTransferService wmsTransferService;

    @Autowired
    private IWmsBaseWarehouseService wmsBaseWarehouseService;

    @Autowired
    private IWmsBaseLocationService wmsBaseLocationService;

    @Autowired
    private IWmsProductStockService wmsProductStockService;

    @Autowired
    private IWmsInventoryCheckService wmsInventoryCheckService;

    @Resource
    private RemoteMesService remoteMesService;

    /**
     * 根据物料条码获取条码信息
     */
//    @RequiresPermissions("wms:rawoutstock:query")
    @GetMapping(value = "/getBaseBarcodeInfo/{materialBarcode}")
    public AjaxResult getBaseBarcodeInfo(@PathVariable("materialBarcode") String materialBarcode) {
        R<MesBaseBarcodeInfo> baseBarcodeInfoR = remoteMesService.getBarcode(materialBarcode, SecurityConstants.INNER);
        if (baseBarcodeInfoR == null) {
            throw new ServiceException("物料编码有误");
        }

        MesBaseBarcodeInfo baseBarcodeInfo = baseBarcodeInfoR.getData();
        if (baseBarcodeInfo == null) {
            throw new ServiceException("物料编码有误");
        }

        return success(baseBarcodeInfo);
    }


    /**
     * 新增原材料入库记录
     */
//    @RequiresPermissions("wms:mobile:addrawinstock")
    @Log(title = "原材料入库记录", businessType = BusinessType.INSERT)
    @PostMapping(("/addRawInstock"))
    public AjaxResult addRawInstock(@Validated @RequestBody WmsRawInstockVo wmsRawInstockVo) {
        return toAjax(wmsRawInstockService.insertWmsRawInstock(wmsRawInstockVo));
    }


    /**
     * 查询原材料待审核状态的出库记录列表
     */
//    @RequiresPermissions("wms:rawoutstock:list")
    @GetMapping("/getToAuditedRawOutstocks")
    public TableDataInfo getToAuditedRawOutstocks() {
        startPage();
        WmsRawOutstock wmsRawOutstock = new WmsRawOutstock();
        wmsRawOutstock.setAuditStatus(WmsConstants.WMS_AUDIT_STATUS_TOAUDIT);
        List<WmsRawOutstock> list = wmsRawOutstockService.selectWmsRawOutstockJoinList4Audit(wmsRawOutstock);
        return getDataTable(list);
    }

    /**
     * 获取原材料出库记录详细信息
     */
//    @RequiresPermissions("wms:rawoutstock:query")
//    @GetMapping(value = "/getRawOutstockByOutstockId/{rawOutstockId}")
//    public AjaxResult getRawOutstockByOutstockId(@PathVariable("rawOutstockId") Long rawOutstockId) {
//        return success(wmsRawOutstockService.selectWmsRawOutstockByRawOutstockId(rawOutstockId));
//    }
    @GetMapping(value = "/getRawOutstockByTaskCode/{taskCode}")
    public AjaxResult getRawOutstockByTaskCode(@PathVariable("taskCode") String taskCode) {
        return success(wmsRawOutstockService.selectWmsRawOutstockByTaskCode(taskCode));
    }

    /**
     * 审核原材料出库记录
     */
    @Log(title = "原材料出库记录", businessType = BusinessType.AUDIT)
    @PostMapping(("/auditRawOutstock"))
    public AjaxResult auditRawOutstock(@Validated @RequestBody WmsRawOutstockAuditVo wmsRawOutstockAuditVo) {
        return success(wmsRawOutstockService.auditWmsRawOutstock(wmsRawOutstockAuditVo));
    }

    /**
     * 查询原材料审核通过的出库记录明细列表
     */
//    @RequiresPermissions("wms:rawoutstock:list")
    @GetMapping("/getAuditPassRawOutstockDetails")
    public TableDataInfo getAuditPassRawOutstocks(WmsRawOutstock wmsRawOutstock) {
        startPage();
//        WmsRawOutstockDetail wmsRawOutstockDetail = new WmsRawOutstockDetail();
//        wmsRawOutstockDetail.setApplyBy(request.getParameter("applyBy"));
        List<WmsRawOutstock> list = wmsRawOutstockService.selectAuditPassRawOutstocks(wmsRawOutstock);
        return getDataTable(list);
    }

    /**
     * 原材料出库确认
     */
    @Log(title = "原材料出库记录", businessType = BusinessType.CONFIRM)
    @PostMapping(("/confirmRawOutstock"))
    public AjaxResult confirmRawOutstock(@Validated @RequestBody WmsRawOutstockConfirmVo wmsRawOutstockConfirmVo) {
        return toAjax(wmsRawOutstockService.confirmWmsRawOutstock(wmsRawOutstockConfirmVo));
    }


    /**
     * 查询原材料待审核状态的退库记录列表
     */
//    @RequiresPermissions("wms:rawoutstock:list")
    @GetMapping("/getToAuditedRawReturns")
    public TableDataInfo getToAuditedRawReturns() {
        startPage();
        WmsRawReturn wmsRawReturn = new WmsRawReturn();
        wmsRawReturn.setAuditStatus(WmsConstants.WMS_AUDIT_STATUS_TOAUDIT);
        List<WmsRawReturn> list = wmsRawReturnService.selectWmsRawReturnJoinList(wmsRawReturn);
        return getDataTable(list);
    }

    /**
     * 获取原材料退库记录详细信息,审核使用
     */
//    @RequiresPermissions("wms:rawoutstock:query")
    @GetMapping(value = "/getRawReturnByReturnId/{returnId}")
    public AjaxResult getRawReturnByReturnId(@PathVariable("returnId") Long returnId) {
        return success(wmsRawReturnService.selectWmsRawReturnByRawReturnId(returnId));
    }

    /**
     * 审核原材料退库记录
     */
    @Log(title = "原材料退库记录", businessType = BusinessType.AUDIT)
    @PostMapping(("/auditRawReturn"))
    public AjaxResult auditRawReturn(@Validated @RequestBody WmsRawReturnAuditVo wmsRawReturnAuditVo) {
        return toAjax(wmsRawReturnService.auditWmsRawReturn(wmsRawReturnAuditVo));
    }

    /**
     * 查询原材料审核通过的退库记录明细列表
     */
//    @RequiresPermissions("wms:rawoutstock:list")
    @GetMapping("/getAuditPassRawReturns")
    public TableDataInfo getAuditPassRawReturns(WmsRawReturnDetail wmsRawReturnDetail) {
        startPage();

        WmsRawReturn wmsRawReturn = new WmsRawReturn();
        wmsRawReturn.setAuditStatus(WmsConstants.WMS_AUDIT_STATUS_PASS);
        List<WmsRawReturn> list = wmsRawReturnService.selectWmsRawReturnJoinList(wmsRawReturn);
        return getDataTable(list);
    }

    /**
     * 获取原材料退库记录详细信息,退库确认使用
     */
//    @RequiresPermissions("wms:rawoutstock:query")
    @GetMapping(value = "/getRawReturnByReturnId4Confirm/{returnId}")
    public AjaxResult getRawReturnByReturnId4Confirm(@PathVariable("returnId") Long returnId) {
        return success(wmsRawReturnService.selectWmsRawReturnByRawReturnId4Confirm(returnId));
    }

    /**
     * 原材料退库确认
     */
    @Log(title = "原材料退库记录", businessType = BusinessType.CONFIRM)
    @PostMapping(("/confirmRawReturn"))
    public AjaxResult confirmRawReturn(@Validated @RequestBody WmsRawReturnConfirmVo wmsRawReturnConfirmVo) {
        return toAjax(wmsRawReturnService.confirmWmsRawReturn(wmsRawReturnConfirmVo));
    }


    /**
     * 人工成品入库（适用于5楼成品入库）
     */
    @Log(title = "成品入库记录", businessType = BusinessType.INSERT)
    @PostMapping(("/addProductInstock"))
    public AjaxResult addProductInstock(@Validated @RequestBody WmsProductInstockVo wmsProductInstockVo) {
        return toAjax(wmsProductInstockService.insertWmsProductInstock(wmsProductInstockVo));
    }


    /**
     * 获取半成品仓库列表
     */
//    @RequiresPermissions("wms:rawoutstock:query")
    @GetMapping(value = "/getSemiWarehouseList")
    public AjaxResult getSemiWarehouseList() {
        WmsBaseWarehouse queryBaseWarehouse = new WmsBaseWarehouse();
        queryBaseWarehouse.setWarehouseInstockType(WmsConstants.WMS_WAREHOUSE_INSTOCK_TYPE_SEMI);
        return success(wmsBaseWarehouseService.selectWmsBaseWarehouseList(queryBaseWarehouse));
    }

    /**
     * 获取成品仓库列表
     */
//    @RequiresPermissions("wms:rawoutstock:query")
    @GetMapping(value = "/getProductWarehouseList")
    public AjaxResult getProductWarehouseList() {
        WmsBaseWarehouse queryBaseWarehouse = new WmsBaseWarehouse();
        queryBaseWarehouse.setWarehouseInstockType(WmsConstants.WMS_WAREHOUSE_INSTOCK_TYPE_PRODUCT);
        return success(wmsBaseWarehouseService.selectWmsBaseWarehouseList(queryBaseWarehouse));
    }


    /**
     * 根据仓库ID获取成品库存信息（目前就是根据半成品仓库ID获取库存信息，然后根据库存选择对应的成品和数量进行转到成品库）
     */
//    @RequiresPermissions("wms:rawoutstock:query")
    @GetMapping(value = "/getProductStocksByWarehouseId")
    public TableDataInfo getProductStocksByWarehouseId(WmsProductStock queryProductStock) {
        startPage();
//        WmsProductStock queryProductStock = new WmsProductStock();
//        queryProductStock.setWarehouseId(Long.valueOf(request.getParameter("warehouseId")));
        List list = wmsProductStockService.selectWmsProductStockJoinList(queryProductStock);
        return getDataTable(list);
    }


    /**
     * 人工申请半成品出半成品库入成品库
     */
    @Log(title = "转库", businessType = BusinessType.TRANSFER)
    @PostMapping(("/applyProductTransfer"))
    public AjaxResult applyProductTransfer(@Validated @RequestBody List<WmsTransfer> wmsTransfers) {
        return toAjax(wmsTransferService.applyTransfers(wmsTransfers));
    }


    /**
     * 获取待转库列表
     */
//    @RequiresPermissions("wms:rawoutstock:query")
    @GetMapping(value = "/getTransfers")
    public TableDataInfo getTransfers() {
        startPage();
        WmsTransfer queryTransfer = new WmsTransfer();
        queryTransfer.setExecuteStatus(WmsConstants.WMS_EXECUTE_STATUS_NOT_FINISH);
        List list = wmsTransferService.selectWmsTransferJoinList(queryTransfer);
        return getDataTable(list);
    }


    /**
     * 转库出库，五楼半成品出半成品库
     */
    @Log(title = "转库", businessType = BusinessType.INSERT)
    @PostMapping(("/transferOutstock"))
    public AjaxResult transferOutstock(@RequestBody WmsTransferDetail wmsTransferDetail) {
        return toAjax(wmsTransferService.transferOutstock(wmsTransferDetail));
    }


    /**
     * 转库入库，五楼半成品入成品库
     */
    @Log(title = "转库", businessType = BusinessType.INSERT)
    @PostMapping(("/transferInstock"))
    public AjaxResult transferInstock(@RequestBody WmsTransferDetail wmsTransferDetail) {
        return toAjax(wmsTransferService.transferInstock(wmsTransferDetail));
    }


    /**
     * 根据销售订单编号获取成品库存列表
     */
//    @RequiresPermissions("wms:rawoutstock:query")
    @GetMapping(value = "/getProductStocksBySalesorderCode")
    public TableDataInfo getProductStocksBySalesorderCode(WmsProductStock queryProductStock) {
        startPage();
//        WmsProductStock queryProductStock = new WmsProductStock();
//        queryProductStock.setSaleorderCode(request.getParameter("salesorderCode"));
//        queryProductStock.setStockType(WmsConstants.PRODUCT_STOCK_STOCK_TYPE_PRODUCT);
        List list = wmsProductStockService.selectWmsProductStocksBySaleorder(queryProductStock);
        return getDataTable(list);
    }

    /**
     * 成品出库申请（包括人工和agv的出库申请）
     */
    @Log(title = "成品出库记录", businessType = BusinessType.INSERT)
    @PostMapping(("/applyProductOutstock"))
    public AjaxResult applyProductOutstock(@RequestBody WmsProductOutstock wmsProductOutstock) {
        return toAjax(wmsProductOutstockService.insertWmsProductOutstock(wmsProductOutstock));
    }


    /**
     * 获取人工成品出库任务列表
     */
//    @RequiresPermissions("wms:rawoutstock:query")
    @GetMapping(value = "/getProductOutStocks")
    public TableDataInfo getProductOutStocks(WmsProductOutstock queryProductOutstock) {
        startPage();
        queryProductOutstock.setOperationType(WmsConstants.WMS_OPERATION_TYPE_MANUAL);
        queryProductOutstock.setExecuteStatus(WmsConstants.WMS_EXECUTE_STATUS_NOT_FINISH);
        queryProductOutstock.setProductType(WmsConstants.WMS_PRODUCT_OUTSTOCK_PRODUCT_TYPE_PRODUCT);
        List list = wmsProductOutstockService.selectWmsProductOutstockJoinList(queryProductOutstock);
        return getDataTable(list);
    }

    /**
     * 获取人工成品出库任务明细,参数是productOutstockId
     */
//    @RequiresPermissions("wms:rawoutstock:query")
    @GetMapping(value = "/getProductOutStockWithDetails")
    public AjaxResult getProductOutStockWithDetails(WmsProductOutstock queryProductOutstock) {
        WmsProductOutstock productOutstock = wmsProductOutstockService.
                selectWmsProductOutstockJoinByOutstockId(queryProductOutstock.getProductOutstockId());

        WmsProductOutstockDetail queryProductOutstockDetail = new WmsProductOutstockDetail();
        queryProductOutstockDetail.setProductOutstockId(queryProductOutstock.getProductOutstockId());
        List productOutstockDetails = wmsProductOutstockDetailService.selectWmsProductOutstockDetailList(queryProductOutstockDetail);

        productOutstock.setWmsProductOutstockDetailList(productOutstockDetails);
//        ajax.put("productOutstock", productOutstock);
//        ajax.put("productOutstockDetails", productOutstockDetails);
        return success(productOutstock);
    }

    /**
     * 人工成品出库确认（适用于成品仓库库管的成品出库确认）
     */
    @Log(title = "成品出库明细", businessType = BusinessType.INSERT)
    @PostMapping(("/confirmProductOutstockDetail"))
    public AjaxResult confirmProductOutstockDetail(@RequestBody WmsProductOutstockDetail wmsProductOutstockDetail) {
        return toAjax(wmsProductOutstockDetailService.insertWmsProductOutstockDetail(wmsProductOutstockDetail));
    }


    /**
     * 人工成品出库最终确认（适用于成品出库后，运输到指定地点，根据销售订单最终确认）
     */
    @Log(title = "成品出库确认", businessType = BusinessType.UPDATE)
    @PostMapping(("/finalConfirmProductOutstock"))
    public AjaxResult finalConfirmProductOutstock(@RequestBody @Validated WmsProductOutstockConfirmVo wmsProductOutstockConfirmVo) {

        return toAjax(wmsProductOutstockService.finalConfirmProductOutstock(wmsProductOutstockConfirmVo));
    }


    /**
     * 组装出库，适合在五楼背板安装区（将拆分的柜体再运输出来进行组装）
     */
    @Log(title = "组装出库", businessType = BusinessType.INSERT)
    @PostMapping(("/assembleOutstock"))
    public AjaxResult assembleOutstock(@Validated @RequestBody WmsAssembleOutstockVo wmsAssembleOutstockVo) {
        return toAjax(wmsRawOutstockService.assembleOutstock(wmsAssembleOutstockVo));
    }


    /**
     * 生产入库，适合在五楼背板安装区（将组装好的柜体入到半成品库）
     */
    @Log(title = "生产入库", businessType = BusinessType.INSERT)
    @PostMapping(("/produceInstock"))
    public AjaxResult fifthFloorProduceInstock(@Validated @RequestBody WmsProduceInstockVo wmsProduceInstockVo) {
        return toAjax(wmsProductInstockService.fifthFloorProduceInstock(wmsProduceInstockVo));
    }


    //todo：入库时校验warehousematerial,入库出库需要校验库位状态，是否是移库合库锁定等








    /**
     * 人工申请移库
     */
    @Log(title = "人工移库", businessType = BusinessType.APPLY)
    @PostMapping(("/applyMove"))
    public AjaxResult applyMove(@Validated @RequestBody WmsMoveApplyVo wmsMoveApplyVo) {
        return toAjax(wmsMoveService.applyMove(wmsMoveApplyVo));
    }

    /**
     * 获取人工移库记录列表
     */
//    @RequiresPermissions("wms:rawoutstock:query")
    @GetMapping(value = "/getMoveList")
    public TableDataInfo getMoveList(WmsMove wmsMove) {
        startPage();
        wmsMove.setMoveWay(WmsConstants.WMS_MOVEMERGE_WAY_MANUAL);
        wmsMove.setExecuteStatusStr(WmsConstants.WMS_EXECUTE_STATUS_TOEXECUTE + "," + WmsConstants.WMS_MOVE_EXECUTE_STATUS_EXECUTING);
        List<WmsMove> wmsMoves = wmsMoveService.selectWmsMoveGroupJoinList(wmsMove);
        return getDataTable(wmsMoves);
    }

    /**
     * 获取人工移库记明细
     */
//    @RequiresPermissions("wms:rawoutstock:query")
    @GetMapping(value = "/getMoveListByTaskCode/{taskCode}")
    public AjaxResult getMoveListByTaskCode(@PathVariable("taskCode") String taskCode) {
        WmsMove queryMove = new WmsMove();
        queryMove.setTaskCode(taskCode);
        List<WmsMove> wmsMoveList = wmsMoveService.selectWmsMoveJoinList(queryMove);
        return success(wmsMoveList);
    }


    /**
     * 人工移库出库
     */
    @Log(title = "人工移库", businessType = BusinessType.OUTSTOCK)
    @PostMapping(("/moveOutstock"))
    public AjaxResult moveOutstock(@Validated @RequestBody WmsMoveVo wmsMoveVo) {
        return toAjax(wmsMoveService.moveOutstock(wmsMoveVo));
    }


    /**
     * 人工移库入库
     */
    @Log(title = "人工移库", businessType = BusinessType.INSTOCK)
    @PostMapping(("/moveInstock"))
    public AjaxResult moveInstock(@Validated @RequestBody WmsMoveVo wmsMoveVo) {
        return toAjax(wmsMoveService.moveInstock(wmsMoveVo));
    }



    /**
     * 获取盘点任务列表
     */
//    @RequiresPermissions("wms:rawoutstock:query")
    @GetMapping(value = "/getInventoryChecks")
    public TableDataInfo getInventoryChecks(WmsInventoryCheck queryInventoryCheck) {
        startPage();
        List<WmsInventoryCheck> inventoryChecks = wmsInventoryCheckService.selectWmsInventoryCheckJoinList(queryInventoryCheck);
        return getDataTable(inventoryChecks);
    }

    /**
     * 获取仓库信息列表，提供给盘库使用
     */
//    @RequiresPermissions("wms:rawoutstock:query")
    @GetMapping(value = "/getWarehouses")
    public AjaxResult getWarehouses() {
        WmsBaseWarehouse queryWarehouse = new WmsBaseWarehouse();
        queryWarehouse.setWarehouseType(WmsConstants.WMS_WAREHOUSE_TYPE_NORMAL);
        List<WmsBaseWarehouse> warehouses = wmsBaseWarehouseService.selectWmsBaseWarehouseList(queryWarehouse);
        return success(warehouses);
    }

    /**
     * 获取库位信息列表，提供给盘库使用
     */
//    @RequiresPermissions("wms:rawoutstock:query")
    @GetMapping(value = "/getLocations")
    public TableDataInfo getLocations(WmsBaseLocation baseLocation) {
        startPage();
        //todo 需要根据正在盘点的生成库位的盘点记录明细过滤
        List<WmsBaseLocation> baseLocations = wmsBaseLocationService.selectWmsBaseLocationList(baseLocation);
        return getDataTable(baseLocations);
    }


    /**
     * 开始盘点（生成盘点数据）
     */
    @Log(title = "物料盘点", businessType = BusinessType.INSERT)
    @PostMapping(("/inventoryCheck"))
    public AjaxResult inventoryCheck(@Validated @RequestBody WmsInventoryCheckVo wmsInventoryCheckVo) {
        return success(wmsInventoryCheckService.insertWmsInventoryCheck(wmsInventoryCheckVo));
    }


    /**
     * 获取待盘点和盘点中的盘点记录明细列表(inventoryCheckId=3&checkStatus=1(1是盘点中，2是盘点完成))
     */
//    @RequiresPermissions("wms:rawoutstock:query")
    @GetMapping(value = "/getInventoryCheckDetails")
    public AjaxResult getInventoryCheckDetails(WmsInventoryCheckDetail wmsInventoryCheckDetail) {
        List<WmsInventoryCheckDetail> checkDetails = wmsInventoryCheckService.getInventoryCheckDetails(wmsInventoryCheckDetail);
        return success(checkDetails);
    }


//TODO 盘点中的不能进行移库合库？
    /**
     * 确认盘点
     */
    @Log(title = "物料盘点", businessType = BusinessType.CONFIRM)
    @PostMapping(("/confirmInventoryCheckDetail"))
    public AjaxResult confirmInventoryCheckDetail(@RequestBody WmsInventoryCheckDetailVo wmsInventoryCheckDetailVo) {
        return success(wmsInventoryCheckService.confirmInventoryCheckDetail(wmsInventoryCheckDetailVo));
    }



    /**
     * 盘点完成
     */
    @Log(title = "物料盘点", businessType = BusinessType.INSERT)
    @PostMapping(("/completeInventoryCheck"))
    public AjaxResult completeInventoryCheck(@RequestBody WmsInventoryCheck wmsInventoryCheck) {
        return success(wmsInventoryCheckService.completeInventoryCheck(wmsInventoryCheck));
    }
}
