/*
*  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.AnonymousAccess;
import com.youchain.annotation.Log;
import com.youchain.basicdata.domain.BomAccount;
import com.youchain.basicdata.domain.Point;
import com.youchain.basicdata.domain.ProductionPlan;
import com.youchain.basicdata.repository.ProductionPlanRepository;
import com.youchain.basicdata.service.BomAccountService;
import com.youchain.basicdata.service.PointService;
import com.youchain.basicdata.service.ProductionPlanService;
import com.youchain.businessdata.domain.Inventory;
import com.youchain.businessdata.domain.InventoryLog;
import com.youchain.businessdata.domain.ItemKey;
import com.youchain.businessdata.domain.Spareparts;
import com.youchain.businessdata.service.InventoryLogService;
import com.youchain.businessdata.service.InventoryService;
import com.youchain.businessdata.service.ItemKeyService;
import com.youchain.businessdata.service.SparepartsService;
import com.youchain.businessdata.service.dto.SparepartsDto;
import com.youchain.businessdata.service.dto.SparepartsQueryCriteria;
import com.youchain.exception.BadRequestException;
import com.youchain.exception.handler.ApiResult;
import com.youchain.modules.system.domain.DictDetail;
import com.youchain.modules.system.service.DictDetailService;
import com.youchain.modules.system.service.dto.DictQueryCriteria;
import com.youchain.utils.BizStatus;
import com.youchain.utils.SecurityUtils;
import com.youchain.utils.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.security.SecurityUtil;
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.io.IOException;
import java.sql.Timestamp;
import java.util.*;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;

/**
* @website https://eladmin.vip
* @author ShenYinAn
* @date 2024-01-30
**/
@RestController
@RequiredArgsConstructor
@Slf4j
@Api(tags = "spareparts管理")
@RequestMapping("/api/spareparts")
public class SparepartsController {

    private final SparepartsService sparepartsService;
    private final ProductionPlanRepository productionPlanRepository;
    private final ProductionPlanService productionPlanService;

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

    @GetMapping
    @Log("查询spareparts")
    @ApiOperation("查询spareparts")
    @AnonymousAccess
    public ResponseEntity<Object> querySpareparts(SparepartsQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(sparepartsService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增spareparts")
    @ApiOperation("新增spareparts")
    @PreAuthorize("@el.check('super:man')")
    public ResponseEntity<Object> createSpareparts(@Validated @RequestBody Spareparts resources){
        resources.setStatus("UN_CONSUME");
        return new ResponseEntity<>(sparepartsService.create(resources),HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改spareparts")
    @ApiOperation("修改spareparts")
    @PreAuthorize("@el.check('super:man')")
    public ResponseEntity<Object> updateSpareparts(@Validated @RequestBody Spareparts resources){
        if(resources.getStatus().equals("CONSUME")){
            return new ResponseEntity(ApiResult.success("已耗用，无法修改",""), HttpStatus.BAD_REQUEST);
        }
        sparepartsService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @Log("删除spareparts")
    @ApiOperation("删除spareparts")
    @Transactional
    @PreAuthorize("@el.check('super:man')")
    public ResponseEntity<Object> deleteSpareparts(@RequestBody Long[] ids) {
        for(Long id : ids){
            SparepartsDto sparepartsDto = sparepartsService.findById(id);
            if(sparepartsDto.getStatus().equals("CONSUME")){
                return  new ResponseEntity(ApiResult.success("已耗用，无法删除",""), HttpStatus.BAD_REQUEST);
            }
        }
        sparepartsService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @PostMapping("/hySpareParts")
    @Log("零件耗用")
    @ApiOperation("零件耗用")
    @Transactional
    @PreAuthorize("@el.check('super:man')")
    public ResponseEntity<Object> hySpareParts(@RequestBody HashMap map) {
        if(map.size()>0){
            List list= (List) map.get("ids");
            for(int i=0;i<list.size();i++){
               Long id=Long.parseLong(list.get(i).toString());
               sparepartsService.hySpareParts(id);
            }
        }
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @PostMapping("/autoAddHy")
    @Log("零件耗用")
    @ApiOperation("零件耗用")
    @Transactional
    @PreAuthorize("@el.check('super:man')")
    public ResponseEntity<Object> autoAddHy(@RequestBody String idno) {
        List<String> whyGwList = productionPlanRepository.getIdNoWhyGw(idno);
        if(whyGwList.size()<=0){
            throw  new BadRequestException("未找到需要耗用数据");
        }
        for (String gw:whyGwList){
            List<ProductionPlan> whyList = productionPlanRepository.getIdNoAllData(gw,idno);
            productionPlanService.scsxHaoyong(whyList,gw,"截止IDNO自动耗用");
        }
        //自动创建
        return new ResponseEntity<>("操作成功",HttpStatus.OK);
    }
}