/*
 *  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.youchain.basicdata.domain.Item;
import com.youchain.basicdata.domain.Point;
import com.youchain.basicdata.service.dto.ItemSmallDto;
import com.youchain.utils.FileUtil;
import com.youchain.utils.PageUtil;
import com.youchain.utils.QueryHelp;
import com.youchain.utils.ValidationUtil;
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.util.List;
import java.util.Map;
import java.io.IOException;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

import org.springframework.data.domain.Example;

import java.util.Optional;

/**
 * @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 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 toEntity(ItemDto itemDto) {
        return itemMapper.toEntity(itemDto);
    }


    @Override
    public Item existItem(String itemCode) {
        String hql = "from Item where code = :code and enabled = true";
        Query query = entityMapper.createQuery(hql);
        query.setParameter("code", itemCode);
        Optional<Item> item = query.getResultStream().findFirst();
        return item.isPresent() ? item.get() : null;
    }

}
