/*
 *  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.basicdata.domain.Point;
import com.youchain.basicdata.domain.Stock;
import com.youchain.businessdata.domain.Inventory;
import com.youchain.businessdata.domain.ItemKey;
import com.youchain.businessdata.domain.Task;
import com.youchain.businessdata.service.dto.*;
import com.youchain.modules.system.domain.Dept;
import com.youchain.utils.*;
import lombok.RequiredArgsConstructor;
import com.youchain.businessdata.repository.InventoryRepository;
import com.youchain.businessdata.service.InventoryService;
import com.youchain.businessdata.service.mapstruct.InventoryMapper;
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;

/**
 * @author huojin
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2023-08-22
 **/
@Service
@RequiredArgsConstructor
public class InventoryServiceImpl implements InventoryService {

    private final InventoryRepository inventoryRepository;
    private final InventoryMapper inventoryMapper;
    private final EntityManager entityManager;

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

    @Override
    public List<InventoryDto> queryAll(InventoryQueryCriteria criteria) {
        return inventoryMapper.toDto(inventoryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    public List<InventoryDto> queryAll(InvQueryCriteria criteria) {
        return inventoryMapper.toDto(inventoryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    @Transactional
    public InventoryDto findById(Long id) {
        Inventory inventory = inventoryRepository.findById(id).orElseGet(Inventory::new);
        ValidationUtil.isNull(inventory.getId(), "Inventory", "id", id);
        return inventoryMapper.toDto(inventory);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public InventoryDto create(Inventory resources) {
        return inventoryMapper.toDto(inventoryRepository.save(resources));
    }

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

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

    @Override
    public void download(List<InventoryDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (InventoryDto inventory : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("单据号", inventory.getBillCode());
            map.put("物料属性", inventory.getItemKey());
            map.put("点位", inventory.getPoint());
            map.put("点位号", inventory.getPointCode());
            map.put("容器", inventory.getStock());
            map.put("容器号", inventory.getStockCode());
            map.put("大容器", inventory.getBigStock());
            map.put("数量", inventory.getQuantity());
            map.put("分配数", inventory.getQueuedQty());
            map.put("重量", inventory.getWeight());
            map.put("体积", inventory.getVolume());
            map.put("描述", inventory.getDescription());
            map.put("是否锁定", inventory.getBeLock());
            map.put("是否不良品", inventory.getBeReject());
            map.put("状态", inventory.getStatus());
            map.put("存货日期", inventory.getStorageDate());
            map.put("仓库ID", inventory.getDept());
            map.put("创建人", inventory.getCreateBy());
            map.put("修改人", inventory.getUpdateBy());
            map.put("创建时间", inventory.getCreateTime());
            map.put("修改时间", inventory.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public Inventory toEntity(InventoryDto inventoryDto) {
        return inventoryMapper.toEntity(inventoryDto);
    }

    @Override
    public List<Inventory> queryInventory(long itemId, String areaName) {
        StringBuilder hql = new StringBuilder("FROM Inventory inv WHERE inv.itemKey.item.id = :itemId AND inv.quantity > 0 AND inv.queuedQty = 0");
        Map<String, Object> params = new HashMap<>();
        params.put("itemId", itemId);
        if (areaName.contains(",")) {
            List<String> areas = Arrays.asList(areaName.split(","));
            hql.append(" AND inv.point.area.name IN (:areaNames)");
            params.put("areaNames", areas);
        } else {
            hql.append(" AND inv.point.area.name = :areaName");
            params.put("areaName", areaName);
        }

        hql.append(" ORDER BY inv.createTime");
        Query query = entityManager.createQuery(hql.toString());
        params.forEach(query::setParameter);

        return query.getResultList();
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Inventory getInventory(ItemKey itemKey, Point point, Stock stock, Dept dept, String type) {
        //生成Inventory
        String hql = " from Inventory inv where 1=1 and inv.quantity>0 ";
        if (itemKey != null) {
            hql += " and inv.itemKey.id=" + itemKey.getId() + " ";
        }
        if (point != null) {
            hql += " and inv.point.id=" + point.getId() + " ";
        }
        if (stock != null) {
            hql += " and inv.stock.id=" + stock.getId() + " ";
        }

        if (dept != null) {
            hql += " and inv.dept.id=" + dept.getId() + " ";
        }
        Query query = entityManager.createQuery(hql);
        List<Inventory> inventoryList = query.getResultList();
        Inventory inventory = null;
        if (inventoryList.size() > 0) {
            inventory = inventoryList.get(0);
        } else {
            //创建Inventory
            if (type.equals(BizStatus.RECEIVING_UP)) {
                inventory = new Inventory();
                inventory.setItemKey(itemKey);
                inventory.setPoint(point);
                inventory.setPointCode(point.getCode());
                inventory.setStock(stock);
                inventory.setStockCode(stock.getCode());
                inventory.setDept(dept);
                this.create(inventory);
            }
        }
        return inventory;
    }

    @Override
    public List<Inventory> queryInventory(Stock stock) {
        String hql = " from Inventory inv where inv.stock.id=:stockId  and inv.quantity>0 ";
        Query query = entityManager.createQuery(hql);
        query.setParameter("stockId", stock.getId());
        return query.getResultList();
    }

    @Override
    public List<Inventory> getInvForPlan(String type, Long areaId, Long itemId, Long deptId) {
        String hql = " from Inventory inv where 1=1 and inv.queuedQty<=0 and inv.quantity>=0";
        if (type.equals(BizStatus.ZONE)) {
            hql += " and inv.point.area.id=" + areaId;
        } else if (type.equals(BizStatus.ITEM)) {
            hql += " and inv.itemKey.item.id=" + itemId;
        } else if (type.equals(BizStatus.WAREHOUSE)) {
            hql += " and 1=1";
        }
        Query query = entityManager.createQuery(hql);
        List<Inventory> list = query.getResultList();
        return list;
    }

    @Override
    public Inventory updateInventory(Task task, Stock stock) {
        Inventory inventory = getInventory(task.getItemKey(), task.getDstPoint(),
                task.getSrcStock(), task.getDept(), BizStatus.RECEIVING_UP);
        inventory.addQty(inventory, task.getPlanQty());
        update(inventory);
        return inventory;
    }

    public List<Object[]> queryItemStock() {
        String hql = "select inv.itemKey.item.code,max(inv.itemKey.item.name),count(inv.id) " +
                " from Inventory inv where 1=1 and inv.quantity>0 group by inv.itemKey.item.code order by inv.itemKey.item.code";
        Query query = entityManager.createQuery(hql);
        List<Object[]> list = query.getResultList();
        return list;
    }
}
