/*
 *  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 com.google.common.collect.Maps;
import com.youchain.basicdata.domain.Item;
import com.youchain.basicdata.domain.Point;
import com.youchain.basicdata.service.dto.ItemSmallDto;
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.apache.commons.collections4.CollectionUtils;
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.util.*;
import java.io.IOException;
import java.util.stream.Collectors;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.http.HttpServletResponse;

import org.springframework.data.domain.Example;

/**
 * @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 EntityManager entityMapper;

    @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
    public Item findByItemId(Long id) {
        Item item = itemRepository.findById(id).orElseGet(Item::new);
        return item;
    }

    @Override
    @Transactional
    public ItemDto findByCode(String itemCode) {
        Item itemExample = new Item();
        itemExample.setCode(itemCode);
        Example<Item> example = Example.of(itemExample);
        List<Item> its = itemRepository.findAll(example);
        if (its.size() > 0) {
            return itemMapper.toDto(its.get(0));
        } else {
            return null;
        }
    }

    @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 Exception {
        List<Map<String, Object>> list = ExcelDownUtils.CreateMap(all, "Item");
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public Item toEntity(ItemDto itemDto) {
        return itemMapper.toEntity(itemDto);
    }


    @Override
    public Item existItem(String itemCode) {
        String hql = "select it from Item it where it.code='" + itemCode + "'";
        Query query = entityMapper.createQuery(hql);
        List<Item> its = query.getResultList();
        if (its.size() > 0) {
            return its.get(0);
        }
        return null;
    }

    @Override
    public List<Item> queryByItemCodes(List<String> itemCodes) {
        if (CollectionUtils.isEmpty(itemCodes)) {
            return Collections.emptyList();
        }
        //去重
        itemCodes = itemCodes.stream().filter(Objects::nonNull).distinct().collect(Collectors.toList());
        return itemRepository.queryByItemCodes(itemCodes);
    }

    @Override
    public Map<String, Item> queryByItemCodesToMap(List<String> itemCodes) {
        List<Item> items = queryByItemCodes(itemCodes);
        //封装成map
        Map<String, Item> itemMap = Maps.newHashMap();
        for (Item item : items) {
            itemMap.put(item.getCode(), item);
        }
        return itemMap;
    }

}