package com.cf.imes.module.executor.controller.admin.order;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.cf.imes.framework.common.exception.ServiceException;
import com.cf.imes.framework.common.pojo.CommonResult;
import com.cf.imes.framework.common.pojo.PageParam;
import com.cf.imes.framework.common.pojo.PageResult;
import com.cf.imes.framework.common.util.object.BeanUtils;
import com.cf.imes.framework.mybatis.core.generator.SnowFlakeGenerator;
import com.cf.imes.framework.operatelog.core.annotations.OperateLog;
import com.cf.imes.framework.redis.config.ChenfengCacheProperties;
import com.cf.imes.framework.redis.constants.RedisKeyConstants;
import com.cf.imes.framework.redis.util.RedisLockUtil;
import com.cf.imes.framework.security.core.util.SecurityFrameworkUtils;
import com.cf.imes.module.executor.controller.admin.order.vo.order.*;
import com.cf.imes.module.executor.controller.admin.order.vo.product.OrderBodyRespVO;
import com.cf.imes.module.executor.controller.admin.order.vo.product.OrderRoomBodyRespVO;
import com.cf.imes.module.executor.controller.admin.orderParts.vo.OrderPartsRespVO;
import com.cf.imes.module.executor.dal.dataobject.order.OrderDO;
import com.cf.imes.module.executor.dal.mysql.order.OrderMapper;
import com.cf.imes.module.executor.enums.CategoryEnum;
import com.cf.imes.module.executor.enums.OrderDeletedEnum;
import com.cf.imes.module.executor.enums.OrderStatusEnum;
import com.cf.imes.module.executor.service.order.OrderInputProcessor;
import com.cf.imes.module.executor.service.order.OrderService;
import com.cf.imes.module.executor.util.ExcelWriterUtil;
import com.cf.imes.module.executor.util.fileConversion.admin.api.webcad.ApiDataAchieve;
import com.cf.imes.module.executor.util.fileConversion.admin.api.webcad.ApiTypeRealize;
import com.cf.imes.module.executor.util.fileConversion.admin.files.excel.*;
import com.cf.imes.module.executor.util.fileConversion.admin.files.xml.VO.OrderXmlVO;
import com.cf.imes.module.executor.util.fileConversion.admin.files.xml.VO.XmlCheckVO;
import com.cf.imes.module.executor.util.fileConversion.admin.files.xml.XMLUtil;
import com.cf.imes.module.executor.util.fileConversion.admin.files.xml.XmlBuilder;
import com.cf.imes.module.executor.util.fileConversion.admin.files.xml.XmlTypeRealize;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;
import java.io.File;
import java.util.*;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutionException;

import static com.cf.imes.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.cf.imes.framework.common.pojo.CommonResult.error;
import static com.cf.imes.framework.common.pojo.CommonResult.success;
import static com.cf.imes.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;
import static com.cf.imes.framework.operatelog.core.enums.OperateTypeEnum.IMPORT;
import static com.cf.imes.module.executor.enums.EsIndexEnum.*;
import static com.cf.imes.framework.security.core.util.SecurityFrameworkUtils.getUserOrganId;
import static com.cf.imes.module.executor.enums.ErrorCodeConstants.*;


@Tag(name = "管理后台 - 生产单管理")
@RestController
@RequestMapping("/executor/order")
@Validated
@Slf4j
public class OrderController {

    @Resource
    private OrderService orderService;

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private LargeFilesUtils largeFilesUtils;

    @Resource
    private ExcelCheckListUtil excelCheckListUtil;

    @Resource
    private ApiDataAchieve apiDataAchieve;

    @Resource
    private ApiTypeRealize apiTypeRealize;

    @Resource
    private IdentifierGenerator identifierGenerator;

    @Resource
    private XMLUtil xmlUtil;

    @Resource
    private ExcelTypeRealize excelTypeRealize;

    @Resource
    private SnowFlakeGenerator snowFlakeGenerator;

    @Resource
    private XmlTypeRealize xmlTypeRealize;

    @Resource
    private RedisLockUtil redisLockUtil;

    @Resource
    private OrderInputProcessor orderInputProcessor;

    @Resource
    private ChenfengCacheProperties chenfengCacheProperties;

    private String errKey = "生产数据导入异常,{}";



    @PostMapping("/create")
    @Operation(summary = "创建生产单")
    @PreAuthorize("@ss.hasPermission('production:manager-list:create')")
    public CommonResult<Long> createOrder(@Valid @RequestBody OrderSaveReqVO createReqVO) {
        return success(orderService.createOrder(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新生产单")
    @PreAuthorize("@ss.hasPermission('production:manager-list:edit')")
    public CommonResult<Boolean> updateOrder(@Valid @RequestBody OrderSaveReqVO updateReqVO) {
        orderService.updateOrder(updateReqVO);
        return success(true);
    }

    //    做生产单是否作废判断
    @GetMapping("/get")
    @Operation(summary = "获得（单个）生产单")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('productManager:List')")
    public CommonResult<OrderRespVO> getOrder(@RequestParam("id") Long id) {
        return success(BeanUtils.toBean(orderService.getOrder(id), OrderRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得生产单分页")
    @PreAuthorize("@ss.hasPermission('productManager:List')")
    public CommonResult<PageResult<OrderRespVO>> getOrderPage(@Valid OrderPageReqVO pageReqVO) {
        return success(BeanUtils.toBean(orderService.getOrderPage(pageReqVO), OrderRespVO.class));
    }

    @GetMapping("/webcad/page")
    @Operation(summary = "获得生产单分页")
    public CommonResult<PageResult<OrderRespVO>> webCadGetOrderPage(@Valid OrderPageReqVO pageReqVO) {
        return success(BeanUtils.toBean(orderService.getOrderPage(pageReqVO), OrderRespVO.class));
    }

    //    不做生产单是否作废判断
    @GetMapping("/printing")
    @Operation(summary = "打印/导出 数据文件")
    @Parameters({
            @Parameter(name = "type", description = "文件类型", required = true, example = "0"),
            @Parameter(name = "orderId", description = "生产单号", required = true, example = "1813119086461190144")
    })
    @PreAuthorize("@ss.hasPermission('production:manager-list:export')")
    @OperateLog(type = EXPORT)
    public CommonResult<Map<String, Object>> getOrderPrintData(@RequestParam("orderId") Long orderId,
                                                               @RequestParam("type") String type, HttpServletResponse response) {
        return success(orderService.getPrintDataMap(orderId, type, response));
    }

    @DeleteMapping("/delete")
    @Operation(summary = "作废")
    @Parameter(name = "orderId", description = "生产单id", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('production:manager-list:nullify')")
    public CommonResult<Boolean> deleteOrder(@RequestParam("orderId") Long orderId) {
        Integer index = orderService.updateOrderDel(orderId, OrderDeletedEnum.DELETED.getStatus());
        if (index == 0) {
            throw exception(ORDER_DELETED_ERR);
        }
        return success(true);
    }

    @PutMapping("/restore")
    @Operation(summary = "还原")
    @Parameter(name = "orderId", description = "生产单id", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('production:manager-list:backOrder')")
    public CommonResult<Boolean> restoreOrder(@RequestBody JSONObject jsonObject) {
        Long orderId = jsonObject.getLong("orderId");
        Integer index = orderService.updateOrderDel(orderId, OrderDeletedEnum.NOT_DELETED.getStatus());
        if (index == 0) {
            throw exception(ORDER_RESTORE_ERR);
        }
        return success(true);
    }

    @GetMapping("/get-import-template")
    @Operation(summary = "获得导入生产单模板")
    @Parameter(name = "value", description = "文件类型", required = true, example = "0")
    public void importTemplate(HttpServletResponse response, @RequestParam("value") @NotEmpty(message = "文件路径不能为空") String value) {
        orderService.exportTemplate(response, value);
    }


    //    获取api订单接口
    @GetMapping("/getApiOrder")
    @Operation(summary = "获取api订单接口")
    @Parameters({
            @Parameter(name = "startTime", description = "开始时间", required = false),
            @Parameter(name = "endTime", description = "结束时间", required = false),
            @Parameter(name = "orderNo", description = "订单号", required = false),
            @Parameter(name = "customOrderNo", description = "自定义单号", required = false)
    })
    @PreAuthorize("@ss.hasPermission('productManager:List')")
    public CommonResult<List<ApiOrderRespVO>> getApiOrder(@RequestParam(value = "startTime", required = false) String startTime,
                                                          @RequestParam(value = "endTime", required = false) String endTime,
                                                          @RequestParam(value = "orderNo", required = false) String orderNo,
                                                          @RequestParam(value = "customOrderNo", required = false) String customOrderNo)
            throws ExecutionException, InterruptedException {
        Long organId = SecurityFrameworkUtils.getLoginUser().getOrganId();
        JSONObject oauth = apiDataAchieve.getApiToken(organId).get();
        String token = oauth.getJSONObject("info").getString("access_token");
        String shopId = oauth.getJSONObject("info").getString("shop_id");
        JSONObject orderList = apiDataAchieve.getApiOrderList(token, shopId, startTime, endTime, orderNo, customOrderNo).get();
        return success(orderService.getApiOrderList(orderList));
    }

    //    api-生产单导入
    @GetMapping("getApiData")
    @Operation(summary = "生产单api数据导入新增")
    @OperateLog(module="管理后台 - 生产单管理",name = "生产单api数据导入新增",type = IMPORT)
    @Parameter(name = "orderNo", description = "原订单号", required = true, example = "20230809027818")
    @PreAuthorize("@ss.hasPermission('production:manager-list:create')")
    public CommonResult<String> getApiData(@RequestParam(value = "orderNo") String orderNo) throws InterruptedException {
        // 加导入锁
        String importLockValue = "syncApiImport";
        String importLockKey = String.format(RedisKeyConstants.ORDER_IMPORT_LOCK_KEY, getUserOrganId());
        boolean isLocked = redisLockUtil.acquireLock(importLockKey, importLockValue, chenfengCacheProperties.getLockTimeout());
        if (!isLocked) {
            throw new ServiceException(ORDER_IMPORT_ORGAN_LOCK_ERROR);
        }
        Long orderId = null;
        try {
            orderId = (Long) identifierGenerator.nextId(null);
            Long organId = getUserOrganId();

            Long id = orderService.importApiData(apiTypeRealize.apiDataChange(orderNo, orderId, organId));

            return success(String.valueOf(id));
        } catch (CompletionException | ExecutionException | InterruptedException e) {
            // 进行判断，为空，写入时出现了错误，数据库数据回滚，此时删除 ES 里的数据
            OrderDO orderDO = orderMapper.selectById(orderId);
            if (orderDO == null) {
                orderInputProcessor.deleteByOrderId(orderId, ORDER_PLATE_MODEL.getIndex());
                orderInputProcessor.deleteByOrderId(orderId, ORDER_PARTS_REMARK_MODEL.getIndex());
            }

            Throwable cause = e.getCause();
            return error((ServiceException) cause);

        } finally {
            // 导入锁解锁
            redisLockUtil.releaseLock(importLockKey, importLockValue);
        }

    }

    @PostMapping("/importFile")
    @Operation(summary = "生产单文件导入新增/导入板材")
    @Parameters({
            @Parameter(name = "file", description = "文件", required = true),
            @Parameter(name = "type", description = "文件类型", required = true),
            @Parameter(name = "index", description = "导入范围 0:全部，1:板材，默认为全部", required = false),
            @Parameter(name = "id", description = "生产单id", required = false)
    })
    @OperateLog(type = IMPORT)
    @PreAuthorize("@ss.hasPermission('production:manager-list:create')")
    public void exportFile(@RequestPart("file") MultipartFile file,
                              @RequestParam(value = "type") Integer type,
                              @RequestParam(value = "index", required = false, defaultValue = "0") Integer index,
                              @RequestParam(value = "id", required = false, defaultValue = "0") Long orderId,
                              HttpServletResponse response) throws Exception {
        List<OrderPlateImportExcelVO> list = null;
        OrderXmlVO orderXmlVO = null;
        Map<String, Object> listMap = null;

        OrderDO orderDO = null;
        Map<String, String> mapOrder = null;

        Boolean flag = true;
        // 加导入锁
        String importLockValue = "syncFileImport";
        String importLockKey = String.format(RedisKeyConstants.ORDER_IMPORT_LOCK_KEY, getUserOrganId());
        boolean isLocked = redisLockUtil.acquireLock(importLockKey, importLockValue, chenfengCacheProperties.getLockTimeout());
        if (!isLocked) {
            throw new ServiceException(ORDER_IMPORT_ORGAN_LOCK_ERROR);
        } else {
            try {
                if (type == 0) { //excel

                    List<OrderPlateImportExcelVO>[] listBoth = largeFilesUtils.importExcelLargeFile(file);// 表头+列表
                    list = listBoth[1];// 列表
                    mapOrder = largeFilesUtils.changeToOrderMap(listBoth[0]); // 表头

                    if (index == 0) { // 全部
                        ExcelCheckVO excelCheckVO = excelCheckListUtil.checkExcelList(mapOrder); // 表头验证
                        orderDO = excelCheckVO.getOrderDO();
                        orderDO.setId((Long) snowFlakeGenerator.nextId(null));
                        flag = excelCheckVO.getFlag();
                    } else { // 补板
                        orderDO = orderService.getOrder(orderId);
                        if (orderDO == null) {
                            mapOrder = new HashMap<>();
                            mapOrder.put(ProduceExcelConstants.ORDER_CUSTOM_ORDER_NO, "---< 生产单号不存在 >---");
                            flag = false;
                        }
                    }

                    String customOrderNo = mapOrder.get(ProduceExcelConstants.ORDER_CUSTOM_ORDER_NO);
                    if (index == 0 && customOrderNo != null && !orderService.customOrderNoIsExists(customOrderNo)) {
                        mapOrder.put(ProduceExcelConstants.ORDER_CUSTOM_ORDER_NO, customOrderNo + "---< 自定义单号重复 >---");
                        flag = false;
                    }

                    if (flag){
                        // list 校验
                        ExcelCheckVO excelCheckVO = excelCheckListUtil.checkExcelLargeFile(listBoth[1]);
                        list = excelCheckVO.getList();
                        flag = excelCheckVO.getFlag();

                        if (flag && list.isEmpty()) {
                            orderDO.setStatus(OrderStatusEnum.EMPTY.getStatus());
                        } else if (flag){
                            orderDO.setStatus(OrderStatusEnum.NEW_ORDER.getStatus());
                            listMap = excelTypeRealize.changeDate(list, orderDO.getId());
                        }
                    }
                    if (!flag) {
                        ExcelWriterUtil.write(response, mapOrder, list, orderService.getSavePath() + File.separator + "order_add_excel_err.xlsx");
                        return;
                    }
                } else if (type == 1) { // json

                } else if (type == 2) { // xml
                    orderXmlVO = (OrderXmlVO) XMLUtil.read(file, OrderXmlVO.class);

                    if (index == 0){
                        if (orderXmlVO != null) {
                            XmlCheckVO xmlCheckVO = xmlUtil.changeDate(orderXmlVO, getUserOrganId()); // 生产单数据格式验证
                            orderDO = xmlCheckVO.getOrderDO();
                            orderDO.setId((Long) snowFlakeGenerator.nextId(null));
                            flag = xmlCheckVO.getFlag();
                        }
                    } else {
                        orderDO = orderService.getOrder(orderId);
                        if (orderDO == null) {
                            orderXmlVO = new OrderXmlVO().setMemo("---< 生产单号不存在 >---");
                            flag = false;
                        }
                    }

                    // 生产数据格式验证
                    if (orderXmlVO == null) {
                        orderXmlVO = new OrderXmlVO().setMemo("文件内容解析为空");
                        flag = false;
                    } else if (orderDO == null) {
                        orderXmlVO = new OrderXmlVO().setMemo("生产单内容为空");
                        flag = false;
                    } else if (orderDO.getCustomOrderNo() != null && !orderService.customOrderNoIsExists(orderDO.getCustomOrderNo())) {
                        orderXmlVO.setOrderCode(orderXmlVO.getOrderCode() + "---< 自定义单号重复 >---");
                        flag = false;
                    } else if (flag){ // 生产单的内容正确
                        if (orderXmlVO.getMaterialXmlVO() == null || orderXmlVO.getMaterialXmlVO().getPlateXmlVOS() == null ||
                                orderXmlVO.getMaterialXmlVO().getPlateXmlVOS().getPlateXmlVOList() == null ||
                                orderXmlVO.getMaterialXmlVO().getPlateXmlVOS().getPlateXmlVOList().size() == 0) {
                            orderDO.setStatus(OrderStatusEnum.EMPTY.getStatus());
                        } else {
                            orderDO.setStatus(OrderStatusEnum.NEW_ORDER.getStatus());
                            flag = xmlUtil.checkVO(orderXmlVO);

                        }
                    }
                    if (!flag){
                        String xmlStr = XmlBuilder.objectToXmlStr(orderXmlVO);
                        XMLUtil.writeErr(response, xmlStr, " order_add_xml_err.xml");
                        return;
                    }

                    listMap = xmlTypeRealize.goodsInfoChange(orderXmlVO, orderDO.getId(), getUserOrganId());

                }
                orderService.importExcelData(orderDO, index, listMap);
            } catch (Exception e) {
                log.error(errKey, e);
                if (type == 0) {
                    ExcelWriterUtil.write(response, mapOrder, list, orderService.getSavePath() + File.separator + "order_add_excel_err.xlsx");
                } else if (type == 2) {
                    String xmlStr = XmlBuilder.objectToXmlStr(orderXmlVO);
                    XMLUtil.writeErr(response, xmlStr, " order_add_xml_err.xml");
                }

                // 进行判断，为空，写入时出现了错误，数据库数据回滚，此时删除 ES 里的数据
                if (ObjectUtil.isNotNull(orderDO) && ObjectUtil.isNotNull(orderMapper.selectById(orderDO.getId()))) {
                    Long deleteOrderId = orderDO.getId();
                    orderInputProcessor.deleteByOrderId(deleteOrderId, ORDER_PLATE_MODEL.getIndex());
                    orderInputProcessor.deleteByOrderId(deleteOrderId, ORDER_PARTS_REMARK_MODEL.getIndex());
                }

            } finally {
                // 导入锁解锁
                redisLockUtil.releaseLock(importLockKey, importLockValue);
            }
        }

    }

    @PostMapping("/import")
    @Operation(summary = "生产单导入新增")
    @Parameters({
            @Parameter(name = "file", description = "文件", required = true),
            @Parameter(name = "type", description = "文件类型", required = true),
            @Parameter(name = "id", description = "生产单id")
    })
    @OperateLog(type = IMPORT)
    @PreAuthorize("@ss.hasPermission('production:manager-list:create')")
    public void orderImport(@RequestPart("file") MultipartFile file,
                            @RequestParam(value = "type") Integer type,
                            @RequestParam(value = "id", required = false) Long orderId) {
        OrderImportAsyncReqVO orderImportAsyncReqVO = new OrderImportAsyncReqVO(orderId, type, null);
        orderService.orderImportAsync(orderImportAsyncReqVO, file);
    }


    //    生产单详情
    @GetMapping("/get-room")
    @Operation(summary = "生产单详情-房间和柜体id")
    @Parameters({
            @Parameter(name = "orderId", description = "生产单编号", required = true, example = "1024"),
            @Parameter(name = "deleted", description = "是否删除", example = "false")
    })
    @PreAuthorize("@ss.hasPermission('production:manager-list:detail')")
    public CommonResult<List<OrderBodyRespVO>> getRoom(@RequestParam("orderId") Long orderId,
                                                       @RequestParam(value = "deleted", required = false, defaultValue = "false") Boolean deleted) {
        if (deleted == null) {
            deleted = false;
        }
        return success(orderService.getOrderBody(orderId, !deleted ? 0 : 1));
    }

    @GetMapping("/get-room-and-body")
    @Operation(summary = "获取柜体和房间信息")
    @Parameter(name = "planId", description = "排单ID", required = true, example = "1024")
    @PreAuthorize("@ss.hasAnyPermissions('production:manager-list:detail','placeorder:optimize:manual-optimization','producePlan:optimize:manual-optimization')")
    public CommonResult<List<OrderRoomBodyRespVO>> getRoomAndBody(@RequestParam("planId") Long planId) {
        return success(orderService.getRoomAndBody(planId));
    }

    @GetMapping("/get-module")
    @Operation(summary = "生产单详情-数量信息")
    @Parameters({
            @Parameter(name = "orderId", description = "生产单编号", required = true, example = "1024"),
            @Parameter(name = "deleted", description = "是否删除", example = "false")
    })
    @PreAuthorize("@ss.hasPermission('production:manager-list:detail')")
    public CommonResult<Map<String, Object>> getModule(@RequestParam("orderId") Long orderId,
                                                        @RequestParam(value = "deleted", required = false, defaultValue = "false") Boolean deleted) {
        if (deleted == null) {
            deleted = false;
        }
        return success(orderService.getModule(orderId, !deleted ? 0 : 1));
    }

    @PostMapping("/get-platesDetailsPage")
    @Operation(summary = "生产单详情-板件详细信息(分页)")
    @OperateLog(enable = false)
    @PreAuthorize("@ss.hasPermission('production:manager-list:detail')")
    public CommonResult<PageResult<OrderPlatesDetailReqVO>> platesDetails(@Valid @RequestBody OrderBodyPageRespVO orderBodyPageRespVO) {
        if (orderBodyPageRespVO.getDeleted() == null) {
            orderBodyPageRespVO.setDeleted(false);
        }
        return success(orderService.getPlatesDetail(orderBodyPageRespVO.getOrderId(),
                orderBodyPageRespVO.getRoomIds(), orderBodyPageRespVO.getBodyIds(),
                orderBodyPageRespVO.getGroupIds(), orderBodyPageRespVO.getGroupName(),
                orderBodyPageRespVO.getPageNo(), orderBodyPageRespVO.getPageSize(), !orderBodyPageRespVO.getDeleted() ? 0 : 1));
    }

    @PostMapping("/get-partsDetailsPage")
    @Operation(summary = "生产单详情-配件详细信息(分页)")
    @OperateLog(enable = false)
    @PreAuthorize("@ss.hasPermission('production:manager-list:detail')")
    public CommonResult<PageResult<OrderPartsRespVO>> partsDetails(@Valid @RequestBody OrderBodyPageRespVO orderBodyPageRespVO) {
        if (orderBodyPageRespVO.getDeleted() == null) {
            orderBodyPageRespVO.setDeleted(false);
        }
        Set<String> types = new HashSet<>();
        // 配件
        types.add(CategoryEnum.HARDWARE.getValue());
        types.add(CategoryEnum.EDGING.getValue());

        return success(orderService.getPartsDetail(orderBodyPageRespVO.getOrderId(),
                orderBodyPageRespVO.getRoomIds(), orderBodyPageRespVO.getBodyIds(),
                orderBodyPageRespVO.getGroupIds(), orderBodyPageRespVO.getPartsName(),
                orderBodyPageRespVO.getPageNo(), orderBodyPageRespVO.getPageSize(), !orderBodyPageRespVO.getDeleted() ? 0 : 1, types));
    }


    @PostMapping("/get-goodsDetailsPage")
    @Operation(summary = "生产单详情-板材详细信息(分页)")
    @OperateLog(enable = false)
    @PreAuthorize("@ss.hasPermission('production:manager-list:detail')")
    public CommonResult<PageResult<OrderGoodsDetailRespVO>> goodsDetails(@Valid @RequestBody OrderBodyPageRespVO orderBodyPageRespVO) {
        if (orderBodyPageRespVO.getDeleted() == null) {
            orderBodyPageRespVO.setDeleted(false);
        }
        return success(orderService.getGoodsDetail(orderBodyPageRespVO.getOrderId(),
                orderBodyPageRespVO.getRoomIds(), orderBodyPageRespVO.getBodyIds(),
                orderBodyPageRespVO.getGroupIds(), orderBodyPageRespVO.getGoodsId(),
                orderBodyPageRespVO.getPageNo(), orderBodyPageRespVO.getPageSize(), !orderBodyPageRespVO.getDeleted() ? 0 : 1));
    }

    @PostMapping("/get-componentDetailsPage")
    @Operation(summary = "生产单详情-组件详细信息(分页)")
    @OperateLog(enable = false)
    @PreAuthorize("@ss.hasPermission('production:manager-list:detail')")
    public CommonResult<PageResult<OrderPartsRespVO>> componentDetails(@Valid @RequestBody OrderBodyPageRespVO orderBodyPageRespVO) {
        if (orderBodyPageRespVO.getDeleted() == null) {
            orderBodyPageRespVO.setDeleted(false);
        }
        Set<String> types = new HashSet<>();
        // 配件
        types.add(CategoryEnum.ASSEMBLY.getValue());

        return success(orderService.getPartsDetail(orderBodyPageRespVO.getOrderId(),
                orderBodyPageRespVO.getRoomIds(), orderBodyPageRespVO.getBodyIds(),
                orderBodyPageRespVO.getGroupIds(), orderBodyPageRespVO.getPartsName(),
                orderBodyPageRespVO.getPageNo(), orderBodyPageRespVO.getPageSize(), !orderBodyPageRespVO.getDeleted() ? 0 : 1, types));
    }

    @DeleteMapping("/delete-body")
    @Operation(summary = "删除柜体")
    @PreAuthorize("@ss.hasPermission('production:manager-list:deleteCabinet')")
    public CommonResult<Boolean> deleteBody(@Valid @RequestBody OrderModuleParameterRespVO orderModuleParameterRespVO) {
        orderService.updateDeleteBody(orderModuleParameterRespVO.getOrderId(), orderModuleParameterRespVO.getRoomIds(),
                orderModuleParameterRespVO.getBodyId(), OrderDeletedEnum.DELETED.getStatus());
        return success(true);
    }

    @PutMapping("/restore-body")
    @Operation(summary = "还原柜体")
    @PreAuthorize("@ss.hasPermission('production:manager-list:restoreCabinet')")
    public CommonResult<Boolean> restoreBody(@Valid @RequestBody OrderModuleParameterRespVO orderModuleParameterRespVO) {
        orderService.updateRestoreBody(orderModuleParameterRespVO.getOrderId(), orderModuleParameterRespVO.getRoomIds(),
                orderModuleParameterRespVO.getBodyId(), OrderDeletedEnum.NOT_DELETED.getStatus());
        return success(true);
    }

    @DeleteMapping("/realDeleted")
    @Operation(summary = "作废中删除")
    @Parameter(name = "orderId", description = "生产单编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('production:manager-list:nullify')")
    public CommonResult<Boolean> realDeleted(@RequestParam("orderId") Long orderId) {
        orderService.realDeletedOrder(orderId);
        return success(true);
    }

    //    统计
    //    生产单超期（工作台）
    @GetMapping("/getOrderOverdue")
    @Operation(summary = "生产单超期 （工作台）")
    @PreAuthorize("@ss.hasPermission('homePage:work:be-overdue')")
    public CommonResult<PageResult<OrderOverdueRespVO>> getOrderOverdue(@Valid PageParam pageParam) {
        return success(orderService.getOrderOverdue(pageParam));
    }

    //    生产单到期告警 （工作台）
    @GetMapping("/getOrderWarn")
    @Operation(summary = "生产单到期告警 （工作台）")
    @PreAuthorize("@ss.hasPermission('homePage:work:completed-today')")
    public CommonResult<PageResult<OrderOverdueRespVO>> getOrderNear(@Valid PageParam pageParam) {
        return success(orderService.getOrderNear(pageParam));
    }





    @GetMapping("/getAllData")
    @Operation(summary = "获取生产单的所有数据")
    public CommonResult<OrderAllData> getOrderAllData(@Schema(description = "生产单id") @RequestParam(required = false) Long orderId,
                                                            @Schema(description = "排单id") @RequestParam(required = false) Long planId) {

        return CommonResult.success(orderService.getOrderAllData(orderId,planId));
    }



}