/*
*  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.youchain.DuplicateSubmission.DuplicateSubmission;
import com.youchain.annotation.AnonymousAccess;
import com.youchain.annotation.Log;
import com.youchain.basicdata.domain.Item;
import com.youchain.basicdata.domain.Point;
import com.youchain.basicdata.service.PointService;
import com.youchain.businessdata.domain.*;
import com.youchain.businessdata.inputJson.IPTask;
import com.youchain.businessdata.inputJson.IScanPut;
import com.youchain.businessdata.inputJson.buttenJson.IPPickOut;
import com.youchain.businessdata.inputJson.buttenJson.PickOutButton;
import com.youchain.businessdata.inputJson.buttenJson.PickTicketButton;
import com.youchain.businessdata.repository.*;
import com.youchain.businessdata.returnJson.RPPickList;
import com.youchain.businessdata.returnJson.RPTaskList;
import com.youchain.businessdata.returnJson.RRkXpp;
import com.youchain.businessdata.service.*;
import com.youchain.businessdata.service.dto.PickOutDto;
import com.youchain.businessdata.service.dto.PickOutQueryCriteria;
import com.youchain.businessdata.service.dto.PickTicketDto;
import com.youchain.exception.BadRequestException;
import com.youchain.modules.system.domain.Dept;
import com.youchain.modules.system.domain.DictDetail;
import com.youchain.modules.system.domain.Job;
import com.youchain.modules.system.repository.JobRepository;
import com.youchain.modules.system.service.DictDetailService;
import com.youchain.modules.system.service.dto.DictQueryCriteria;
import com.youchain.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.Temperature;
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.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.*;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://eladmin.vip
* @author jiangkun
* @date 2024-02-21
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "pickOut管理")
@RequestMapping("/api/pickOut")
@Slf4j
public class PickOutController {

    private final PickOutService pickOutService;
    private final CodeUtils codeUtils;
    private final TaskLogService taskLogService;
    private final InventoryService inventoryService;
    private final InventoryLogService inventoryLogService;
    private final TaskService taskService;
    private final PickDetailService pickDetailService;
    private final PickTicketService pickTicketService;
    private final XppRecordRepository xppRecordRepository;
    private final XppRecordService xppRecordService;
    private final TaskLogRepository taskLogRepository;
    private final PointService pointService;
    private final ItemKeyService itemKeyService;
    private final PickDetailRepository pickDetailRepository;
    private final PickTicketRepository pickTicketRepository;
    private final PickOutRepository pickOutRepository;
    private final DictDetailService dictDetailService;
    private final JobRepository jobRepository;
    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @AnonymousAccess
    public void exportPickOut(HttpServletResponse response, PickOutQueryCriteria criteria) throws Exception {
        pickOutService.download(pickOutService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询pickOut")
    @ApiOperation("查询pickOut")
    @AnonymousAccess
    public ResponseEntity<Object> queryPickOut(PickOutQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(pickOutService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @PostMapping("/queryOutListApp")
    @Log("出库列表查询")
    @ApiOperation("出库列表查询")
    @AnonymousAccess
    public ResponseEntity<Object> queryOutListApp(@RequestBody IScanPut t){
        List<RPPickList> ts= pickOutService.queryOutList(t);
        return new ResponseEntity<>(ts,HttpStatus.OK);
    }

    @PostMapping("/queryOutTaskListApp")
    @Log("备货列表明细查询")
    @ApiOperation("备货列表明细查询")
    @AnonymousAccess
    public ResponseEntity<Object> queryTaskListApp(@RequestBody IPTask t){
        List<RPTaskList> ts= taskLogService.queryTaskLogApp(t);
        return new ResponseEntity<>(ts,HttpStatus.OK);
    }

    @PostMapping
    @Log("新增pickOut")
    @ApiOperation("新增pickOut")
    @PreAuthorize("@el.check('super:man')")
    public ResponseEntity<Object> createPickOut(@Validated @RequestBody PickOut resources){
        resources.setOrderNo(codeUtils.getCode_yyMMdd("CK",3));
        return new ResponseEntity<>(pickOutService.create(resources),HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改pickOut")
    @ApiOperation("修改pickOut")
    @PreAuthorize("@el.check('super:man')")
    public ResponseEntity<Object> updatePickOut(@Validated @RequestBody PickOut resources){
        pickOutService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

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

    @PostMapping("/getPickOutById")
    @Log("根据id获取数据")
    @ApiOperation("根据id获取数据")
    @PreAuthorize("@el.check('super:man')")
    public ResponseEntity<PickOutDto> getPickOutById(@RequestBody Long id) {
        return new ResponseEntity<>(pickOutService.findById(id),HttpStatus.OK);
    }


    @PostMapping("/operationAll")
    @Log("出库单维护操作")
    @ApiOperation("出库单维护操作")
    @PreAuthorize("@el.check('super:man')")
    public ResponseEntity<Object> operationAll(@RequestBody PickOutButton pickOutButton){
        int button = pickOutButton.getButton();
        if (button == 1){
            //新增
            if (pickOutButton.getPickOutId() != null){//向表中加数据
                pickOutService.addData(pickOutButton);
            }else {//添加表单数据
                return new ResponseEntity<>( pickOutService.createPickOut(pickOutButton),HttpStatus.OK);
            }
            return new ResponseEntity<>("新增成功",HttpStatus.OK);
        }else if (button == 2){
            //出库确认
            pickOutService.confirmPickOut(pickOutButton);
            return new ResponseEntity<>("确认成功",HttpStatus.OK);
        }
        return new ResponseEntity<>("成功",HttpStatus.OK);
    }

    @PostMapping("/pickOutApp")
    @Log("APP出库")
    @ApiOperation("APP出库")
    @AnonymousAccess
    @Transactional
    public ResponseEntity<Object> pickOutApp(@RequestBody IPPickOut po){
        int seq = po.getSeq();
        if (seq == 1){
            //新增
            PickOut out=null;
            String cph=po.getCph();
            if(cph==null||cph.equals("")){
                return new ResponseEntity<>("车牌号必填",HttpStatus.BAD_REQUEST);
            }
            List<PickOut> outs=pickOutService.findByOut(cph);
            if(outs.size()>0){
                out=outs.get(0);
            }else{
                out=new PickOut();
                out.setOrderNo(codeUtils.getCode_yyMMdd("CK", 3));
                out.setPlateNo(po.getCph());
                pickOutService.create(out);
            }
            HashMap<String,Object> map=new HashMap<>();
            map.put("outId",out.getId());
            map.put("code",out.getOrderNo());
            map.put("tps",0);
            map.put("xs",0);
            return new ResponseEntity<>(map,HttpStatus.OK);
        }else if (seq == 2){//把托盘追加至车牌号中
            String tph=po.getTph();
            PickOut out=pickOutService.findByEntity(po.getOutId());
            if(tph==null||tph.equals("")){
                return new ResponseEntity<>("托盘号必填",HttpStatus.BAD_REQUEST);
            }
            if(out==null){
                return new ResponseEntity<>("请选定出库单",HttpStatus.BAD_REQUEST);
            }
            List<TaskLog> logs=taskLogService.findByTph(tph,null);
            if(logs.size()<=0){
                return new ResponseEntity<>(tph+"托盘号无数据",HttpStatus.BAD_REQUEST);
            }else{
                for (TaskLog l:logs){
                    l.setPickOut(out);
                    taskLogService.update(l);
                    out.setOrderQty(out.getOrderQty()+l.getMoveQty());
                }
                pickOutService.update(out);
            }
            HashMap<String,Object> map=new HashMap<>();
            map.put("outId",out.getId());
            map.put("tps",0);
            map.put("xs",0);
            return new ResponseEntity<>(map,HttpStatus.OK);
        }else if(seq==3){
            PickOut out=pickOutService.findByEntity(po.getOutId());
            if(out==null){
                return new ResponseEntity<>("请选定出库单",HttpStatus.BAD_REQUEST);
            }
            List<TaskLog> logs=taskLogService.findByTph(null,out.getId());
            for(TaskLog l:logs){
                confirmPickOut(out,l,po.getFhr());
            }
        }
        return new ResponseEntity<>("成功",HttpStatus.OK);
    }

    @PostMapping("/pickOutXppApp")
    @Log("APP现品票出库")
    @ApiOperation("APP现品票出库")
    @AnonymousAccess
    @Transactional
    public ResponseEntity<Object> pickOutXppApp(@RequestBody IPPickOut po){
        int seq = po.getSeq();
        if (seq == 1){
            String code=po.getBhdh();
            if(code==null||code.equals("")){
                return new ResponseEntity<>("备货单号不能为空",HttpStatus.BAD_REQUEST);
            }
            List<PickTicket> pts=pickTicketRepository.queryCode(code);
            if(pts.size()<=0){
                return new ResponseEntity<>(code+"找不到备货单号",HttpStatus.BAD_REQUEST);
            }
            PickTicket pt=pts.get(0);
            Long user_id=SecurityUtils.getCurrentUserId();
            List<Job> jobs=jobRepository.jobAreaCodes(user_id);
            if(jobs.size()>0){
                String ckAreaCode= jobs.get(0).getAreaCode();
                if(!ckAreaCode.equals(pt.getArea().getCode())){
                    return new ResponseEntity<>(code+"没有该库区权限",HttpStatus.BAD_REQUEST);
                }
            }
            if(pt.getShippedQuantity()>=pt.getPickedQuantity()){
                return new ResponseEntity<>(code+"状态错误",HttpStatus.BAD_REQUEST);
            }
            //查询是否全部备货，如果没有则提示
            List list=pickDetailRepository.queryPickQty(pt.getId());
            if(list.size()>0){
                return new ResponseEntity<>(code+"未全部备货完成",HttpStatus.BAD_REQUEST);
            }
            HashMap<String,Object> map=new HashMap<>();
            map.put("ptId",pt.getId());
            return new ResponseEntity<>(map,HttpStatus.OK);
        }else if (seq == 2){//现品票批量出库
            String xpp=po.getXpp();
            PickTicketDto pickTicket=pickTicketService.findById(po.getPtId());
            String code=pickTicket.getCode();
            if(xpp==null||xpp.equals("")){
                return new ResponseEntity<>("现品票必填",HttpStatus.BAD_REQUEST);
            }
            List<TaskLog> logs=taskLogService.findByLog(xpp,code);
            if(logs.size()<=0){
                return new ResponseEntity<>("现品票不属于该备货单或已出库",HttpStatus.BAD_REQUEST);
            }
            XppRecord xppRecord = xppRecordRepository.findByCode(xpp);
            if(xppRecord==null){
                return new ResponseEntity<>("现品票不存在",HttpStatus.BAD_REQUEST);
            }
            TaskLog log=logs.get(0);
            if(log.getShipQty()>0){
                return new ResponseEntity<>("现品票已出库",HttpStatus.BAD_REQUEST);
            }
            RRkXpp map = new RRkXpp();
            Item it=xppRecord.getItem();
            map.setItemCode(it.getCode());
            map.setItemName(it.getName());
            map.setAc(xppRecord.getAc());
            map.setDdbh(xppRecord.getDdbh());
            map.setNrs(xppRecord.getNrs());
            if(xppRecord.getNrDate()!=null) {
                map.setNrzsr(DateUtil.dateYmd(xppRecord.getNrDate()));
            }else{
                map.setNrzsr("");
            }
            map.setFzh(xppRecord.getFzh());
            map.setCjsj(xppRecord.getCreateTime());
            map.setLogId(logs.get(0).getId());
            Task t=log.getTask();
            PickDetail pd =t.getPickDetail();
            if(pd.getShArea()!=null) {
                map.setGw(pd.getShArea().getWorkingStation());
            }
            return new ResponseEntity<>(map,HttpStatus.OK);
        }else if(seq==3){
            String cph=po.getCph();
            if(cph==null||cph.equals("")){
                return new ResponseEntity<>("车牌号必填",HttpStatus.BAD_REQUEST);
            }
            cph=cph.replace("\n","");
            PickOut  out=new PickOut();
            out.setOrderNo(codeUtils.getCode_yyMMdd("CK", 3));
            out.setPlateNo(cph);
            out.setStatus(BizStatus.OPEN);
            pickOutService.create(out);
            Long[] ids=po.getLogIds();
            for(int i=0;i<ids.length;i++){
                TaskLog log=taskLogService.findEntityId(ids[i]);
                if(log.getPickOut()!=null){
                    return new ResponseEntity<>("已出库",HttpStatus.BAD_REQUEST);
                }
                log.setPickOut(out);
                taskLogService.update(log);
                confirmPickOut(out,log,po.getFhr());
                out.setOrderQty(out.getOrderQty()+log.getMoveQty());
            }
            pickOutService.update(out);
        }
        return new ResponseEntity<>("成功",HttpStatus.OK);
    }

    //出库确认
    @PostMapping("/pickOutConfirm")
    @Log("系统备货出库确认")
    @ApiOperation("系统备货出库确认")
    @AnonymousAccess
    @Transactional
    public ResponseEntity<Object> pickOutConfirm(@RequestBody Long[] ptIds){
     for(Long id:ptIds){
//            PickOut  out=new PickOut();
//            out.setOrderNo(codeUtils.getCode_yyMMdd("CK", 3));
//            out.setPlateNo("系统出库单");
//            out.setStatus(BizStatus.OPEN);
//            pickOutService.create(out);
            List<TaskLog> logs=taskLogRepository.getTaskLogsByPtId(id);
            for(TaskLog log:logs){
                if(log.getShipQty()>0){
                    return new ResponseEntity<>("已出库",HttpStatus.BAD_REQUEST);
                }
//                log.setPickOut(out);
                taskLogService.update(log);
                confirmPickOut(null,log,SecurityUtils.getCurrentUsername());
//                confirmPickOut(out,log,SecurityUtils.getCurrentUsername());
//                out.setOrderQty(out.getOrderQty()+log.getMoveQty());
            }
//            pickOutService.update(out);
        }
        return new ResponseEntity<>("成功",HttpStatus.OK);
    }
    public void confirmPickOut(PickOut out,TaskLog log,String fhr) {
        Task task=log.getTask();
        PickDetail pd=task.getPickDetail();
        if(pd.getPickedQty().intValue()<pd.getAllocatedQty().intValue()){
            throw new BadRequestException(HttpStatus.NOT_FOUND, pd.getItem().getCode() + "该品番未全部备货完成，不能出库");
        }
        PickTicket pt=pd.getPickTicket();
        String billCode=pt.getCode();
        if(out!=null){
            billCode=out.getOrderNo();
            if(out.getArea()==null){
                out.setArea(pt.getArea());
                out.setGcCode(pt.getGcCode());
            }else{
                //如果放置不同工厂需要提示，放置不同出库库区需要提示
            }
        }
        if(pt.getPickedQuantity().intValue()<pt.getAllocatedQuantity().intValue()){
            throw new BadRequestException(HttpStatus.NOT_FOUND, pt.getCode() + "该单未全部备货完成，不能出库");
        }
        XppRecord xpp=xppRecordRepository.findByCode(log.getSrcStockCode());
//        if (out.getStatus().equals(BizStatus.SHIP_ALL)) {
//            throw new BadRequestException(HttpStatus.NOT_FOUND, out.getOrderNo() + "该单已全部发运");
//        }
        if (log.getMoveQty() - log.getShipQty() == 0d) {
            return;
        }
        //扣库存
        Inventory inventory = inventoryService.getInventory(log.getItemKey(),pt.getArea(),log.getDstPoint(),pd.getPoint(),log.getDept(),BizStatus.SHIPPING,null);
        if (inventory==null) {
            throw new BadRequestException(HttpStatus.NOT_FOUND, log.getItem().getCode() + "未发现库存数据");
        }
        if (inventory.getQuantity() < log.getMoveQty()) {
            throw new BadRequestException(HttpStatus.NOT_FOUND, log.getItem().getCode() + "发货区库存不足单子出现问题");
        }
        inventoryLogService.storeInventoryLog(BizStatus.SHIPPING, BizStatus.REDUCE, billCode, inventory.getArea(), inventory.getItemKey(), inventory.getPoint(), inventory.getPoint(), pd.getPoint(), inventory.getQuantity(), log.getMoveQty(),
                log.getSrcStockCode(), BizStatus.SHIPPING, inventory.getId(), inventory.getId(), inventory.getDescription());
        inventory.setQuantity(inventory.getQuantity() - log.getMoveQty());
        inventoryService.update(inventory);

        //tasklog的出库数量回写
        log.setShipQty(log.getMoveQty());
        log.setShipTime(new Timestamp(new Date().getTime()));
        log.setShipBy(fhr);
        double shipQty =log.getMoveQty();
        pd.setShippedQty(pd.getShippedQty()+shipQty);
        pt.setShipDate(new Timestamp(new Date().getTime()));

        if(xpp!=null){
            xpp.setStatus(BizStatus.SHIP_ALL);
            xpp.setFhr(SecurityUtils.getCurrentUsername());
            xpp.setFhDate(new Timestamp(new Date().getTime()));
            xppRecordService.update(xpp);
        }
        if(out!=null) {
            if (Objects.isNull(pt.getRelatedBill2())) {
                pt.setRelatedBill2(out.getOrderNo());
            } else if (pt.getRelatedBill2().indexOf(out.getOrderNo()) < 0) {
                pt.setRelatedBill2(pt.getRelatedBill2() + "," + out.getOrderNo());
            }
        }
        pt.setShippedQuantity(pt.getShippedQuantity()+shipQty);
        if ((pt.getPickedQuantity().intValue() <= pt.getShippedQuantity().intValue())) {
            pt.setStatus(BizStatus.SHIP_ALL);
        } else {
            pt.setStatus(BizStatus.SHIP_PART);
        }
        pickTicketService.update(pt);
        taskLogService.update(log);
        pickDetailService.update(pd);
        if(out!=null) {
            out.setDispatchQty(out.getDispatchQty() + shipQty);
            if (out.getDispatchQty().intValue() >= out.getOrderQty().intValue()) {
                out.setStatus(BizStatus.SHIP_ALL);
            } else {
                out.setStatus(BizStatus.SHIP_PART);
            }
            out.setBhNo(pt.getCode());
            out.setShArea(pt.getShArea());
            pickOutService.update(out);
        }
    }

    @PostMapping("/pickOutBack")
    @Log("系统出库退回")
    @ApiOperation("系统出库退回")
    @AnonymousAccess
    @Transactional
    public ResponseEntity<Object> pickOutBack(@RequestBody Long[] ptIds){
        for(Long id:ptIds){
            List<TaskLog> logs=taskLogRepository.getCancelByShip(id);
            if(logs.size()<=0){
                return new ResponseEntity<>("没有出库数据",HttpStatus.BAD_REQUEST);
            }
            PickTicket pt=pickTicketRepository.getById(id);
            for(TaskLog log:logs){
                pickTicketService.backPickOut(log.getId(),pt.getArea());
            }
        }
        return new ResponseEntity<>("成功",HttpStatus.OK);
    }
    @PostMapping("/queryTaskLog")
    @Log("查询TaskLog")
    @ApiOperation("查询TaskLog")
//    @PreAuthorize("@el.check('pickOut:queryTaskLog')")
    @AnonymousAccess
    public ResponseEntity<List<TaskLog>> queryTaskLog(@RequestBody PickOutButton pickOutButton) {
        return new ResponseEntity<>(pickOutService.getTaskLogNotPickOut(pickOutButton),HttpStatus.CREATED);
    }

    @PostMapping("/xbjsOut")
    @Log("线边接收确认")
    @ApiOperation("线边接收确认")
    @PreAuthorize("@el.check('super:man')")
    @Transactional
    @DuplicateSubmission(10)
    public ResponseEntity<Object> xbjsOut(@RequestBody Long[] ids) {
        String userName=SecurityUtils.getCurrentUsername();
        Dept dept= UserUtils.getDept();
        for (Long id : ids) {
            PickOut pickOut=pickOutService.findByEntity(id);
            if(pickOut.getSlQty()>0){
                //continue;
                throw new BadRequestException(pickOut.getOrderNo()+"状态不正确");
            }
            List<TaskLog> logs=taskLogRepository.getTaskLogByPickOutId(id);
            int tlNum=0;
            double shNum = 0d;
            for (TaskLog tasklog : logs) {
                if (tasklog.getSlQty() > 0) {
                    shNum += tasklog.getSlQty();
                    continue;
                }
                tasklog.setSlQty(tasklog.getShipQty() - tasklog.getTkjsQty());
                tasklog.setSlBy(userName);
                tlNum+=tasklog.getTkjsQty().intValue();
                taskLogService.update(tasklog);
                if (tasklog.getSlQty() > 0) {
                    shNum += tasklog.getSlQty();
                    //生成具体的库存信息
                    Task task = tasklog.getTask();
                    PickDetail pickDetail = task.getPickDetail();
//                Point point=pickOut.getShArea().getPoint();
                    Point point = pointService.findEntityById(pickDetail.getShArea().getPointId());
                    //线边接收不需要管理到批次，重新生成itemKey
                    ItemKey itemKey = itemKeyService.getItemKey(tasklog.getItemKey().getItem(), null,task.getItemKey().getPropC2());
                    Inventory inventory = inventoryService.getInventory(itemKey, pickDetail.getShArea(), point, pickDetail.getPoint(), dept, BizStatus.SL_ALL,null);
                    double srcQty = inventory.getQuantity();
                    inventory.setQuantity(inventory.getQuantity() + tasklog.getSlQty());
                    inventoryService.update(inventory);
                    InventoryLog inventoryLog = inventoryLogService.storeInventoryLog(BizStatus.SL_ALL, BizStatus.ADD, pickOut.getOrderNo(), pickDetail.getShArea(), itemKey, inventory.getPoint(), inventory.getPoint(), null, null, srcQty, tasklog.getSlQty(), null, tasklog.getSrcStockCode(),
                            BizStatus.SL_ALL, tasklog.getId(), inventory.getId(), "线边接收");
                    inventoryLog.setZzkw(pickDetail.getPoint());
                    inventoryLogService.update(inventoryLog);
                    XppRecord xpp = xppRecordRepository.findByCode(tasklog.getSrcStockCode());
                    if (xpp != null) {
                        xpp.setStatus(BizStatus.SL_ALL);
                        xpp.setJsr(userName);
                        xpp.setJsDate(new Timestamp(new Date().getTime()));
                        xpp.setJskw(tasklog.getDstPoint());
                        xppRecordService.update(xpp);
                    }
                }
            }
            pickOut.setSlQty(shNum);
            pickOut.setSlBy(userName);
            pickOut.setSlDate(new Timestamp(new Date().getTime()));
            if(pickOut.getSlQty().intValue()+tlNum>=pickOut.getDispatchQty().intValue()) {
                pickOut.setStatus(BizStatus.SL_ALL);
            }
            pickOutService.update(pickOut);
        }
        return new ResponseEntity<>("操作成功",HttpStatus.OK);
    }
    @PostMapping("/xbjsQueryApp")
    @Log("线边接收App")
    @ApiOperation("线边接收App")
    @PreAuthorize("@el.check('super:man')")
    @Transactional
    public ResponseEntity<Object> xbjsQueryApp(@RequestBody HashMap<String, Object> js) {
        String outCode=js.get("outCode").toString();
        List<PickOut> outs=pickOutRepository.queryCode(outCode);
        if(outs.size()<=0){
            return new ResponseEntity<>("未找到对应单号",HttpStatus.BAD_REQUEST);
        }
        PickOut o=outs.get(0);
        HashMap<String,Object> map=new HashMap<>();
        map.put("id",o.getId());
        String status=o.getStatus();
//        DictQueryCriteria dictStatus=new DictQueryCriteria();
//        dictStatus.setBlurry("pick_status");
//        Map<String, DictDetail> status_dic = dictDetailService.getDictDetailByName("pick_status");
//        status=status_dic.get(o.getStatus()).getValue();
        if(o.getStatus().equals(BizStatus.SHIP_ALL)){
            status="发运完成";
        } else if (o.getStatus().equals(BizStatus.SL_ALL)) {
            status="接收完成";
        }
        map.put("status",status);
        map.put("code",outCode);
        map.put("outName",o.getArea().getName());
        map.put("gc_code",o.getGcCode());
        List<TaskLog> logs=taskLogRepository.getTaskLogByPickOutId(o.getId());
        List list=new ArrayList<>();
        for(TaskLog log:logs){
            HashMap<String,Object> detail=new HashMap<>();
            Task t=log.getTask();
            PickDetail pd=t.getPickDetail();
            String gw="";
            if(pd.getShArea()!=null){
                gw=pd.getShArea().getWorkingStation();
            }
            detail.put("gw",gw);
            detail.put("itemCode",log.getItemKey().getItem().getCode());
            detail.put("itemName",log.getItemKey().getItem().getName());
            detail.put("qty",log.getMoveQty().intValue());
            detail.put("ddbh","");
            detail.put("fzh","");
            if(log.getSrcStockCode()!=null) {
                XppRecord xpp = xppRecordRepository.findByCode(log.getSrcStockCode());
                if(xpp!=null){
                    detail.put("ddbh",xpp.getDdbh());
                    detail.put("fzh",xpp.getFzh());
                }
            }
            list.add(detail);
        }
        map.put("details",list);
        map.put("itemCount",list.size()+"/"+o.getOrderQty().intValue());
        log.info(map.toString());
        return new ResponseEntity<>(map,HttpStatus.OK);
}

    @PostMapping("/xbjsQueryDetialApp")
    @Log("线边接收明细App")
    @ApiOperation("线边接收明细App")
    @PreAuthorize("@el.check('super:man')")
    public ResponseEntity<Object> xbjsQueryDetialApp(@RequestBody Long id) {
        PickOut o=pickOutRepository.getById(id);
        HashMap<String,Object> map=new HashMap<>();
        List<TaskLog> logs=taskLogRepository.getTaskLogByPickOutId(o.getId());
        List list=new ArrayList<>();
        for(TaskLog log:logs){
            HashMap<String,Object> detail=new HashMap<>();
            detail.put("itemCode",log.getItemKey().getItem().getCode());
            detail.put("itemName",log.getItemKey().getItem().getName());
            detail.put("qty",log.getMoveQty().intValue()+"/"+log.getSlQty().intValue());
            detail.put("ddbh","");
            detail.put("fzh","");
            if(log.getSrcStockCode()!=null) {
                XppRecord xpp = xppRecordRepository.findByCode(log.getSrcStockCode());
                if(xpp!=null){
                    detail.put("ddbh",xpp.getDdbh());
                    detail.put("fzh",xpp.getFzh());
                }
            }
            list.add(detail);
        }
        map.put("details",list);
        log.info(map.toString());
        return new ResponseEntity<>(map,HttpStatus.OK);
    }

}