/*
*  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.Point;
import com.youchain.businessdata.domain.*;
import com.youchain.businessdata.repository.CountMoveDetailRepository;
import com.youchain.businessdata.repository.CountMoveRepository;
import com.youchain.businessdata.repository.InventoryRepository;
import com.youchain.businessdata.repository.XppRecordRepository;
import com.youchain.businessdata.service.CountMoveService;
import com.youchain.businessdata.service.InventoryLogService;
import com.youchain.businessdata.service.InventoryService;
import com.youchain.businessdata.service.XppRecordService;
import com.youchain.businessdata.service.dto.CountDetailDto;
import com.youchain.businessdata.service.dto.CountMoveDto;
import com.youchain.businessdata.service.dto.CountMoveQueryCriteria;
import com.youchain.exception.BadRequestException;
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 java.io.IOException;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://eladmin.vip
* @author houjianlan
* @date 2024-11-19
**/
@RestController
@RequiredArgsConstructor
@Slf4j
@Api(tags = "count_move管理")
@RequestMapping("/api/countMove")
public class CountMoveController {

    private final CountMoveService countMoveService;
    private final CodeUtils codeUtils;
    private final CountMoveRepository countMoveRepository;
    private final CountMoveDetailRepository countMoveDetailRepository;
    private final EntityManager entityManager;
    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('countMove:list')")
    public void exportCountMove(HttpServletResponse response, CountMoveQueryCriteria criteria) throws Exception {
        countMoveService.download(countMoveService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询count_move")
    @ApiOperation("查询count_move")
    @PreAuthorize("@el.check('countMove:list')")
    public ResponseEntity<Object> queryCountMove(CountMoveQueryCriteria criteria, Pageable pageable) {
        return new ResponseEntity<>(countMoveService.queryAll(criteria, pageable), HttpStatus.OK);
    }

    @PostMapping
    @Log("新增count_move")
    @ApiOperation("新增count_move")
    @PreAuthorize("@el.check('countMove:add')")
    public ResponseEntity<Object> createCountMove(@Validated @RequestBody CountMove resources) {
        if(resources.getDstArea()==null){
            throw new BadRequestException("需填写目标库区");
        }
        if(resources.getSrcArea()==null){
            throw new BadRequestException("需填写原库区");
        }
        if(resources.getType()==null){
            throw new BadRequestException("需填写盘点类型");
        }
        resources.setCode(codeUtils.getCode_yyMMdd("PM", 3));
        return new ResponseEntity<>(countMoveService.create(resources), HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改count_move")
    @ApiOperation("修改count_move")
    @PreAuthorize("@el.check('countMove:edit')")
    public ResponseEntity<Object> updateCountMove(@Validated @RequestBody CountMove resources) {
        countMoveService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @Log("删除count_move")
    @ApiOperation("删除count_move")
    @PreAuthorize("@el.check('countMove:del')")
    public ResponseEntity<Object> deleteCountMove(@RequestBody Long[] ids) {
        for (Long id:ids){
            CountMoveDto countMove=countMoveService.findById(id);
            if(!countMove.getStatus().equals(BizStatus.OPEN)&&!countMove.getStatus().equals(BizStatus.COUNT)){
                throw new BadRequestException(countMove.getCode()+"状态不正确");
            }
        }
        countMoveService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

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

    @PostMapping("/countCheck")
    @Log("移位数据审核")
    @ApiOperation("移位数据审核")
    @PreAuthorize("@el.check('super:man')")
    @Transactional
    @DuplicateSubmission(1*60)
    public ResponseEntity<Object> countCheck(@RequestBody Long[] ids) {
        for (Long id : ids) {
            CountMove countMove=countMoveRepository.getById(id);
            if(!countMove.getStatus().equals(BizStatus.OPEN)){
                throw new BadRequestException(countMove.getCode()+"状态不正确");
            }
            if(countMove.getType().equals(BizStatus.COUNT_ALL)) {
                List<CountMoveDetail> countMoveDetailList=countMoveDetailRepository.queryDetails(id);
                if(countMoveDetailList.size()==0) {
                    countMoveService.countCheck(countMove);
                }
            }
            String sql="INSERT into data_inventory_count_bak(count_id,bill_code,item_key_id,stock_code,point_id,quantity,queued_qty,be_lock,be_reject,`status`,dept_id,area_id,zzkw,bf_date)   \n" +
                    "select "+countMove.getId()+",'"+countMove.getCode()+"',item_key_id,stock_code,point_id,quantity,queued_qty,be_lock,be_reject,status,dept_id,area_id,zzkw,SYSDATE() from data_inventory inv where inv.quantity!=0";
            Query query=entityManager.createNativeQuery(sql);
            query.executeUpdate();
            countMove.setStatus(BizStatus.COUNT);
            countMoveService.update(countMove);
        }
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @PostMapping("/countFinish")
    @Log("移位完成")
    @ApiOperation("移位完成")
    @PreAuthorize("@el.check('super:man')")
    @Transactional
    @DuplicateSubmission(1*60)
    public ResponseEntity<Object> countFinish(@RequestBody Long[] ids) {
        for (Long id : ids) {
            CountMove countMove=countMoveRepository.getById(id);
            if(!countMove.getStatus().equals(BizStatus.COUNT)&&!countMove.getStatus().equals(BizStatus.OPEN)){
                throw new BadRequestException(countMove.getCode()+"状态不正确");
            }
            countMoveService.countXpp(countMove);
            countMove.setStatus(BizStatus.CLOSE);
        }
        return new ResponseEntity<>(HttpStatus.OK);
    }

}