/*
 *  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.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.exception.handler.ApiResult;
import com.youchain.modules.system.domain.Dept;
import com.youchain.utils.*;
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.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;

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

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

    private final StockService stockService;

    private final FileProperties properties;

    private final StockTypeService stockTypeService;

    private final BatchCreateOrUpdate batchCreateOrUpdate;

    private final RedisObjectUtils redisObjectUtils;

    @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);
        try {
            List<Map<String, Object>> readAll = reader.readAll();
            Set<String> stockCodes = new HashSet<>();//容器集合
            for (Map<String, Object> record : readAll) {
                String stockCode = record.get("代码").toString().trim();
                if (!StringUtils.isEmpty(stockCode)) {
                    stockCodes.add(stockCode);
                }
            }

            //获取已存在的点位
            Map<String, Stock> existingStock = stockService.findByCodes(stockCodes);

            List<Stock> stocksToCreate = new ArrayList<>();//新增容器集合
            List<Stock> stocksToUpdate = new ArrayList<>();//修改容器集合

            for (Map<String, Object> record : readAll) {
                String stockCode = record.get("代码").toString().trim();
                String stockType = record.get("类型").toString().trim();

                //判断是否已存在容器
                if (existingStock.containsKey(stockCode)) {
                    //修改容器
                    Stock stock = existingStock.get(stockCode);
                    stocksToUpdate.add(updateStock(stock, stockType));
                } else {
                    //新增容器
                    stocksToCreate.add(createStock(stockType, UserUtils.getDept(), record));
                }
            }

            CompletableFuture<Void> createFuture = CompletableFuture.runAsync(() -> {
                //批量新增Mo票
                if (!stocksToCreate.isEmpty()) {
                    batchCreateOrUpdate.batchCreate(stocksToCreate);
                }
            });

            CompletableFuture<Void> updateFuture = CompletableFuture.runAsync(() -> {
                //批量更新Mo票
                if (!stocksToUpdate.isEmpty()) {
                    batchCreateOrUpdate.batchUpdate(stocksToUpdate);
                }
            });
            // 等待所有操作完成
            CompletableFuture.allOf(createFuture, updateFuture).join();
            return successRequest("导入成功：" + " 新增（" + stocksToCreate.size() + ")修改（" + stocksToUpdate.size() + ")", "");

        } catch (Exception e) {
            return badRequest("导入失败：" + e.getMessage());
        }

    }

    private Stock createStock(String stockType, Dept dept, Map<String, Object> record) {
        Stock stock = new Stock();
        stock.setCode(record.get("代码").toString().trim());
        stock.setName(record.get("代码").toString().trim());
        stock.setStockType(stockType);
        stock.setDept(dept);
        stock.setStatus(BaseStatus.FREE);
        stock.setEnabled(true);
        return stock;
    }

    private Stock updateStock(Stock stock, String stockType) {
        stock.setStockType(stockType);
        return stock;
    }

    @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);
    }

    private ResponseEntity<Object> badRequest(String message) {
        return new ResponseEntity<>(ApiResult.fail(BAD_REQUEST.value(), message, ""), HttpStatus.BAD_REQUEST);
    }

    private ResponseEntity<Object> successRequest(String message, Object object) {
        return new ResponseEntity<>(ApiResult.fail(OK.value(), message, object), HttpStatus.OK);
    }

}
