/*
 *  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.Item;
import com.youchain.config.FileProperties;
import com.youchain.exception.BadRequestException;
import com.youchain.modules.system.domain.Dept;
import com.youchain.modules.system.repository.DeptRepository;
import com.youchain.utils.*;
import lombok.RequiredArgsConstructor;
import com.youchain.basicdata.repository.ItemRepository;
import com.youchain.basicdata.service.ItemService;
import com.youchain.basicdata.service.dto.ItemDto;
import com.youchain.basicdata.service.dto.ItemQueryCriteria;
import com.youchain.basicdata.service.mapstruct.ItemMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.io.File;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.MultipartFile;

/**
 * @author houjianlan
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2023-08-07
 **/
@Service
@RequiredArgsConstructor
public class ItemServiceImpl implements ItemService {

    private final ItemRepository itemRepository;
    private final ItemMapper itemMapper;
    private final FileProperties properties;
    private final DeptRepository deptRepository;

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

    @Override
    public List<ItemDto> queryAll(ItemQueryCriteria criteria) {
        return itemMapper.toDto(itemRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    @Transactional
    public ItemDto findById(Long id) {
        Item item = itemRepository.findById(id).orElseGet(Item::new);
        ValidationUtil.isNull(item.getId(), "Item", "id", id);
        return itemMapper.toDto(item);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ItemDto create(Item resources) {
        return itemMapper.toDto(itemRepository.save(resources));
    }

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

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

    @Override
    public void download(List<ItemDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ItemDto item : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("代码", item.getCode());
            map.put("名称", item.getName());
            map.put("规格", item.getSpecs());
            map.put("客户ID", item.getStructureId());
            map.put("描述", item.getDescription());
            map.put("状态", item.getEnabled());
            map.put("保质期", item.getValidPeriod());
            map.put("预警天数", item.getAlertLeadingDays());
            map.put("大类", item.getLargeClass());
            map.put("中类", item.getCenterClass());
            map.put("小类", item.getSmallClass());
            map.put("物料类型", item.getGoodType());
            map.put("长", item.getLength());
            map.put("宽", item.getWidth());
            map.put("高", item.getHeight());
            map.put("重量", item.getWeight());
            map.put("体积", item.getVolume());
            map.put("单位", item.getUnit());
            map.put("大单位", item.getMasterUnit());
            map.put("包装系数", item.getPackNumber());
            map.put("条码", item.getBarCode());
            map.put("仓库ID", item.getDept());
            map.put("来源名称", item.getSourceName());
            map.put("来源序号", item.getSourceId());
            map.put("创建人", item.getCreateBy());
            map.put("修改人", item.getUpdateBy());
            map.put("创建时间", item.getCreateTime());
            map.put("修改时间", item.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public Item validateItem(String itemCode) {
        Item item = itemRepository.findByCode(itemCode);
        if (item == null) {
            throw new BadRequestException("物料不存在或已失效");
        }
        return item;
    }

    @Override
    public Map<String, Item> findByCodes(Set<String> itemCodes, String goodType) {
        List<Item> items = itemRepository.findByCodes(itemCodes, goodType);
        Map<String, Item> itemMap = new HashMap<>();
        for (Item item : items) {
            itemMap.put(item.getCode(), item);
        }
        return itemMap;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String impoertItem(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> itemCodes = new HashSet<>();//物料集合
        for (Map<String, Object> record : readAll) {
            String itemCode = record.get("编码").toString().trim();
            if (!StringUtils.isEmpty(itemCode)) {
                itemCodes.add(itemCode);
            }
        }


        //获取已存在的物料
        Map<String, Item> existingPoint = findByCodes(itemCodes, null);


        List<Item> itemsToCreate = new ArrayList<>();//新增物料集合
        List<Item> itemsToUpdate = new ArrayList<>();//修改物料集合
        for (Map<String, Object> record : readAll) {
            String itemCode = record.get("编码").toString().trim();
            //判断是否已存在点位
            if (existingPoint.containsKey(itemCode)) {
                Item item = existingPoint.get(itemCode);
                //更新点位
                itemsToUpdate.add(updateItems(item, dept, record));
            } else {
                //新增点位
                itemsToCreate.add(createItem(dept, record));
            }
        }

        //批量新增物料
        if (!itemsToCreate.isEmpty()) {
            itemRepository.saveAll(itemsToCreate);
        }

        //批量更新物料
        if (!itemsToUpdate.isEmpty()) {
            itemRepository.saveAll(itemsToUpdate);
        }
        return ("导入成功：" + " 新增（" + itemsToCreate.size() + ")修改（" + itemsToUpdate.size() + ")");
    }

    @Override
    public Item createItem(String itemCode, String itemName, Double extendD1, String goodType) {
        Item item = new Item();
        item.setCode(itemCode);
        item.setName(itemName);
        item.setExtendD1(extendD1);
        item.setGoodType(goodType);
        item.setUnit("PCS");
        item.setEnabled(true);
        Dept dept = deptRepository.getById(7L);
        item.setDept(dept);
        itemRepository.save(item);
        return item;
    }

    private Item updateItems(Item item, Dept dept, Map<String, Object> record) {
        item.setDept(dept);
        item.setName(Optional.ofNullable(record.get("名称")).map(Object::toString).map(String::trim).orElse(null));
        item.setExtendD1(Optional.ofNullable(record.get("单台用量")).map(Object::toString).map(Double::parseDouble).orElse(0.0));
        item.setUnit(Optional.ofNullable(record.get("单位")).map(Object::toString).map(String::trim).orElse(null));
        item.setGoodType(Optional.ofNullable(record.get("物料类型")).map(Object::toString).map(String::trim).orElse(null));
        return item;
    }

    private Item createItem(Dept dept, Map<String, Object> record) {
        Item item = new Item();
        item.setCode(Optional.ofNullable(record.get("编码")).map(Object::toString).map(String::trim).orElse(null));
        item.setName(Optional.ofNullable(record.get("名称")).map(Object::toString).map(String::trim).orElse(null));
        item.setExtendD1(Optional.ofNullable(record.get("单台用量")).map(Object::toString).map(Double::parseDouble).orElse(0.0));
        item.setUnit(Optional.ofNullable(record.get("单位")).map(Object::toString).map(String::trim).orElse(null));
        item.setGoodType(Optional.ofNullable(record.get("物料类型")).map(Object::toString).map(String::trim).orElse(null));
        item.setDept(dept);
        item.setEnabled(true);
        return item;
    }

}
