/*
 *  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.annotation.AnonymousAccess;
import com.youchain.annotation.Log;
import com.youchain.basicdata.domain.*;
import com.youchain.basicdata.repository.PointRepository;
import com.youchain.basicdata.repository.StockRepository;
import com.youchain.basicdata.service.AreaService;
import com.youchain.basicdata.service.ItemService;
import com.youchain.basicdata.service.StockService;
import com.youchain.basicdata.service.PointService;
import com.youchain.basicdata.service.dto.AreaDto;
import com.youchain.basicdata.service.dto.BillTypeDto;
import com.youchain.basicdata.service.dto.PointDto;
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.Zhengli;
import com.youchain.businessdata.inputJson.buttenJson.AsnDetailButton;
import com.youchain.businessdata.repository.AsnDetailRepository;
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.mapstruct.AsnMapper;
import com.youchain.businessdata.service.mapstruct.InventoryMapper;
import com.youchain.config.FileProperties;
import com.youchain.exception.BadRequestException;
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 InventoryRepository inventoryRepository;
    private final PointMapper pointMapper;
    private final FileProperties properties;
    private final AsnService asnService;
    private final AsnDetailRepository asnDetailRepository;
    private final AsnMapper asnMapper;
    private final InventoryMapper inventoryMapper;
    private final XppRecordRepository xppRecordRepository;
    private final XppRecordService xppRecordService;
    private final PointRepository pointRepository;

    @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')")
    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);

        //刷新
        asnDetailService.updateAsnStatus(asnDetail.getAsn());

        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());
        asnDetailService.update(resources);
        asnService.update(asnMapper.toEntity(byId1));
        asnDetailService.updateAsnStatus(resources.getAsn());
        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
    public ResponseEntity<Object> putawayInvApp(@RequestBody IRkPut s) {
        log.info("s:" + 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();
            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')")
    public ResponseEntity<Object> putawayXppApp(@RequestBody IRkPut s) {
        int seq = s.getSeq();
        if (seq == 1) {
            XppRecord xppRecord = null;
            String ewm = s.getEwm();
            xppRecord = xppRecordRepository.findByCode(ewm);
            if (xppRecord == null) {
                return new ResponseEntity<>(ewm + "二维码未采集", BAD_REQUEST);
            }
            if (!xppRecord.getStatus().equals(BizStatus.RECEIVED) && !xppRecord.getStatus().equals(BizStatus.RETENTION_IN)) {
                throw new BadRequestException(xppRecord.getItem().getCode() + "现品票状态不正确");
            }
            if (!xppRecord.getStatus().equals(BizStatus.RECEIVED) && !xppRecord.getStatus().equals(BizStatus.RETENTION_IN)) {
                return new ResponseEntity<>("现品票状态不正确", BAD_REQUEST);
            }
            RRkXpp map = xppRecordService.xppAnalysis(xppRecord);
            return new ResponseEntity<>(map, HttpStatus.OK);
        }
        if (seq == 2) {
            String pointCode = s.getPointCode();
            if (pointCode == null || pointCode.equals("")) {
                return new ResponseEntity<>("库位不能为空", BAD_REQUEST);
            }
            Point point = pointService.getPoint(pointCode, null, null, null);
            if (point == null) {
                return new ResponseEntity<>(pointCode + "库位不存在", BAD_REQUEST);
            }
            Area area = point.getArea();
            for (String ewm : s.getEwms()) {
                XppRecord xppRecord = xppRecordRepository.findByCode(ewm);
                AsnDetail d = xppRecordService.addAsnDetail(xppRecord);
                putawayInv(d.getId(), area.getId(), point.getId(), d.getOrderQty(), ewm);
            }
        }
        return new ResponseEntity<>("操作成功", HttpStatus.OK);
    }


    @PostMapping("/putawayConfirmXpp")
    @Log("现品票上架确认-系统")
    @ApiOperation("现品票上架确认-系统")
    @PreAuthorize("@el.check('super:man')")
    @Transactional(rollbackFor = Exception.class)
    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();
        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')")
    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, null, ad.getPoint().getArea(), inventoryDto.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) {
                    this.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 + "库区未填写");
            }
            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 = "/invVerify")
    @PreAuthorize("@el.check('super:man')")
    @Transactional(rollbackFor = Exception.class)
    public ApiResult invVerify(@RequestBody Long[] ids) {
        for (Long id : ids) {
            Asn asn = asnService.getEntity(id);
            //AsnDto asnDto = asnService.findById(id);
            if (Objects.isNull(asn)) {
                // 通用异常，使用自定义状态码
                throw new BadRequestException(HttpStatus.NOT_FOUND, id + "未查到该数据");
            }
            //库区的判断
            Area area = asn.getArea();
            if (Objects.isNull(area)) {
                // 通用异常，使用自定义状态码
                throw new BadRequestException(HttpStatus.NOT_FOUND, id + "库区未填写");
            }
            BillType bt = asn.getBillType();
            if (bt.getBezl() && asn.getZlBy() == null) {
                throw new BadRequestException(asn.getCode() + "该单子还未整理，请先整理");
            }
            if (bt.getBecy() && asn.getCyBy() == null) {
                throw new BadRequestException(asn.getCode() + "该单子还未抽样，请先抽样");
            }
            if (bt.getBezj() && asn.getZjBy() == null) {
                throw new BadRequestException(asn.getCode() + "该单子还未质检，请先质检");
            }
//            if (!area.getBesh()){
//                // 通用异常，使用自定义状态码
//                throw new BadRequestException(HttpStatus.NOT_FOUND,id+"的库区的仓库不是接收仓库");
//            }
            //查询 那个明细需要确认
            List<AsnDetail> asnDetails = asnDetailRepository.queryByAsnId(id);
            if (!asnDetails.isEmpty()) {
                for (AsnDetail asnDetailData : asnDetails) {
                    if (asnDetailData.getOrderQty() == asnDetailData.getReceivedQty()) {
                        continue;
                    }
                    //1.库区为接收仓库，库位为每个detail上的库位，如果没有则提示
                    //2.库区不为接收仓库，库位取item上维护的库位，如果没有则提示
                    if (area.getBexb()) {//判断库区是否为接受仓库
                        if (Objects.isNull(asnDetailData.getPoint())) {
                            // 通用异常，使用自定义状态码
                            throw new BadRequestException(HttpStatus.NOT_FOUND, id + "是接受仓库 副表" + asnDetailData.getId() + "的库位未填写");
                        }
                    } else {
                        if (Objects.isNull(asnDetailData.getItem())) {
                            // 通用异常，使用自定义状态码
                            throw new BadRequestException(HttpStatus.NOT_FOUND, id + "是不是接受仓库 副表" + asnDetailData.getId() + "的物料未填写");
                        }
                    }
                    ApiResult apiResult = null;

                    if (asnDetailData.getReceivedQty() > 0) {
                        // 通用异常，使用自定义状态码
                        throw new BadRequestException(HttpStatus.NOT_FOUND, id + "的副表" + asnDetailData.getId() + "的物料已经单一入库无法使用整单入库");
                    }
                    Point p = asnDetailData.getPoint();
                    if (p == null) {
                        p = pointRepository.findByCode("MR-CH");
                    }
                    apiResult = this.putawayInv(asnDetailData.getId(), asn.getArea().getId(), p.getId(), (asnDetailData.getOrderQty() - asnDetailData.getReceivedQty()), null);
                    if (apiResult.getStatus() == 200) {
                        //收货日期改成当前日期 数量累计
                        asn.setReceivedDate(new Timestamp(System.currentTimeMillis()));
                        //asn.setReceivedQuantity(asn.getReceivedQuantity() + asnDetailData.getOrderQty());
                    } else {
                        // 通用异常，使用自定义状态码
                        throw new BadRequestException(HttpStatus.NOT_FOUND, apiResult.getMessage());
                    }
                    double pd = asn.getOrderQuantity() - asn.getReceivedQuantity();
                    if (pd == 0) {
                        asn.setStatus(BizStatus.RECEIVED);
                    } else if (pd > 0 && asn.getReceivedQuantity() > 0) {
                        asn.setStatus(BizStatus.RECEIVING);
                    }
                    asnService.update(asn);
                }
            }
        }
        return ApiResult.result(200, "入库确认成功", HttpStatus.OK);
    }


    public ApiResult putawayInv(@RequestBody Long asnDetailId, Long areaId, Long pointId, double recQty, String ewm) {
        AsnDetail d = asnDetailService.getEntity(asnDetailId);
        Area area = areaService.findEntityById(areaId);
        Point point = null;
        if (pointId != null) {
            point = pointService.findEntityById(pointId);
        } else {
            point = pointRepository.findByCode("MR-CH");
        }
        Point zzkw = null;
        if (area.getBexb()) {
            point = pointService.getPoint(area.getPointCode(), null, BaseStatus.HCKW, null);//取默认线边库位
            zzkw = d.getPoint();
            if (zzkw == null) {
                //取默认制造库位
                zzkw = pointService.getPoint("ZZKW", null, null, null);
            }
        }
        if (point == null) {
            throw new BadRequestException("请选择入库库位");
        }
        double unRecQty = d.getOrderQty() - d.getReceivedQty();
        if (recQty <= unRecQty) {
            String pc1 = null;
            //现品票确认将任务id回写到现品票表中
            XppRecord xppRecord = xppRecordRepository.findByCode(ewm);
            ItemKey ik = null;
            if (xppRecord != null) {
                if (!xppRecord.getStatus().equals(BizStatus.RECEIVED) && !xppRecord.getStatus().equals(BizStatus.RETENTION_IN)) {
                    throw new BadRequestException(d.getItem().getCode() + "现品票状态不正确");
                }
                pc1 = DateUtil.dateYmd(new Date());
                ik = xppRecord.getItemKey();
            }
            if (ik == null) {
                ik = itemKeyService.getItemKey(d.getItem(), pc1, null, null, null, null, null);
            }
            Task t = taskService.storeTask(d, null, area, ik, point, point, recQty);
            if (xppRecord != null) {
                xppRecord.setRkTask(t);
                xppRecord.setInvPoint(point);
                xppRecord.setStatus(BizStatus.PUTAWAY);
                xppRecord.setItemKey(ik);
                ewm = xppRecord.getEwm();
                xppRecordService.update(xppRecord);
            }
            d.setReceivedQty(d.getReceivedQty() + recQty);
            if (d.getReceivedQty().intValue() >= d.getOrderQty().intValue()) {
                d.setStatus(BizStatus.PUTAWAY);
            } else if (d.getReceivedQty().intValue() > 0) {
                d.setStatus(BizStatus.PUTAWAY);
            }
            asnDetailService.update(d);
            point.setStatus(BaseStatus.USED);
            pointService.update(point);
            Inventory inv = invService.getInventory(ik, area, point, zzkw, d.getDept(), BizStatus.RECEIVING_UP);
            t.setInvId(inv.getId());
            taskService.update(t);
            double srcQty = inv.getQuantity();
            inv.addQty(recQty);
            invService.update(inv);
            String billCode = null;
            if (d.getAsn() != null) {
                Asn asn = d.getAsn();
                billCode = asn.getCode();
                asn.setReceivedQuantity(asn.getReceivedQuantity() + recQty);
                if (asn.getReceivedQuantity().intValue() >= asn.getOrderQuantity().intValue()) {
                    asnService.update(asn);
                }
            }
            Point srcPoint = pointService.getPoint(null, null, BaseStatus.SHZC, null);
            InventoryLog log = invLogService.storeInventoryLog(BizStatus.RECEIVING_UP, BizStatus.ADD, billCode, area, ik, srcPoint, point, zzkw, srcQty, recQty, ewm,
                    BizStatus.ASN, d.getId(), inv.getId(), d.getRemark());
        } else {
            throw new BadRequestException(d.getItem().getCode() + "收货数量不能大于未收数量");
        }
        return ApiResult.result(200, "", HttpStatus.OK);

    }

    @PostMapping("/zhengli")
    @Log("明细整理")
    @ApiOperation("明细整理")
    @PreAuthorize("@el.check('super:man')")
    public ResponseEntity<Object> zhengli(@RequestBody Zhengli zhengli) {
        try {
            asnDetailService.zhengli(zhengli);
            return new ResponseEntity<>(ApiResult.success("整理成功", null), HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(ApiResult.fail(HttpStatus.BAD_REQUEST.value(), "整理失败：" + e.getMessage(), null), HttpStatus.BAD_REQUEST);
        }
    }

}
