/*
*  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.BigItem;
import com.youchain.basicdata.domain.Item;
import com.youchain.exception.EntityExistException;
import com.youchain.utils.*;
import lombok.RequiredArgsConstructor;
import com.youchain.basicdata.repository.BigItemRepository;
import com.youchain.basicdata.service.BigItemService;
import com.youchain.basicdata.service.dto.BigItemDto;
import com.youchain.basicdata.service.dto.BigItemQueryCriteria;
import com.youchain.basicdata.service.mapstruct.BigItemMapper;
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;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author baobinglin
* @date 2023-12-29
**/
@Service
@RequiredArgsConstructor
public class BigItemServiceImpl implements BigItemService {

    private final BigItemRepository bigItemRepository;
    private final BigItemMapper bigItemMapper;
    private final EntityManager entityManager;

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

    @Override
    public List<BigItemDto> queryAll(BigItemQueryCriteria criteria){
        return bigItemMapper.toDto(bigItemRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public BigItemDto findById(Long id) {
        BigItem bigItem = bigItemRepository.findById(id).orElseGet(BigItem::new);
        ValidationUtil.isNull(bigItem.getId(),"BigItem","id",id);
        return bigItemMapper.toDto(bigItem);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BigItemDto create(BigItem resources) {
        return bigItemMapper.toDto(bigItemRepository.save(resources));
    }

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

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

    @Override
    public void download(List<BigItemDto> all, HttpServletResponse response) throws Exception {
        List<Map<String, Object>>  list= ExcelDownUtils.CreateMap(all,"BigItem");
//        List<Map<String, Object>> list = new ArrayList<>();
//        for (BigItemDto bigItem : all) {
//            Map<String,Object> map = new LinkedHashMap<>();
//            map.put("完成品品番", bigItem.getCode());
//            map.put("完成形式名", bigItem.getName());
//            map.put("机种", bigItem.getModels());
//            map.put("国别", bigItem.getCountry());
//            map.put("出库类型", bigItem.getOutboundType());
//            map.put("仓库ID", bigItem.getDeptId());
//            map.put("是否启用", bigItem.getEnabled());
//            map.put("描述", bigItem.getDescription());
//            map.put("创建人", bigItem.getCreateBy());
//            map.put("修改人", bigItem.getUpdateBy());
//            map.put("创建时间", bigItem.getCreateTime());
//            map.put("修改时间", bigItem.getUpdateTime());
//            list.add(map);
//        }
        FileUtil.downloadExcel(list, response);
    }
    public List<BigItemDto> getBigItem(String type){
        List<BigItem> bigItems=bigItemRepository.getBigItem();
        return bigItemMapper.toDto(bigItems);
    }

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

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

    @Override
    public Map<String, BigItem> queryByBigItemCodesToMap(List<String> codes) {
        List<BigItem> items = queryByBigItemCodes(codes);
        //封装成map
        Map<String, BigItem> itemMap = Maps.newHashMap();
        for (BigItem item : items) {
            itemMap.put(item.getCode(), item);
        }
        return itemMap;
    }


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

    @Override
    public Map<String, BigItem> queryByBigItemNamesToMap(List<String> names) {
        List<BigItem> items = queryByBigItemNames(names);
        //封装成map
        Map<String, BigItem> itemMap = Maps.newHashMap();
        for (BigItem item : items) {
            itemMap.put(item.getMasterName(), item);
        }
        return itemMap;
    }

}