/*
*  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.annotation.Log;
import com.youchain.basicdata.domain.Point;
import com.youchain.businessdata.domain.*;
import com.youchain.businessdata.service.CountDetailService;
import com.youchain.businessdata.service.CountPlanService;
import com.youchain.businessdata.service.CountRecordService;
import com.youchain.businessdata.service.InventoryService;
import com.youchain.businessdata.service.dto.CountDetailQueryCriteria;
import com.youchain.exception.handler.ApiError;
import com.youchain.exception.handler.ApiResult;
import com.youchain.utils.BaseStatus;
import com.youchain.utils.BizStatus;
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.servlet.http.HttpServletResponse;

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

/**
* @website https://eladmin.vip
* @author houjianlan
* @date 2023-10-20
**/
@RestController
@Slf4j
@RequiredArgsConstructor
@Api(tags = "count_detail管理")
@RequestMapping("/api/countDetail")
public class CountDetailController {

    private final CountDetailService countDetailService;

    private final CountPlanService countPlanService;

    private final CountRecordService countRecordService;

    private final InventoryService inventoryService;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('countDetail:list')")
    public void exportCountDetail(HttpServletResponse response, CountDetailQueryCriteria criteria) throws IOException {
        countDetailService.download(countDetailService.queryAll(criteria), response);
    }

    @GetMapping
    @ApiOperation("查询count_detail")
    public ResponseEntity<Object> queryCountDetail(CountDetailQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(countDetailService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @GetMapping(value = "/queryPlanCountDetail")
    @ApiOperation("查询count_detail")
    public ResponseEntity<Object> queryPlanCountDetail(CountDetailQueryCriteria criteria){
       // log.info(criteria.getPlanId()+"------盘点ID");
        return new ResponseEntity<>(countDetailService.queryAll(criteria),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增count_detail")
    @ApiOperation("新增count_detail")
    @PreAuthorize("@el.check('countDetail:add')")
    public ResponseEntity<Object> createCountDetail(@Validated @RequestBody CountDetail resources){
        return new ResponseEntity<>(countDetailService.create(resources),HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改count_detail")
    @ApiOperation("修改count_detail")
    @PreAuthorize("@el.check('countDetail:edit')")
    public ResponseEntity<Object> updateCountDetail(@Validated @RequestBody CountDetail resources){
        countDetailService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @Log("删除count_detail")
    @ApiOperation("删除count_detail")
    @PreAuthorize("@el.check('countDetail:del')")
    public ResponseEntity<Object> deleteCountDetail(@RequestBody Long[] ids) {
        countDetailService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @Log("盘点审核")
    @ApiOperation("盘点审核")
    @PutMapping(value = "/checkCountPlan")
    @PreAuthorize("@el.check('countDetail:checkCountPlan')")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<Object> checkCountPlan(@RequestBody Long[] ids) {
        for(Long id:ids) {
            CountPlan p =countPlanService.toEntity(countPlanService.findById(id));
            List<CountDetail> details=countPlanService.findAllDetail(id);
            if(details.size()>0){
                if(p.getType().equals(BizStatus.ZONE)){
                    for(CountDetail d:details){
                        List<Inventory> invs=inventoryService.getInvForPlan(p.getType(),d.getArea().getId(), null,null);
                        for(Inventory inv:invs){
                            inv.setQueuedQty(inv.getQuantity());
                            inventoryService.update(inv);
                            countRecordService.createCountRecord(d,inv);
                            d.setPlanQty(d.getPlanQty()+inv.getQuantity());
                            countDetailService.update(d);
                        }
                    }
                }
                p.setStatus(BizStatus.ACTIVE);
                countPlanService.update(p);
            }else{
                ApiError apiError = ApiError.errorJosn(BAD_REQUEST.value(),"先维护盘点明细");
                return new ResponseEntity(apiError, HttpStatus.valueOf(apiError.getStatus()));
            }
        }
        return new ResponseEntity<>(HttpStatus.OK);
    }
}
