/*
*  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.basicdata.rest;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.youchain.annotation.AnonymousAccess;
import com.youchain.annotation.Log;
import com.youchain.basicdata.domain.Area;
import com.youchain.basicdata.domain.Point;
import com.youchain.basicdata.domain.Stock;
import com.youchain.basicdata.domain.StockType;
import com.youchain.basicdata.repository.PointRepository;
import com.youchain.basicdata.service.StockService;
import com.youchain.basicdata.service.StockTypeService;
import com.youchain.basicdata.service.dto.StockQueryCriteria;
import com.youchain.config.FileProperties;
import com.youchain.exception.handler.ApiError;
import com.youchain.utils.BaseStatus;
import com.youchain.utils.FileUtil;
import com.youchain.utils.ImportEntityUtils;
import com.youchain.utils.UserUtils;
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.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import static org.springframework.http.HttpStatus.BAD_REQUEST;

/**
* @website https://eladmin.vip
* @author liuxue
* @date 2023-07-28
**/
@RestController
@RequiredArgsConstructor
@Slf4j
@Api(tags = "stock管理")
@RequestMapping("/api/stock")
public class StockController {

    private final StockService stockService;
    private final PointRepository pointRepository;

    private final FileProperties properties;

    private final StockTypeService stockTypeService;
    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('stock:list')")
    public void exportStock(HttpServletResponse response, StockQueryCriteria criteria) throws IOException {
        stockService.download(stockService.queryAll(criteria), response);
    }

    @PostMapping(value = "/import_stock")
    @ApiOperation("容器导入")
    @AnonymousAccess
    public ResponseEntity<Object> importStock( @RequestParam("file") MultipartFile multipartFile) {
        FileUtil.checkSize(properties.getMaxSize(), multipartFile.getSize());
        String suffix = FileUtil.getExtensionName(multipartFile.getOriginalFilename());
        String type = FileUtil.getFileType(suffix);
        File file = FileUtil.upload(multipartFile, properties.getPath().getPath() + type + File.separator);
        //代码、库区
        ExcelReader reader = ExcelUtil.getReader(file);
        int i=0;
        int edit_len=0;
        int new_len=0;
        try{
            List<Map<String, Object>> readAll = reader.readAll();
            for ( i = 0; i < readAll.size(); i++) {
                int j=0;
                String code=readAll.get(i).get("代码").toString().trim();
                String stockTypeCode=readAll.get(i).get("类型").toString().trim();
//                String pointCode=readAll.get(i).get("点位").toString().trim();
                StockType st=stockTypeService.findByCode(stockTypeCode);
                if(code==null || code.length()<=0){
                    break;
                }
                if(st==null){
                    ApiError apiError = ApiError.errorJosn(BAD_REQUEST.value(),"找不到容器类型"+stockTypeCode);
                    return new ResponseEntity(apiError, HttpStatus.valueOf(apiError.getStatus()));
                }
                Stock stock=stockService.findByCode(code,null);
                if(stock==null){
                    stock=new Stock();
                    stock.setCode(code);
                    stock.setName(code);
                    stock.setStatus(BaseStatus.FREE);
                    /*if (ImportEntityUtils.stringFlag(pointCode)){
                        Point point=pointRepository.findByCode(pointCode);
                        stock.setPoint(point);
                    }*/
                    stock.setEnabled(true);
                    stock.setStockType(st);
                    stock.setDept(UserUtils.getDept());
                    stockService.create(stock);
                }else{
                    /*if (ImportEntityUtils.stringFlag(pointCode)){
                        Point point=pointRepository.findByCode(pointCode);
                        stock.setPoint(point);
                    }*/
                    stock.setCode(code);
                    stock.setName(code);
                    stock.setStockType(st);
                    stockService.update(stock);
                }

                log.info("导入"+(i+1)+"行");
            }
        }catch (Exception e){
            ApiError apiError = ApiError.errorJosn(HttpStatus.BAD_REQUEST.value(), "导入异常---第"+(i+1)+"行："+e.toString());
            return new ResponseEntity(apiError, HttpStatus.valueOf(apiError.getStatus()));
        }


        ApiError apiError = ApiError.errorJosn(HttpStatus.OK.value(), "导入成功："+(i)+"行 新增（"+new_len+")修改（"+edit_len+")");
        return new ResponseEntity(apiError, HttpStatus.valueOf(apiError.getStatus()));

    }

    @GetMapping
    @ApiOperation("查询stock")
    public ResponseEntity<Object> queryStock(StockQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(stockService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @ApiOperation("查询可用空闲的容器stock")
    @GetMapping(value = "/queryKyStockList")
    public ResponseEntity<Object> queryKyStockList(StockQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(stockService.queryKyStockList(criteria.getCode()),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增stock")
    @ApiOperation("新增stock")
    @PreAuthorize("@el.check('stock:add')")
    public ResponseEntity<Object> createStock(@Validated @RequestBody Stock resources){
        resources.setDept(UserUtils.getDept());
        resources.setEnabled(true);
        return new ResponseEntity<>(stockService.create(resources),HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改stock")
    @ApiOperation("修改stock")
    @PreAuthorize("@el.check('stock:edit')")
    public ResponseEntity<Object> updateStock(@Validated @RequestBody Stock resources){
        stockService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @PutMapping("/updateStockOK")
    @Log("修改stock")
    @ApiOperation("修改stock")
    @PreAuthorize("@el.check('stock:edit')")
    public ResponseEntity<Object> updateStockOK(@Validated @RequestBody Stock resources){
        stockService.update(resources);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @PutMapping("/updateStockStatus")
    @Log("批量修改stock的状态")
    @ApiOperation("批量修改stock的状态")
    @PreAuthorize("@el.check('stock:edit')")
    public ResponseEntity<Object> updateStockStatus(@Validated @RequestBody List<Stock> stockList){
        for (Stock s : stockList) {
            stockService.update(s);
        }
        return new ResponseEntity<>(HttpStatus.OK);
    }

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

    @PostMapping(value = "/getItemCode")
    @AnonymousAccess
    public ResponseEntity<Object> getItemCode(@Validated @RequestBody String stockCode){
        return new ResponseEntity<>(stockService.getItemCode(stockCode),HttpStatus.OK);
    }

}
