/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.youchain.businessdata.rest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.youchain.DuplicateSubmission.DuplicateSubmission;
import com.youchain.annotation.AnonymousAccess;
import com.youchain.annotation.Log;
import com.youchain.basicdata.domain.*;
import com.youchain.basicdata.repository.BigItemRepository;
import com.youchain.basicdata.repository.BomAccountRepository;
import com.youchain.basicdata.repository.StockRepository;
import com.youchain.basicdata.service.*;
import com.youchain.basicdata.service.dto.AreaDto;
import com.youchain.basicdata.service.mapstruct.PointMapper;
import com.youchain.businessdata.inputJson.IRkConfirm;
import com.youchain.businessdata.inputJson.IRkInv;
import com.youchain.businessdata.inputJson.IRkPut;
import com.youchain.businessdata.domain.*;
import com.youchain.businessdata.inputJson.IScanPut;
import com.youchain.businessdata.inputJson.buttenJson.AsnDetailButton;
import com.youchain.businessdata.repository.AsnDetailRepository;
import com.youchain.businessdata.repository.AsnRepository;
import com.youchain.businessdata.repository.InventoryRepository;
import com.youchain.businessdata.repository.XppRecordRepository;
import com.youchain.businessdata.returnJson.RRkXpp;
import com.youchain.businessdata.service.*;
import com.youchain.businessdata.service.dto.*;
import com.youchain.businessdata.service.impl.SparepartsServiceImpl;
import com.youchain.businessdata.service.mapstruct.AsnMapper;
import com.youchain.businessdata.service.mapstruct.InventoryMapper;
import com.youchain.config.FileProperties;
import com.youchain.exception.BadRequestException;
import com.youchain.exception.OperBadRequestException;
import com.youchain.exception.handler.ApiError;
import com.youchain.exception.handler.ApiResult;
import com.youchain.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Pageable;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;

import java.beans.Transient;
import java.io.IOException;
import java.sql.Timestamp;
import java.time.format.DateTimeFormatter;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import org.springframework.transaction.annotation.Transactional;

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

/**
 * @author hjl
 * @website https://eladmin.vip
 * @date 2023-08-14
 **/
@RestController
@RequiredArgsConstructor
@Api(tags = "asn_detail管理")
@Slf4j
@RequestMapping("/api/asnDetail")
public class AsnDetailController {

    private final AsnDetailService asnDetailService;

    private final ItemService itemService;

    private final TaskService taskService;

    private final StockService stockService;
    private final StockRepository stockRepository;

    private final ItemKeyService itemKeyService;

    private final InventoryService invService;

    private final InventoryLogService invLogService;

    private final PointService pointService;

    private final AreaService areaService;
    private final BomAccountService bomAccountService;

    private final InventoryRepository inventoryRepository;
    private final PointMapper pointMapper;
    private final FileProperties properties;
    private final AsnService asnService;
    private final AsnDetailRepository asnDetailRepository;
    private final AsnRepository asnRepository;
    private final AsnMapper asnMapper;
    private final InventoryMapper inventoryMapper;
    private final XppRecordRepository xppRecordRepository;
    private final XppRecordService xppRecordService;
    private final BigItemRepository bigItemRepository;
    private final BomAccountRepository bomAccountRepository;
    private final SparepartsServiceImpl sparepartsServiceImpl;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @AnonymousAccess
    public void exportAsnDetail(HttpServletResponse response, AsnDetailQueryCriteria criteria) throws Exception {
        asnDetailService.download(asnDetailService.queryAll(criteria), response);
    }

    @PostMapping("/getIdData")
    @Log("根据id查询asn_detail")
    @ApiOperation("根据id查询asn_detail")
    @AnonymousAccess
    public ResponseEntity<Object> getIdData(@RequestBody Long ids) {
        return new ResponseEntity<>(asnDetailRepository.queryByAsnId(ids), HttpStatus.OK);
    }


    @GetMapping
    @Log("查询asn_detail")
    @ApiOperation("查询asn_detail")
    @AnonymousAccess
    public ResponseEntity<Object> queryAsnDetail(AsnDetailQueryCriteria criteria, Pageable pageable) {
        return new ResponseEntity<>(asnDetailService.queryAll(criteria, pageable), HttpStatus.OK);
    }

    @GetMapping("/queryAsnDetailAll")
    @Log("查询asn_detail全部数据")
    @ApiOperation("查询asn_detail全部数据")
    @AnonymousAccess
    public ResponseEntity<Object> queryAsnDetailAll(AsnDetailQueryCriteria criteria) {
        return new ResponseEntity<>(asnDetailService.queryAll(criteria), HttpStatus.OK);
    }

    @PostMapping
    @Log("新增asn_detail")
    @ApiOperation("新增asn_detail")
    @PreAuthorize("@el.check('super:man')")
    @Transactional
    public ResponseEntity<Object> createAsnDetail(@Validated @RequestBody AsnDetail asnDetail) {
        asnDetail.setStatus(BizStatus.OPEN);
        asnDetail.setDept(UserUtils.getDept());
        if (asnDetail.getRemark() == null && asnDetail.getAsn().getDescription() != null) {
            asnDetail.setRemark(asnDetail.getAsn().getDescription());
        }
        asnDetailService.create(asnDetail);
//        Stock stock=asnDetail.getStock();
//        stock.setStatus(BaseStatus.USED);
//        stockService.update(stock);
        //orderQty
        //添加订单数量
        if (asnDetail.getOrderQty() != null && asnDetail.getOrderQty() != 0) {
            Asn asn = asnDetail.getAsn();
            asn.setOrderQuantity(asn.getOrderQuantity() + asnDetail.getOrderQty());
            asnService.update(asn);
        }
        return new ResponseEntity<>(HttpStatus.OK);
    }



    @PutMapping
    @Log("修改asn_detail")
    @ApiOperation("修改asn_detail")
    @PreAuthorize("@el.check('super:man')")
    public ResponseEntity<Object> updateAsnDetail(@Validated @RequestBody AsnDetail resources) {
        AsnDetailDto byId = asnDetailService.findById(resources.getId());
        AsnDto byId1 = asnService.findById(resources.getAsn().getId());
        byId1.setOrderQuantity((byId1.getOrderQuantity() - byId.getOrderQty()) + resources.getOrderQty());
        asnDetailService.update(resources);
        asnService.update(asnMapper.toEntity(byId1));
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }


    @DeleteMapping
    @Log("删除asn_detail")
    @ApiOperation("删除asn_detail")
    @PreAuthorize("@el.check('super:man')")
    public ResponseEntity<Object> deleteAsnDetail(@RequestBody Long[] ids) {
        asnDetailService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @PostMapping("/putawayInvApp")
    @Log("APP现品票上架-单个")
    @ApiOperation("APP现品票上架-单个")
    @AnonymousAccess
    @Transactional
    public ResponseEntity<Object> putawayInvApp(@RequestBody IRkPut s) {
        String pointCode = s.getPointCode();
        String ewm = s.getEwm();
        int seq=s.getSeq();
        XppRecord xppRecord =null;
        Point point =null;
        RRkXpp map = new RRkXpp();
        AsnDetail d=null;
        xppRecord = xppRecordRepository.findByCode(ewm);
        if(xppRecord==null){
            return new ResponseEntity<>(ewm + "未收货", BAD_REQUEST);
        }
        d=xppRecord.getAsnDetailId();
        if(d.getReceivedQty()>0){
            return new ResponseEntity<>(ewm + "已上架，不能重复上架", BAD_REQUEST);
        }
        if(seq==1){//扫描列表
            Item it=d.getItem();
            map.setItemCode(it.getCode());
            map.setItemName(it.getName());
            map.setAc(xppRecord.getAc());
            map.setDdbh(xppRecord.getDdbh());
            map.setNrs(xppRecord.getNrs());
            map.setNrzsr(DateUtil.dateYmd(xppRecord.getNrDate()));
            map.setFzh(xppRecord.getFzh());
            map.setTjkw(it.getPoint()==null?null:it.getPoint().getCode());
            return new ResponseEntity<>(map, HttpStatus.OK);
        }
        if (seq==2) {//列表提交上架
            if(pointCode==null||!pointCode.equals("")){
                Point dstPoint=d.getItem().getPoint();
                if(dstPoint==null){
                    return new ResponseEntity<>(d.getItem().getCode() + "品番未维护库位", BAD_REQUEST);
                }
                point=dstPoint;
                pointCode=dstPoint.getCode();
            }else {
                point = pointService.getPoint(pointCode, null, null, null);
                if (point == null) {
                    return new ResponseEntity<>(pointCode + "库位不存在", BAD_REQUEST);
                }
            }
            Area area=point.getArea();
            asnDetailService.putawayInv(d.getId(),area.getId(),point.getId(),s.getQty(),ewm);
        }
        return new ResponseEntity<>("操作成功", HttpStatus.OK);
    }

    @PostMapping("/putawayXppApp")
    @Log("扫描现品票上架APP")
    @ApiOperation("扫描现品票上架APP")
    @PreAuthorize("@el.check('super:man')")
    @Transactional
    @DuplicateSubmission
    public ResponseEntity<Object> putawayXppApp(@RequestBody IRkPut s) {
        int seq=s.getSeq();
        if(seq==1){
//            if(s.getPageName()!=null&&s.getPageName().equals("制造投料")) {
//                type=BillParmType.XPP_2001;
//            }
            RRkXpp map = xppRecordService.xppAnalysis(s.getEwm(), s.getType());
            return new ResponseEntity<>(map, HttpStatus.OK);
        }
        if (seq==2||seq==3) {//库存上架
            String pointCode = s.getPointCode();
            String[] str=pointCode.split("]");
            String bomItemCode=null;
            String bonded=null;
            if(str.length>1){//固定库位标签
                pointCode=str[3];
                bomItemCode=str[0];
                bonded=str[2];
            }
            if (pointCode == null||pointCode.equals("")) {
                throw  new BadRequestException( "库位不能为空");
            }
            Point point = pointService.getPoint(pointCode,null, null, null);
            if (point == null) {
                throw new OperBadRequestException(pointCode + "库位不存在");
            }
            if(bomItemCode==null){
                bomItemCode=point.getItemCode();
            }
            Area area=point.getArea();
            for(String ewm:s.getEwms()){
                if(seq==2) {//收货上架
                    //只能材管库位
                    if(!point.getType().equals(BaseStatus.CH)){
                        throw new OperBadRequestException(point.getCode()+"库位不为材管库位");
                    }
                    XppRecord xppRecord = xppRecordService.saveXppRecord(ewm, point.getArea(), BillParmType.XPP_1001);
                    AsnDetail asnDetail = xppRecordService.addAsnDetail(xppRecord);
                    String nrcs=xppRecord.getRelaCode();
                    if(nrcs.equals("00209")||nrcs.equals("00609")||nrcs.equals("00683")||nrcs.equals("00809")){
                        asnDetail.setPropC2(BaseStatus.BS);
                    }else {
                        asnDetail.setPropC2(BaseStatus.KS);
                    }
                    asnDetailRepository.save(asnDetail);
                    asnDetailService.putawayInv(asnDetail.getId(), area.getId(), point.getId(), xppRecord.getNrs(), xppRecord.getEwm());
                    //获取品番，如果品番为台车库位码，则台车配料
                    if(!nrcs.equals("00404")&&!nrcs.equals("00405")) {
                        String tckw = ewm.substring(3, 13);
                        List<BomAccount> bs = bomAccountRepository.queryTckwBom(tckw, null);
                        if (bs.size() > 0) {
                            bomAccountService.bomInvDeal(bs, xppRecord.getNrs(), BizStatus.TC_ZGP_OUT, tckw, xppRecord.getId(), xppRecord.getEwm(),"台车配料支给品出库");
                        }
                    }
                }else if(seq==3){//制造投料
                    if(!point.getType().equals(BaseStatus.ZZKW)){
                        throw new OperBadRequestException(point.getCode()+"库位不为制造库位");
                    }
                    if(bonded==null){
                        throw new OperBadRequestException(bonded + "税别不能为空");
                    }
                    String xppItemCode = ewm.substring(3, 13);
                    if(!xppItemCode.equals(bomItemCode)){
                        throw new OperBadRequestException("现品票品番"+xppItemCode+"和库位品番"+bomItemCode+"不一致");
                    }
                    XppRecord xppRecord = xppRecordService.saveXppRecord(ewm,point.getArea(),BillParmType.XPP_2001);
                    xppRecordService.xppPutaway(ewm,xppRecord,bonded,bomItemCode,point);
                    String nrcs=xppRecord.getRelaCode();
                    if(!nrcs.equals("00404")&&!nrcs.equals("00405")) {
                        //获取品番，如果品番为台车库位码，则台车配料
                        String tckw = ewm.substring(3, 13);
                        List<BomAccount> bs = bomAccountRepository.queryTckwBom(tckw, null);
                        if (bs.size() > 0) {
                            XppRecord xppRecord2 = xppRecordRepository.findByEwmType(ewm,BillParmType.XPP_1001);
                            if(xppRecord2==null) {
                                bomAccountService.bomInvDeal(bs, xppRecord.getNrs(), BizStatus.TC_ZGP_OUT, tckw, xppRecord.getId(), xppRecord.getEwm(), "台车配料支给品出库");
                            }
                        }
                    }
                }
            }
        }
        return new ResponseEntity<>("操作成功", HttpStatus.OK);
    }

    @PostMapping("/collectPutAway")
    @Log("现品票上架")
    @ApiOperation("现品票上架")
    @AnonymousAccess
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<Object> collectPutAway(@RequestBody HashMap rk) {
        Long pointId=Long.parseLong(rk.get("pointId").toString());
        String type=rk.get("type").toString();
        Point point=pointService.findEntityById(pointId);
        String ewm=rk.get("ewm").toString();
        if(type.equals(BillParmType.XPP_1001)){//收货上架
            XppRecord xppRecord = xppRecordService.saveXppRecord(rk.get("ewm").toString(),point.getArea(),type);
            AsnDetail asnDetail = xppRecordService.addAsnDetail(xppRecord);
            String nrcs=xppRecord.getRelaCode();
            if(nrcs.equals("00209")||nrcs.equals("00609")||nrcs.equals("00683")||nrcs.equals("00809")){
                asnDetail.setPropC2(BaseStatus.BS);
            }else {
                asnDetail.setPropC2(BaseStatus.KS);
            }
            asnDetailService.putawayInv(asnDetail.getId(),point.getArea().getId(),pointId,xppRecord.getNrs(),xppRecord.getEwm());
            //获取品番，如果品番为台车库位码，则台车配料
            String tckw=ewm.substring(3,13);
            List<BomAccount> bs = bomAccountRepository.queryTckwBom(tckw,null);
            if(bs.size()>0){
                bomAccountService.bomInvDeal(bs,xppRecord.getNrs(),BizStatus.TC_ZGP_OUT,tckw,xppRecord.getId(),xppRecord.getEwm(),"台车配料支给品出库");
            }
        }else  if(type.equals(BillParmType.XPP_2001)){//制造投料上架
            //查找线边库存是否存在，插入
            Long bomId=Long.parseLong(rk.get("bomId").toString());
            BomAccount bom=bomAccountRepository.getById(bomId);
            String bomItemCode=bom.getItem().getCode();
            String xppItemCode = ewm.substring(3, 13);
            if(!xppItemCode.equals(bomItemCode)){
                throw new BadRequestException("现品票品番"+xppItemCode+"和库位品番"+bomItemCode+"不一致");
                //return new ResponseEntity<>( "现品票品番"+xppItemCode+"和库位品番"+bomItemCode+"不一致", BAD_REQUEST);
            }
            XppRecord xppRecord = xppRecordService.saveXppRecord(ewm,point.getArea(),BillParmType.XPP_2001);
            xppRecordService.xppPutaway(ewm,xppRecord,bom.getBonded(),bomItemCode,point);

        }
        return new ResponseEntity<>("操作成功", HttpStatus.OK);
    }


    @PostMapping("/putawayConfirmXpp")
    @Log("现品票上架确认-系统")
    @ApiOperation("现品票上架确认-系统")
    @PreAuthorize("@el.check('super:man')")
    @Transactional(rollbackFor = Exception.class)
    @DuplicateSubmission
    public ResponseEntity<Object> putawayConfirmXpp(@RequestBody HashMap rk) {
        Long asnDetailId=Long.parseLong(rk.get("detailId").toString());
        AsnDetailDto dto= asnDetailService.findById(asnDetailId);
        Double recQty=dto.getOrderQty()-dto.getReceivedQty();
        asnDetailService.putawayInv(asnDetailId, Long.parseLong(rk.get("areaId").toString())
                , Long.parseLong(rk.get("pointId").toString()),recQty,null);
        return new ResponseEntity<>("操作成功", HttpStatus.OK);
    }

    @Log("取消上架")
    @ApiOperation("取消上架")
    @PostMapping("/cancelPut")
    @PreAuthorize("@el.check('super:man')")
    @Transactional
    public ResponseEntity<Object> cancelPut(@RequestBody Long[] ids) {
       for (Long id:ids){
           XppRecord xppRecord = xppRecordService.getEntity(id);
           AsnDetail ad=xppRecord.getAsnDetailId();
           if(ad==null){
               return new ResponseEntity("找不到上架记录", BAD_REQUEST);
           }
           if (!xppRecord.getStatus().equals(BizStatus.PUTAWAY)) {
               throw new BadRequestException("上架状态才能取消上架");
           }
           Task t=xppRecord.getRkTask();
//           List<Task> ts=taskService.queryTask(ad.getId(),null,null,null);
//           for(Task t:ts) {
               asnDetailService.cancelPut(t.getId(), xppRecord);
//           }
           xppRecordRepository.delete(xppRecord);
       }
        return new ResponseEntity("取消成功", HttpStatus.OK);
    }
    @Log("的操作")
    @ApiOperation("取消收货的操作")
    @PostMapping("/rkAndQxButtonQX")
    @PreAuthorize("@el.check('super:man')")
    @Transactional
    public ApiResult rkAndQxButtonQX(@RequestBody AsnDetailButton asnDetailButton) {
        if (!asnDetailButton.getAsnDetailDataS().isEmpty()) {
            for (AsnDetail ad : asnDetailButton.getAsnDetailDataS()) {
                Asn asn = ad.getAsn();
                if (Objects.isNull(asn)){
                    throw new BadRequestException(HttpStatus.NOT_FOUND, ad.getItem().getCode() + "没有主单（订单序号）");
                }
                AsnDto byId = asnMapper.toDto(asn);
                //取消收货
                //物料  点位    增加/减少  1
                InventoryLogQueryCriteria inventoryLogQueryCriteria = new InventoryLogQueryCriteria();
                inventoryLogQueryCriteria.setIncDec(1);
                inventoryLogQueryCriteria.setItemCode(ad.getItem().getCode());
                inventoryLogQueryCriteria.setSrcPointCode(ad.getPoint().getCode());
                inventoryLogQueryCriteria.setAreaCode(byId.getArea().getCode());
                List<InventoryLogDto> inventoryLogDtos = invLogService.queryAll(inventoryLogQueryCriteria);
                if (inventoryLogDtos.isEmpty()) {
                    throw new BadRequestException(HttpStatus.NOT_FOUND, ad.getId() + "未发现库存日志");
                }
                //判断库存数量 是否大于取消的数量
//                    for (InventoryLogDto inve : inventoryLogDtos) {
                InventoryLogDto inve = inventoryLogDtos.get(0);
                //目标标点位
                Point dstPoint = inve.getDstPoint();
                //查库存
                InventoryQueryCriteria inventoryQueryCriteria = new InventoryQueryCriteria();
                inventoryQueryCriteria.setPointCode(dstPoint.getCode());
                inventoryQueryCriteria.setItemKey(inve.getItemKey());
                inventoryQueryCriteria.setAreaName(byId.getArea().getName());
                List<InventoryDto> inventoryDtos = invService.queryAll(inventoryQueryCriteria);
                if (!inventoryDtos.isEmpty()) {
                    InventoryDto inventoryDto = inventoryDtos.get(0);
                    double pd = inventoryDto.getQuantity()-ad.getReceivedQty();
                    if (pd>0){
                        inventoryDto.setQuantity((int)pd);
                        invService.update(inventoryMapper.toEntity(inventoryDto));
                    }else if (pd==0d){
                        inventoryRepository.deleteById(inventoryDto.getId());
                    }else {
                        throw new BadRequestException(HttpStatus.NOT_FOUND, ad.getItem().getCode()+"库存数量不满,无法取消");
                    }

                    //生成库存日志
                    InventoryLog inventoryLog = invLogService.storeInventoryLog(BizStatus.RECEIVING_CANCEL, BizStatus.REDUCE, asn.getCode(), ad.getPoint().getArea(), inve.getItemKey(),
                            pointMapper.toEntity(inventoryDto.getPoint()) , dstPoint, ad.getStock(), ad.getStock(), ad.getReceivedQty(), ad.getReceivedQty(), null,null,BizStatus.ASN, ad.getId(), inventoryDto.getId(), ad.getRemark());
                }
//                    }
                byId.setReceivedQuantity(byId.getReceivedQuantity()-ad.getReceivedQty());
                ad.setReceivedQty(0d);
                asnDetailService.update(ad);
                asnService.update(asnMapper.toEntity(byId));
            }
        }
        return ApiResult.result(200, "操作成功", HttpStatus.OK);
    }
    /**
     * 整单入库、单一入库、取消收货的操作
     *
     * @param asnDetailButton
     * @return
     */
    @Log("整单入库、单一入库、取消收货的操作")
    @ApiOperation("整单入库、单一入库、取消收货的操作")
    @PostMapping("/rkAndQxButton")
    @PreAuthorize("@el.check('super:man')")
    @Transactional(rollbackFor = Exception.class)
    public ApiResult rkAndQxButton(@RequestBody AsnDetailButton asnDetailButton) {
        if (asnDetailButton.getButton() == 1) {
            //整单入库
            long asnId = asnDetailButton.getId();
            AsnDto byId = asnService.findById(asnId);
            if (Objects.isNull(byId)) {
                // 通用异常，使用自定义状态码
                throw new BadRequestException(HttpStatus.NOT_FOUND, asnId + "未查到该数据");
            }
            //库区的判断
            AreaDto area = byId.getArea();
            if (Objects.isNull(area)) {
                // 通用异常，使用自定义状态码
                throw new BadRequestException(HttpStatus.NOT_FOUND, asnId + "库区未填写");
            }
            //查询 那个明细需要确认
            List<AsnDetail> asnDetails =asnDetailService.findAsnDetails(asnId,"1");
            if (!asnDetails.isEmpty()) {
                for (AsnDetail d : asnDetails) {
                    asnDetailService.putawayInv(d.getId(), byId.getArea().getId(), d.getPoint()==null?null:d.getPoint().getId(),(d.getOrderQty()-d.getReceivedQty()),null);
                    byId.setReceivedDate(new Timestamp(System.currentTimeMillis()));
                    byId.setReceivedQuantity(byId.getReceivedQuantity() + d.getOrderQty());

                    double pd = byId.getOrderQuantity() - byId.getReceivedQuantity();
                    if (pd == 0) {
                        byId.setStatus(BizStatus.RECEIVED);
                    } else if (pd > 0 && byId.getReceivedQuantity() > 0) {
                        byId.setStatus(BizStatus.RECEIVING);
                    }
                    asnService.update(asnMapper.toEntity(byId));
                }
            }
            return ApiResult.result(200, "入库确认成功", HttpStatus.OK);
        } else if (asnDetailButton.getButton() == 2) {
            double qty=asnDetailButton.getOneRNumber();
            long id = asnDetailButton.getId();
            AsnDto byId = asnService.findById(id);
            if (Objects.isNull(byId)) {
                // 通用异常，使用自定义状态码
                throw new BadRequestException(HttpStatus.NOT_FOUND, id + "未查到该数据");
            }
            //库区的判断
            AreaDto area = byId.getArea();
            if (Objects.isNull(area)) {
                // 通用异常，使用自定义状态码
                throw new BadRequestException(HttpStatus.NOT_FOUND, id + "库区未填写");
            }
            asnDetailService.putawayInv(id,area.getId(),asnDetailButton.getOneRPoint().getId(),qty,null);
        } else if (asnDetailButton.getButton() == 3) {
            long id = asnDetailButton.getId();
            AsnDto byId = asnService.findById(id);
            if (!asnDetailButton.getAsnDetailDataS().isEmpty()) {
                for (AsnDetail ad : asnDetailButton.getAsnDetailDataS()) {
                    List<Task> ts=taskService.queryTask(ad.getId(),null,null,null,null);
                    for(Task t:ts) {
                        asnDetailService.cancelPut(t.getId(),null);
                    }
                }
            }
        } else {
            throw new BadRequestException(HttpStatus.NOT_FOUND, asnDetailButton.getButton() + "的操作码不对 1、整单入库,2、单一入库,3取消收货");
        }
        return ApiResult.result(200, "操作成功", HttpStatus.OK);
    }


    @Log("入库确认")
    @ApiOperation("入库确认")
    @PostMapping(value = "/putawayAsn")
    @PreAuthorize("@el.check('super:man')")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity putawayAsn(@RequestBody Long[] ids) {
        for (Long id : ids) {
            Asn asn = asnRepository.getById(id);
            if (!asn.getStatus().equals(BizStatus.OPEN)) {
                throw new BadRequestException(asn.getCode()+ "状态不正确");
            }
            //查询 那个明细需要确认
            List<AsnDetail> asnDetails = asnDetailRepository.queryByAsnId(id);
            if (!asnDetails.isEmpty()) {
                for (AsnDetail asnDetail : asnDetails) {
                    if (asnDetail.getOrderQty() <= asnDetail.getReceivedQty()) {
                        continue;
                    }
                    asnDetailService.putawayInv(asnDetail.getId(),asnDetail.getPoint().getArea().getId(),asnDetail.getPoint().getId(),asnDetail.getOrderQty()-asnDetail.getReceivedQty(),null);
                }
            }
        }
        return new ResponseEntity("入库成功", HttpStatus.OK);
    }



}