/*
 *  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.basicdata.repository.PointRepository;
import com.youchain.businessdata.domain.*;
import com.youchain.businessdata.repository.*;
import com.youchain.businessdata.service.InventoryLogService;
import com.youchain.businessdata.service.dto.*;
import com.youchain.modules.system.domain.Dept;
import com.youchain.utils.*;
import lombok.RequiredArgsConstructor;
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.Entity;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

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

    private final InventoryRepository inventoryRepository;
    private final InventoryLogService inventoryLogService;
    private final AsnRepository asnRepository;
    private final AsnDetailRepository asnDetailRepository;
    private final InventoryMapper inventoryMapper;
    private final PickDetailRepository pickDetailRepository;
    private final EntityManager entityManager;
    private final ItemKeyRepository itemKeyRepository;
    private final PickRepository pickRepository;
    private final TaskRepository taskRepository;
    private final PointRepository pointRepository;

    @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) {
            Inventory inventory=inventoryRepository.getById(id);
            InventoryDto inventoryDto= inventoryMapper.toDto(inventory);
            double quantity=inventory.getQuantity();
            ItemKey itemKey=inventory.getItemKey();
            itemKey.setEnabled(false);
            Point point=inventory.getPoint();
            if (point!=null) {
                point.setStorageType(null);
                point.setStatus(BaseStatus.FREE);
                pointRepository.save(point);
            }
            itemKeyRepository.save(itemKey);
            inventoryRepository.deleteById(id);
            // 添加日志
            inventoryLogService.storeInventoryLog(BizStatus.DEL,BizStatus.REDUCE,itemKey.getPropC3(),itemKey,point,null,null,null,quantity,quantity, itemKey.getPropC6(),null,inventoryDto.getId(),inventoryDto.getDescription());
            // 反馈修改库存
            UrlApi.invBackSap(inventoryDto.getOwner(), itemKey.getItem().getCode(),0+""
                    , quantity+"",inventoryDto.getZtBid(),inventory.getProdMtrl(),inventoryDto.getDescription());
        }
    }

    @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
        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);
                create(inventory);
            }
        }
        return inventory;
    }

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

    @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
    @Transactional
    public Inventory asnAddInventoryList(Task task) {
        Inventory inventory = getInventory(task.getPlanQty(), task.getItemKey().getId()
                , task.getDstPoint().getId(), BizStatus.RECEIVING_UP);
            /*List<Inventory> inventoryList = inventoryRepository.findByItemAndPoint(task.getItemKey().getItem().getId(),task.getDstPoint().getId());
            if (inventoryList.size()>0){
                inventory = inventoryList.get(0);
            }
            if (inventory==null) {
                inventory = getInventory(task.getPlanQty(), task.getItemKey().getId()
                        , task.getDstPoint().getId(), BizStatus.RECEIVING_UP);
            }else {
                inventory.setQuantity(inventory.getQuantity()+task.getPlanQty());
            }*/
        task.setTaskStatus(BizStatus.RECEIVED);
        task.setMoveQty(task.getPlanQty());
        task.setInventory(inventory);
        taskRepository.save(task);
        Asn asn=asnRepository.findByRelatedBill2(task.getBillCode());
        AsnDetail asnDetail=task.getAsnDetail();
        asnDetail.setPutQty(asnDetail.getPutQty()+task.getMoveQty());
        asnDetailRepository.save(asnDetail);
        if (asn!=null){
            // 添加 登记单号 货主
            inventory.setBillCode(task.getBillCode());
            inventory.setOwner(asn.getStructure());
            inventoryRepository.save(inventory);
        }
        UrlApi.asnBackSap(inventory.getOwner(),
                inventory.getBillCode(),
                task.getAsnDetail().getLineNo()+"",
                task.getItemKey().getItem().getCode(),
                task.getAsnDetail().getOrderQty()+"",
                task.getAsnDetail().getPutQty()+"");
        return inventory;
    }
    @Override
    @Transactional
    public Inventory getInventory(Double qty, Long ikID, Long pointId, String logType) {
        Inventory inventory =new Inventory();
        inventory.setQuantity(qty);
        ItemKey itemKey=itemKeyRepository.getById(ikID);
        inventory.setItemKey(itemKey);
        if (pointId!=null) {
            Point point=pointRepository.getById(pointId);
            inventory.setPoint(point);
        }
        inventory.setDept(UserUtils.getDept());
        inventory.setStatus(BizStatus.OPEN);
        inventoryRepository.save(inventory);
        //添加库存日志
        inventoryLogService.storeInventoryLog(logType,BizStatus.ADD,itemKey.getPropC3(),itemKey,null,inventory.getPoint(),null,null,0d,inventory.getQuantity(), itemKey.getPropC6(),null,inventory.getId(),inventory.getDescription());

        return inventory;
    }

    @Override
    public void pickDelInventory(List<Task> taskList) {
        Point pointStart=null;
        Point pointEnd=null;
        //删除库存
        for (int i = 0; i < taskList.size(); i++) {
            /** 书安心Task表*/
            Task task=taskList.get(i);
            if (pointStart==null){
                pointStart = task.getSrcPoint();
            }
            if (pointEnd==null){
                pointEnd = task.getDstPoint();
            }
            task.setTaskStatus(BizStatus.PICK_ALL);
            task.setMoveQty(task.getPlanQty());
            taskRepository.save(task);
            /** 刷新出库单明细表*/
            PickDetail pickDetail=task.getPickDetail();
            pickDetail.setPickedQty(pickDetail.getPickedQty()+task.getMoveQty());
            if (pickDetail.getAllocatedQty()<=pickDetail.getPickedQty()){
                pickDetail.setStatus(BizStatus.PICK_ALL);
            }
            pickDetailRepository.save(pickDetail);
            /** 更新出库单状态 -*/
            List<PickDetail> pickDetailList=pickDetailRepository.findByQtyAllGtPick(pickDetail.getPick().getId());
            if (pickDetailList.size()==0){
                Pick pick=pickDetail.getPick();
                pick.setStatus(BizStatus.PICK_ALL);
                pickRepository.save(pick);
            }
            /** 添加库存日志，删除库存*/
            Inventory inventory=task.getInventory();
            if (inventory==null){
                continue;
            }
            inventoryLogService.storeInventoryLog(BizStatus.PICK_DOWN,BizStatus.REDUCE,inventory.getItemKey().getPropC3(),inventory.getItemKey(),task.getSrcPoint(),task.getDstPoint(),null,null,inventory.getQuantity(),task.getMoveQty(), task.getItemKey().getPropC6(),null,inventory.getId(),"");
            inventoryRepository.delete(inventory);
            // 失效ItemKey
            ItemKey itemKey=inventory.getItemKey();
            itemKey.setEnabled(false);
            itemKeyRepository.save(itemKey);
        }
        // 查询原库位是否有其他库存，如果有移出到线边
        if (pointStart!=null){
            List<Inventory> inventoryList=inventoryRepository.findByPoint(pointStart.getId());
            for (int i = 0; i < inventoryList.size(); i++) {
                Inventory inventory=inventoryList.get(i);
                inventory.setPoint(pointEnd);
                inventoryRepository.save(inventory);
                inventoryLogService.storeInventoryLog(BizStatus.MOVE,BizStatus.REDUCE,inventory.getItemKey().getPropC3(),inventory.getItemKey(),pointStart,pointEnd,null,null,inventory.getQuantity(),0d, inventory.getItemKey().getPropC6(),null,inventory.getId(),"");
            }
        }
    }

    @Override
    public Inventory editInvPoint(Long invId, Point point) {
        Inventory inventory=inventoryRepository.getById(invId);
        if (inventory!=null&&inventory.getQueuedQty()<1){
            inventory.setPoint(point);
            inventoryRepository.save(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;
    }
}