/*
*  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.sun.jna.platform.win32.WinDef;
import com.youchain.basicdata.domain.Item;
import com.youchain.basicdata.domain.Point;
import com.youchain.basicdata.domain.Stock;
import com.youchain.businessdata.domain.Inventory;
import com.youchain.businessdata.domain.InventoryLog;
import com.youchain.businessdata.domain.ItemKey;
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.List;
import java.util.Map;
import java.io.IOException;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

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

    private final InventoryRepository inventoryRepository;
    private final InventoryMapper inventoryMapper;

    @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 List<Inventory> queryInventory(long itemId) {
        return inventoryRepository.queryInventory(itemId);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Inventory getInventory(ItemKey itemKey, Point point, Stock stock, Dept dept,String type) {
        //生成Inventory
        InvQueryCriteria invq=new InvQueryCriteria();
        invq.setItemKeyId(itemKey.getId());
        invq.setPointId(point.getId());
        invq.setStockId(stock.getId());
        invq.setDeptId(dept.getId());
        List<InventoryDto> invds=queryAll(invq);
        Inventory inv=null;
        if(invds.size()>0){
            inv= inventoryMapper.toEntity(invds.get(0));
        }else{
            //创建Inventory
            if(type.equals(BizStatus.RECEIVING_UP)) {
                inv = new Inventory();
                inv.setItemKey(itemKey);
                inv.setPoint(point);
                inv.setPointCode(point.getCode());
                inv.setStock(stock);
                inv.setStockCode(stock.getCode());
                inv.setDept(dept);
                create(inv);
            }
        }
        return inv;
    }
}