/*
 *  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 cn.hutool.json.JSONArray;
import com.youchain.DuplicateSubmission.DuplicateSubmission;
import com.youchain.annotation.AnonymousAccess;
import com.youchain.annotation.Log;
import com.youchain.basicdata.domain.Point;
import com.youchain.basicdata.repository.PointRepository;
import com.youchain.basicdata.service.dto.BillTypeQueryCriteria;
import com.youchain.businessdata.domain.Asn;
import com.youchain.businessdata.domain.AsnDetail;
import com.youchain.businessdata.inputJson.PutawayRequest;
import com.youchain.businessdata.repository.AsnDetailRepository;
import com.youchain.businessdata.repository.AsnRepository;
import com.youchain.businessdata.returnJson.PutawayRet;
import com.youchain.businessdata.service.AsnDetailService;
import com.youchain.businessdata.service.AsnService;
import com.youchain.businessdata.service.dto.AsnDetailDto;
import com.youchain.businessdata.service.dto.AsnQueryCriteria;
import com.youchain.exception.BadRequestException;
import com.youchain.exception.handler.ApiResult;
import com.youchain.utils.BaseStatus;
import com.youchain.utils.BizStatus;
import com.youchain.utils.CodeUtils;
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.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

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

/**
 * @author JiangKun
 * @website https://eladmin.vip
 * @date 2024-01-09
 **/
@Slf4j
@RestController
@RequiredArgsConstructor
@Api(tags = "asn管理")
@RequestMapping("/api/asn")
public class AsnController {

    private final AsnService asnService;
    private final AsnDetailService asnDetailService;
    private final AsnRepository asnRepository;
    private final AsnDetailRepository asnDetailRepository;
    private final PointRepository pointRepository;
    private final CodeUtils codeUtils;


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


    @GetMapping
    @Log("查询asn")
    @ApiOperation("查询asn")
    @AnonymousAccess
    public ResponseEntity<Object> queryAsn(AsnQueryCriteria criteria, Pageable pageable) {
        return new ResponseEntity<>(asnService.queryAll(criteria, pageable), HttpStatus.OK);
    }


    @GetMapping("/getIdByAsn")
    @Log("查询asn")
    @ApiOperation("查询asn")
    @AnonymousAccess
    public ResponseEntity<Object> getIdByAsn(@RequestParam("id") Long id) {
        return new ResponseEntity<>(asnService.findById(id), HttpStatus.OK);
    }

    @GetMapping("/queryAsnAll")
    @Log("查询asn")
    @ApiOperation("查询asn")
    @AnonymousAccess
    public ResponseEntity<Object> queryAsnAll(AsnQueryCriteria criteria) {
        return new ResponseEntity<>(asnService.queryAll(criteria), HttpStatus.OK);
    }

    @PostMapping
    @Log("新增asn")
    @ApiOperation("新增asn")
    @PreAuthorize("@el.check('super:man')")
    public ResponseEntity<Object> createAsn(@Validated @RequestBody Asn resources) {
        return new ResponseEntity<>(asnService.create(resources), HttpStatus.CREATED);
    }

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

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

    @PostMapping("/checkPutawayApp")
    @Log("箱单入库-APP")
    @ApiOperation("箱单入库-APP")
    @PreAuthorize("@el.check('super:man')")
    @Transactional(rollbackFor = Exception.class)
    @DuplicateSubmission
    public ResponseEntity<Object> checkPutawayApp(@RequestBody PutawayRequest request) {
        String stockCode = request.getStockCode();
        if(stockCode.indexOf("84")==0){
            stockCode=stockCode.substring(2);
        }
        int checkType=request.getCheckType();
        String pointCode= request.getPointCode();
        if(checkType==1) {
            List<Asn> asns = asnRepository.queryByCusCode(stockCode);
            if (asns.size() <= 0) {
                throw new BadRequestException(stockCode + "不存在");
            }else{
                Long asnId=asns.get(0).getId();
                List<AsnDetail> ads=asnDetailRepository.queryByAsnId(asnId);
                List<PutawayRet> rets=new ArrayList<>();
                for(AsnDetail ad:ads){
                    PutawayRet ret=new PutawayRet();
                    ret.createPutawayRet(asnId,ad.getId(),ad.getItem().getCode(),ad.getItem().getName(),ad.getOrderQty(),ad.getPropC2(),ad.getPo());
//                    ret.setBonded(ad.getPropC2());
//                    ret.setPo(ad.getPo());
//                    ret.setQty(ad.getOrderQty());
//                    ret.setItemCode(ad.getItem().getCode());
//                    ret.setItemName(ad.getItem().getName());
                    rets.add(ret);
                }
                return new ResponseEntity<>(rets, HttpStatus.OK);
            }
        } else if (checkType==2) {
            Point point=pointRepository.findByCodeType(pointCode, BaseStatus.CH);
            if(point==null){
                throw new BadRequestException(pointCode + "不存在");
            }
        }
        return new ResponseEntity<>("操作成功", HttpStatus.OK);
    }

    @PostMapping("/putawayApp")
    @Log("上架确认-APP")
    @ApiOperation("上架确认-APP")
    @PreAuthorize("@el.check('super:man')")
    @Transactional(rollbackFor = Exception.class)
    @DuplicateSubmission
    public ResponseEntity<Object> putawayApp(@RequestBody PutawayRequest request) {
        String stockCode = request.getStockCode();
        if(stockCode.indexOf("84")==0){
            stockCode=stockCode.substring(2);
        }
        int checkType=request.getCheckType();
        String pointCode= request.getPointCode();
        Point point=pointRepository.findByCodeType(pointCode, BaseStatus.CH);
        if(point==null){
            throw new BadRequestException(pointCode + "不存在");
        }
        List<Asn> asns = asnRepository.queryByCusCode(stockCode);
        if (asns.size() <= 0) {
            throw new BadRequestException(stockCode + "不存在");
        }
        Long asnId=asns.get(0).getId();
        List<Long> detailIds=asnDetailRepository.queryIdsByAsn(asnId);
        for(Long detailId:detailIds) {
            AsnDetail d=asnDetailRepository.getById(detailId);
            asnDetailService.putawayInv(detailId,null,point.getId(),d.getOrderQty()-d.getReceivedQty(),null);
        }
        return new ResponseEntity<>("操作成功", HttpStatus.OK);
    }

    @PostMapping("/mutilPutawaySys")
    @Log("上架确认-系统")
    @ApiOperation("上架确认-系统")
    @PreAuthorize("@el.check('super:man')")
    @Transactional(rollbackFor = Exception.class)
    @DuplicateSubmission
    public ResponseEntity<Object> mutilPutawaySys(@RequestBody PutawayRequest request) {
        Long[] ids = request.getIds().toArray(new Long[0]);
        Long pointId = request.getPointId();
        for (Long id:ids){
            List<Long> detailIds=asnDetailRepository.queryIdsByAsn(id);
            for(Long detailId:detailIds) {
                AsnDetail d=asnDetailRepository.getById(detailId);
                asnDetailService.putawayInv(detailId,null,pointId,d.getOrderQty()-d.getReceivedQty(),null);
            }
        }
        return new ResponseEntity<>("操作成功", HttpStatus.OK);
    }
}