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

import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.youchain.RequestData.TransTask;
import com.youchain.appupdate.ReturnJson.ReturnTaskVo;
import com.youchain.basicdata.domain.Area;
import com.youchain.basicdata.domain.Item;
import com.youchain.basicdata.domain.Point;
import com.youchain.basicdata.domain.Stock;
import com.youchain.basicdata.repository.AreaRepository;
import com.youchain.basicdata.repository.PointRepository;
import com.youchain.basicdata.service.ItemService;
import com.youchain.basicdata.vo.BarCodeVo;
import com.youchain.businessdata.domain.*;
import com.youchain.businessdata.repository.*;
import com.youchain.businessdata.service.*;
import com.youchain.businessdata.service.dto.TaskDto;
import com.youchain.config.FileProperties;
import com.youchain.exception.BadRequestException;
import com.youchain.modules.mnt.websocket.MsgType;
import com.youchain.modules.mnt.websocket.SocketMsg;
import com.youchain.modules.mnt.websocket.WebSocketServer;
import com.youchain.modules.system.domain.Dept;
import com.youchain.utils.*;
import lombok.RequiredArgsConstructor;
import com.youchain.basicdata.repository.StockRepository;
import com.youchain.basicdata.service.StockService;
import com.youchain.basicdata.service.dto.StockDto;
import com.youchain.basicdata.service.dto.StockQueryCriteria;
import com.youchain.basicdata.service.mapstruct.StockMapper;
import lombok.extern.slf4j.Slf4j;
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.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;


/**
 * @author liuxue
 * @website <a href="https://eladmin.vip">...</a>
 * @description 服务实现
 * @date 2023-07-28
 **/
@Service
@RequiredArgsConstructor
@Slf4j
public class StockServiceImpl implements StockService {

    private final StockRepository stockRepository;
    private final PointRepository pointRepository;
    private final StockMapper stockMapper;
    private final FileProperties properties;


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

    @Override
    public List<StockDto> queryAll(StockQueryCriteria criteria) {
        return stockMapper.toDto(stockRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }


    @Override
    @Transactional
    public StockDto findById(Long id) {
        Stock stock = stockRepository.findById(id).orElseGet(Stock::new);
        ValidationUtil.isNull(stock.getId(), "Stock", "id", id);
        return stockMapper.toDto(stock);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public StockDto create(Stock resources) {
        if (resources.getPoint() != null) {
            Point point = resources.getPoint();
            point.setStatus(BaseStatus.USED);
            pointRepository.save(point);
        }
        return stockMapper.toDto(stockRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Stock resources) {
        Stock stock = stockRepository.findById(resources.getId()).orElseGet(Stock::new);
        if (stock.getPoint() != null) {
            Point point = stock.getPoint();
            point.setStatus(BaseStatus.FREE);
            pointRepository.save(point);
        }

        if (resources.getPoint() != null) {
            //绑定的点位是否暂用了其他容器
            Point point = resources.getPoint();
            Stock curStock = this.findByPointCode(point.getCode());
            if (curStock != null) {
                if (!curStock.getId().equals(resources.getId())) {
                    throw new BadRequestException(point.getCode() + "点位绑定的当前容器为" + curStock.getCode());
                }
            }
            point.setStatus(BaseStatus.USED);
            pointRepository.save(point);
        } else {
            resources.setPoint(null);
            stockRepository.save(resources);
        }
        ValidationUtil.isNull(stock.getId(), "Stock", "id", resources.getId());
        stock.copy(resources);
        stockRepository.save(stock);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            stockRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<StockDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (StockDto stock : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("代码", stock.getCode());
            map.put("类型", stock.getStockType());
            map.put("状态", stock.getStatus());
            map.put("启用", stock.getEnabled());
            map.put("地标", stock.getPoint() == null ? null : stock.getPoint().getCode());
            list.add(map);
        }

        FileUtil.downloadExcel(list, response);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importStock(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);

        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 = this.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));
            }
        }
        //批量新增Mo票
        if (!stocksToCreate.isEmpty()) {
            stockRepository.saveAll(stocksToCreate);
        }

        //批量更新Mo票
        if (!stocksToUpdate.isEmpty()) {
            stockRepository.saveAll(stocksToUpdate);
        }
        return ("导入成功：" + " 新增（" + stocksToCreate.size() + ")修改（" + stocksToUpdate.size() + ")");


    }


    @Override
    public Map<String, Stock> findByCodes(Set<String> stockCodes) {
        List<Stock> stockList = stockRepository.findByCodes(stockCodes);
        Map<String, Stock> stockMap = new HashMap<>();
        for (Stock stock : stockList) {
            stockMap.put(stock.getCode(), stock);
        }
        return stockMap;
    }

    @Override
    public String stockMsg(String msg) {
        try {
            SocketMsg socketMsg = new SocketMsg(msg, MsgType.INFO);
            WebSocketServer.sendInfo(socketMsg, "stock");
            String message = JSONObject.toJSONString(socketMsg);
            return message;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "error";
    }


    /**
     * 验证容器是否存在
     *
     * @param containerCode 容器编号
     */
    @Override
    public Stock validateStock(String containerCode) {
        Stock stock = stockRepository.findByCode(containerCode);
        if (stock == null) {
            throw new BadRequestException("容器不存在或已失效");
        }
        return stock;
    }

    @Override
    public void validateStockStatus(Stock stock) {
        if (BaseStatus.USED.equals(stock.getStatus()) || stock.getPoint() != null) {
            throw new BadRequestException(stock.getCode() + "容器已占用,请更换容器!");
        }
       
    }

    /**
     * 占用容器
     *
     * @param stock  容器
     * @param point  点位
     * @param status 状态
     */
    @Override
    public void usedStock(Stock stock, Point point, String status) {
        stock.setPoint(point);
        stock.setStatus(status);
        stockRepository.save(stock);
    }

    @Override
    public Stock findByCode(String code) {
        return stockRepository.findByCode(code);
    }

    @Override
    public List<Stock> findByFreeOrUsedStock(String areaName, String status) {
        return stockRepository.findByFreeOrUsedStock(areaName, status);
    }

    @Override
    public Stock findByPointCode(String code) {
        return stockRepository.findByPointCode(code);
    }

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

}
