/*
 *  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.service.impl;


import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.youchain.basicdata.domain.Item;
import com.youchain.basicdata.domain.Point;
import com.youchain.basicdata.domain.Stock;
import com.youchain.basicdata.service.ItemService;
import com.youchain.basicdata.service.PointService;
import com.youchain.basicdata.service.StockService;
import com.youchain.businessdata.domain.Inventory;
import com.youchain.businessdata.domain.ItemKey;
import com.youchain.businessdata.service.InventoryLogService;
import com.youchain.businessdata.service.ItemKeyService;
import com.youchain.businessdata.service.dto.*;
import com.youchain.config.FileProperties;
import com.youchain.exception.handler.ApiResult;
import com.youchain.modules.system.domain.Dept;
import com.youchain.utils.*;
import lombok.RequiredArgsConstructor;
import com.youchain.businessdata.repository.InventoryRepository;
import com.youchain.businessdata.service.InventoryService;
import com.youchain.businessdata.service.mapstruct.InventoryMapper;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.multipart.MultipartFile;


import java.io.File;
import java.sql.Timestamp;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

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

/**
 * @author huojin
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2023-08-22
 **/
@Service
@RequiredArgsConstructor
public class InventoryServiceImpl implements InventoryService {

    private final InventoryRepository inventoryRepository;
    private final InventoryMapper inventoryMapper;
    private final StockService stockService;
    private final ItemService itemService;
    private final PointService pointService;
    private final ItemKeyService itemKeyService;
    private final InventoryLogService inventoryLogService;
    private final FileProperties properties;

    @Override
    public Map<String, Object> queryAll(InventoryQueryCriteria criteria, Pageable pageable) {
        Page<Inventory> page = inventoryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(inventoryMapper::toDto));
    }

    @Override
    public List<InventoryDto> queryAll(InventoryQueryCriteria criteria) {
        return inventoryMapper.toDto(inventoryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }


    @Override
    public Inventory findById(Long id) {
        return inventoryRepository.findById(id).orElseGet(Inventory::new);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public InventoryDto create(Inventory resources) {
        return inventoryMapper.toDto(inventoryRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Inventory resources) {
        Inventory inventory = inventoryRepository.findById(resources.getId()).orElseGet(Inventory::new);
        ValidationUtil.isNull(inventory.getId(), "Inventory", "id", resources.getId());
        inventory.copy(resources);
        inventoryRepository.save(inventory);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            Inventory inventory = this.findById(id);
            Stock stock = inventory.getStock();
            Point point = inventory.getPoint();
            inventoryRepository.deleteById(inventory.getId());
            List<Inventory> inventoryList = this.findByStockCode(stock.getCode());
            if (inventoryList.isEmpty()) {
                pointService.freePoint(point);
                stockService.usedStock(stock, null, BaseStatus.FREE);
            }
        }
    }

    @Override
    public void download(List<InventoryDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (InventoryDto inventory : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("单据号", inventory.getBillCode());
            map.put("物料属性", inventory.getItemKey());
            map.put("点位", inventory.getPoint());
            map.put("点位号", inventory.getPointCode());
            map.put("容器", inventory.getStock());
            map.put("容器号", inventory.getStockCode());
            map.put("大容器", inventory.getBigStock());
            map.put("数量", inventory.getQuantity());
            map.put("分配数", inventory.getQueuedQty());
            map.put("重量", inventory.getWeight());
            map.put("体积", inventory.getVolume());
            map.put("描述", inventory.getDescription());
            map.put("是否锁定", inventory.getBeLock());
            map.put("是否不良品", inventory.getBeReject());
            map.put("状态", inventory.getStatus());
            map.put("存货日期", inventory.getStorageDate());
            map.put("仓库ID", inventory.getDept());
            map.put("创建人", inventory.getCreateBy());
            map.put("修改人", inventory.getUpdateBy());
            map.put("创建时间", inventory.getCreateTime());
            map.put("修改时间", inventory.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void clearInventory(Stock stock) {
        List<Inventory> inventoryList = inventoryRepository.queryInventory(stock.getId(), null, null, null, stock.getDept().getId());
        if (!inventoryList.isEmpty()) {
            inventoryRepository.deleteAll(inventoryList);
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Inventory createInventory(ItemKey itemKey, Point point, Stock stock, Dept dept, Double quantity) {
        Inventory inventory = new Inventory();
        inventory.setItemKey(itemKey);
        inventory.setPoint(point);
        inventory.setPointCode(point.getCode());
        inventory.setStock(stock);
        inventory.setStockCode(stock.getCode());
        inventory.setDept(dept);
        inventory.setQuantity(quantity);
        inventoryRepository.save(inventory);
        return inventory;
    }

    @Override
    public List<Inventory> queryInventory(Long stockId, Long itemId, Long pointId, String areaName, Long deptId) {
        return inventoryRepository.queryInventory(stockId, itemId, pointId, areaName, deptId);
    }

    @Override
    public Inventory findByOrderNumber(String orderNumber, String srcStockCode) {
        return inventoryRepository.findByOrderNumber(orderNumber, srcStockCode);
    }

    @Override
    public List<Inventory> findByStockCode(String stockCode) {
        return inventoryRepository.findByStockCode(stockCode);
    }

    @Override
    public Page<List<Object[]>> queryBigScreenPointInfo(int currentPage, int pageSize) {
        Pageable pageable = PageRequest.of(currentPage - 1, pageSize);
        return inventoryRepository.queryBigScreenPointInfo(pageable);
    }

    @Override
    public List<Inventory> findByOrderNumbers(List<String> orderNumbers) {
        return inventoryRepository.findByOrderNumbers(orderNumbers);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<Object> impoertBigItemInventory(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);
        Dept dept = UserUtils.getDept();
        ExcelReader reader = ExcelUtil.getReader(file);
        List<Map<String, Object>> readAll = reader.readAll();
        Set<String> stocks = new HashSet<>();//托盘集合
        List<String> orderNumbers = new ArrayList<>();//箱号集合
        Set<String> items = new HashSet<>();//物料集合
        Set<String> points = new HashSet<>();//点位集合
        Map<String, Set<String>> stockItemMap = new HashMap<>();//一个托盘一种物料
        for (Map<String, Object> record : readAll) {
            String stock = record.get("托盘号").toString().trim();
            String orderNumber = record.get("箱号").toString().trim();
            String itemCode = record.get("物料编码").toString().trim();
            String pointCode = record.get("点位").toString().trim();
            if (StringUtils.isNotEmpty(stock)) {
                stocks.add(stock);
            }
            if (StringUtils.isNotEmpty(orderNumber)) {
                orderNumbers.add(orderNumber);
            }
            if (StringUtils.isNotEmpty(itemCode)) {
                items.add(itemCode);
            }
            if (StringUtils.isNotEmpty(pointCode)) {
                points.add(pointCode);
            }
            if (StringUtils.isNotEmpty(stock) && StringUtils.isNotEmpty(itemCode)) {
                Set<String> itemSet = stockItemMap.get(stock);
                if (itemSet == null) {
                    itemSet = new HashSet<>();
                }
                itemSet.add(itemCode);
                stockItemMap.put(stock, itemSet);
            }
        }
        //验证托盘
        Map<String, Stock> existingStock = stockService.findByCodes(stocks);
        Set<String> stockCodes = existingStock.keySet().stream().collect(Collectors.toSet());
        Set<String> differenceStockSet = stocks.stream().filter(stock -> !stockCodes.contains(stock)).collect(Collectors.toSet());
        if (!differenceStockSet.isEmpty()) {
            return new ResponseEntity<>(ApiResult.fail(BAD_REQUEST.value(), "WMS不存在的托盘集合,请维护：" + differenceStockSet, null), HttpStatus.BAD_REQUEST);
        }

        //验证箱号
        boolean hasDuplicates = orderNumbers.size() != orderNumbers.stream().distinct().count();
        if (hasDuplicates) {
            return new ResponseEntity<>(ApiResult.fail(BAD_REQUEST.value(), "文件中有重复的箱号,请调整", null), HttpStatus.BAD_REQUEST);
        }

        //验证物料
        Map<String, Item> existingItem = itemService.findByCodes(items, "大件");
        Set<String> itemCodes = existingItem.keySet().stream().collect(Collectors.toSet());
        Set<String> differenceItemSet = items.stream().filter(item -> !itemCodes.contains(item)).collect(Collectors.toSet());
        if (!differenceItemSet.isEmpty()) {
            return new ResponseEntity<>(ApiResult.fail(BAD_REQUEST.value(), "WMS不存在的物料集合,请维护：" + differenceItemSet, null), HttpStatus.BAD_REQUEST);
        }

        //验证库位
        Map<String, Point> existingPoint = pointService.findByCodes(points);
        Set<String> pointCodes = existingPoint.keySet().stream().collect(Collectors.toSet());
        Set<String> differencePointSet = points.stream().filter(point -> !pointCodes.contains(point)).collect(Collectors.toSet());
        if (!differencePointSet.isEmpty()) {
            return new ResponseEntity<>(ApiResult.fail(BAD_REQUEST.value(), "WMS不存在的点位集合,请维护：" + differencePointSet, null), HttpStatus.BAD_REQUEST);
        }

        // 验证一个托盘只能一种物料;用于存储不符合条件的托盘
        List<String> invalidStocks = new ArrayList<>();
        for (Map.Entry<String, Set<String>> entry : stockItemMap.entrySet()) {
            String tp = entry.getKey();
            Set<String> values = entry.getValue();
            if (values.size() > 1) {
                invalidStocks.add(tp);
            }
        }
        if (!invalidStocks.isEmpty()) {
            return new ResponseEntity<>(ApiResult.fail(BAD_REQUEST.value(), "以下托盘包含多种物料:" + invalidStocks, null), HttpStatus.BAD_REQUEST);
        }

        //1.验证箱号是否已生成库存
        List<Inventory> inventoryList = this.findByOrderNumbers(orderNumbers);
        List<String> existingOrderNumber = new ArrayList<>();
        for (Inventory inventory : inventoryList) {
            existingOrderNumber.add(inventory.getItemKey().getOrderNumber());
        }
        if (!existingOrderNumber.isEmpty()) {
            return new ResponseEntity<>(ApiResult.fail(BAD_REQUEST.value(), "以下箱号已导入，请勿重复导入:" + existingOrderNumber, null), HttpStatus.BAD_REQUEST);
        }

        //2.新增库存
        for (Map<String, Object> record : readAll) {
            String stockCode = record.get("托盘号").toString().trim();
            String orderNumber = record.get("箱号").toString().trim();
            String itemCode = record.get("物料编码").toString().trim();
            String quantity = record.get("数量").toString().trim();
            String propC1 = record.get("批次号").toString().trim();
            String propD1 = record.get("生产日期").toString().trim();
            String pointCode = record.get("点位").toString().trim();
            //物料
            Item item = existingItem.get(itemCode);
            //托盘
            Stock stock = existingStock.get(stockCode);
            //库位
            Point point = existingPoint.get(pointCode);
            //创建ItemKey
            ItemKey itemKey = itemKeyService.createItemKey(item, propC1, Timestamp.valueOf(propD1), orderNumber);
            //生成库存
            Inventory inventory = this.createInventory(itemKey, point, stock, dept, Double.parseDouble(quantity));
            //点位占用
            pointService.usedPoint(point);
            //占用容器
            stockService.usedStock(stock, point, BaseStatus.USED);

            //新增日志
            inventoryLogService.createInventoryLog(BizStatus.RECEIVING_UP, BizStatus.ADD, null, itemKey, null, point, stock, stock, 0d, Double.parseDouble(quantity), BizStatus.ASN, null, inventory.getId(), null);

        }

        return new ResponseEntity<>(ApiResult.fail(OK.value(), "导入成功!", null), HttpStatus.OK);
    }


}
