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

import com.youchain.businessdata.domain.AsnDetail;
import com.youchain.businessdata.domain.Mo;
import com.youchain.businessdata.domain.Order;
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.businessdata.repository.OrderRepository;
import com.youchain.businessdata.service.OrderService;
import com.youchain.businessdata.service.dto.OrderDto;
import com.youchain.businessdata.service.dto.OrderQueryCriteria;
import com.youchain.businessdata.service.mapstruct.OrderMapper;
import org.springframework.data.domain.Example;
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 javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.http.HttpServletResponse;

/**
 * @author huojin
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2024-04-08
 **/
@Service
@RequiredArgsConstructor
public class OrderServiceImpl implements OrderService {

    private final OrderRepository orderRepository;
    private final OrderMapper orderMapper;
    private final EntityManager entityManager;


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

    @Override
    public List<OrderDto> queryAll(OrderQueryCriteria criteria) {
        return orderMapper.toDto(orderRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    @Transactional
    public OrderDto findById(Integer id) {
        Order order = orderRepository.findById(id).orElseGet(Order::new);
        ValidationUtil.isNull(order.getId(), "Order", "id", id);
        return orderMapper.toDto(order);
    }

    @Override
    @Transactional
    public OrderDto findByDeliveryHeaderId(Integer deliveryHeaderId) {
        String hql = "from Order o where o.deliveryHeaderId = :deliveryHeaderId";
        Query query = entityManager.createQuery(hql);
        query.setParameter("deliveryHeaderId", deliveryHeaderId);
        List<Order> orders = query.getResultList();
        if (orders.size() > 0) {
            return orderMapper.toDto(orders.get(0)); // 返回第一个订单
        } else {
            return null;
        }
    }

    @Override
    public OrderDto findByBarcodeNumber(String barcodeNumber) {
        String hql = "from Order o where o.barcodeNumber = :barcodeNumber";
        Query query = entityManager.createQuery(hql);
        query.setParameter("barcodeNumber", barcodeNumber);
        List<Order> orders = query.getResultList();
        if (orders.size() > 0) {
            return orderMapper.toDto(orders.get(0)); // 返回第一个订单
        } else {
            return null;
        }

    }

    @Override
    public Map<String, Order> findByBarcodeNumbers(Set barcodeNumbers) {
        Map<String, Order> result = new HashMap<>();
        String hql = "from Order o where o.barcodeNumber in (:barcodeNumbers)";
        Query query = entityManager.createQuery(hql);    // 这里的query是org.hibernate.query.Query
        query.setParameter("barcodeNumbers", barcodeNumbers);
        List<Order> orders = query.getResultList();
        for (Order order : orders) {
            result.put(order.getBarcodeNumber(), order);
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderDto create(Order resources) {
        return orderMapper.toDto(orderRepository.save(resources));
    }

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

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

    @Override
    public void download(List<OrderDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (OrderDto order : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("送货单ID", order.getDeliveryHeaderId());
            map.put("送货单条码", order.getBarcodeNumber());
            map.put("物料编码", order.getItemCode());
            map.put("检验结果", order.getIqcResult());
            map.put("送货单状态", order.getDeliveryStatus());
            map.put("计划数量", order.getDeliveryQty());
            map.put("接收数量", order.getReceivedQty());
            map.put("供应商编码", order.getSupplierCode());
            map.put("供应商名称", order.getSupplierName());
            map.put("送货单号", order.getDeliveryNumber());
            map.put("是否检验", order.getIsIqcInspected());
            map.put("检验员", order.getInInspector());
            map.put("mls修改时间", order.getMlsUpdateTime());
            map.put("wms接收时间", order.getCreateTime());
            map.put("wms修改时间", order.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public Order toEntity(OrderDto orderDto) {
        return orderMapper.toEntity(orderDto);
    }

}
