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

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.youchain.basicdata.domain.Area;
import com.youchain.basicdata.domain.Point;
import com.youchain.basicdata.service.AreaService;
import com.youchain.config.FileProperties;
import com.youchain.exception.BadRequestException;
import com.youchain.modules.system.domain.Dept;
import com.youchain.utils.*;
import lombok.RequiredArgsConstructor;
import com.youchain.basicdata.repository.PointRepository;
import com.youchain.basicdata.service.PointService;
import com.youchain.basicdata.service.dto.PointDto;
import com.youchain.basicdata.service.dto.PointQueryCriteria;
import com.youchain.basicdata.service.mapstruct.PointMapper;
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.util.*;
import java.io.IOException;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

/**
 * @author liuxue
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2023-07-26
 **/
@Service
@RequiredArgsConstructor
@Slf4j
public class PointServiceImpl implements PointService {

    private final PointRepository pointRepository;
    private final PointMapper pointMapper;
    private final AreaService areaService;
    private final FileProperties properties;

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

    @Override
    public List<PointDto> queryAll(PointQueryCriteria criteria) {
        return pointMapper.toDto(pointRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }


    @Override
    @Transactional
    public PointDto findById(Long id) {
        Point point = pointRepository.findById(id).orElseGet(Point::new);
        ValidationUtil.isNull(point.getId(), "Point", "id", id);
        return pointMapper.toDto(point);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PointDto create(Point resources) {
        return pointMapper.toDto(pointRepository.save(resources));
    }

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

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

    @Override
    public void download(List<PointDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (PointDto point : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("RCS代码", point.getCode());
            map.put("名称", point.getName());
            map.put("状态", point.getStatus());
            map.put("描述", point.getDescription());
            map.put("区域编码", point.getBeatCode());
            map.put("物料编码", point.getItemCode());
            map.put("库区名称", point.getArea().getName());
            map.put("是否启用", point.getEnabled());
            map.put("仓库名称", point.getDept().getName());
            map.put("坐标X", point.getPosX());
            map.put("坐标Y", point.getPosY());
            map.put("坐标Z", point.getPosZ());
            map.put("类型", point.getType());
            map.put("热度", point.getHeat());
            map.put("创建人", point.getCreateBy());
            map.put("修改人", point.getUpdateBy());
            map.put("创建时间", point.getCreateTime());
            map.put("修改时间", point.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public Point validatePoint(String position) {
        Point point = pointRepository.findByCode(position);
        if (point == null) {
            throw new BadRequestException("点位不存在或已失效");
        }
        return point;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void usedPoint(Point point) {
        point.setStatus(BaseStatus.USED);
        pointRepository.save(point);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void freePoint(Point point) {
        point.setStatus(BaseStatus.FREE);
        pointRepository.save(point);
    }

    @Override
    public void validatePointStatus(Point point) {
        if (BaseStatus.USED.equals(point.getStatus())) {
            throw new RuntimeException(point.getCode() + "点位已有任务，请勿重复操作!");
        }
    }

    @Override
    public List<Point> queryPoints(String code, String status, String type, String areaName) {
        return pointRepository.queryPoints(code, status, type, areaName);
    }

    @Override
    public Point queryPoint(String code, String status, String type, String areaName) {
        List<Point> pointList = pointRepository.queryPoints(code, status, type, areaName);
        if (pointList.isEmpty()) {
            throw new BadRequestException(code + "点位不存在或已失效");
        }
        return pointList.get(0);
    }

    @Override
    public Map<String, Point> findByCodes(Set<String> pointCodes) {
        List<Point> pointList = pointRepository.findByCodes(pointCodes);
        Map<String, Point> pointMap = new HashMap<>();
        for (Point point : pointList) {
            pointMap.put(point.getCode(), point);
        }
        return pointMap;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importPoint(MultipartFile multipartFile) {
        //编码、类型、库区、存储类型、坐标X、坐标Y
        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> pointCodes = new HashSet<>();//点位集合
        Set<String> areaNames = new HashSet<>();//库区集合
        for (Map<String, Object> record : readAll) {
            String pointCode = record.get("编码").toString().trim();
            String areaName = record.get("库区").toString().trim();
            if (!StringUtils.isEmpty(pointCode)) {
                pointCodes.add(pointCode);
            }
            if (!StringUtils.isEmpty(areaName)) {
                areaNames.add(areaName);
            }
        }


        //获取已存在的点位
        Map<String, Point> existingPoint = this.findByCodes(pointCodes);

        //查找数据库中存在的库区
        List<Area> areaList = areaService.findByCodes(areaNames);
        Set<String> newAreaNames = areaList.stream().map(Area::getName).collect(Collectors.toSet());

        // 取areaCodes和newAreaCodes的差集，说明有不存在的库区
        Set<String> diffAreaNames = areaNames.stream().filter(name -> !newAreaNames.contains(name)).collect(Collectors.toSet());

        if (!diffAreaNames.isEmpty()) {
            throw new BadRequestException("WMS不存在的库区集合,请维护：" + diffAreaNames);
        }


        Map<String, Area> existingArea = areaList.stream().collect(Collectors.toMap(Area::getName, area -> area));

        List<Point> pointsToCreate = new ArrayList<>();//新增点位集合
        List<Point> pointsToUpdate = new ArrayList<>();//修改点位集合
        for (Map<String, Object> record : readAll) {
            String pointCode = record.get("编码").toString().trim();
            String areaCode = record.get("库区").toString().trim();
            Area area = existingArea.get(areaCode);
            //判断是否已存在点位
            if (existingPoint.containsKey(pointCode)) {
                Point point = existingPoint.get(pointCode);
                //更新点位
                pointsToUpdate.add(updatePoints(point, area, dept, record));
            } else {
                //新增点位
                pointsToCreate.add(createPoint(area, dept, record));
            }
        }

        //批量新增Mo票
        if (!pointsToCreate.isEmpty()) {
            pointRepository.saveAll(pointsToCreate);
        }

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

    private Point updatePoints(Point point, Area area, Dept dept, Map<String, Object> record) {
        point.setArea(area);
        point.setDept(dept);
        String types = record.get("类型").toString().trim();
        String lx = null;
        if ("缓存点".equals(types)) {
            lx = BaseStatus.STORAGE;

        } else if ("线边点位".equals(types)) {
            lx = BaseStatus.BOX;
        }
        point.setType(lx);
        point.setPosX(record.get("排") == null ? 0 : Double.parseDouble(record.get("排").toString()));
        point.setPosY(record.get("列") == null ? 0 : Double.parseDouble(record.get("列").toString()));
        point.setPosZ(record.get("层") == null ? 0 : Double.parseDouble(record.get("层").toString()));
        return point;
    }

    private Point createPoint(Area area, Dept dept, Map<String, Object> record) {
        Point point = new Point();
        point.setCode(record.get("编码").toString().trim());
        point.setName(record.get("编码").toString().trim());
        point.setArea(area);
        point.setDept(dept);
        String types = record.get("类型").toString().trim();
        String lx = null;
        if ("缓存点".equals(types)) {
            lx = BaseStatus.STORAGE;

        } else if ("线边点位".equals(types)) {
            lx = BaseStatus.BOX;
        }
        point.setType(lx);
        point.setPosX(record.get("排") == null ? 0 : Double.parseDouble(record.get("排").toString()));
        point.setPosY(record.get("列") == null ? 0 : Double.parseDouble(record.get("列").toString()));
        point.setPosZ(record.get("层") == null ? 0 : Double.parseDouble(record.get("层").toString()));
        point.setEnabled(true);
        point.setStatus(BaseStatus.FREE);
        return point;
    }
}
