/*
 *  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.alibaba.fastjson.JSON;
import com.sun.jna.platform.win32.WinDef;
import com.youchain.basicdata.domain.Area;
import com.youchain.basicdata.domain.Item;
import com.youchain.basicdata.domain.Point;
import com.youchain.basicdata.domain.Stock;
import com.youchain.basicdata.service.PointService;
import com.youchain.businessdata.domain.CountDetail;
import com.youchain.businessdata.domain.Inventory;
import com.youchain.businessdata.domain.InventoryLog;
import com.youchain.businessdata.domain.ItemKey;
import com.youchain.businessdata.inputJson.buttenJson.InventoryButton;
import com.youchain.businessdata.inputJson.buttenJson.dataAll.InventoryYW;
import com.youchain.businessdata.returnJson.RInvQuery;
import com.youchain.businessdata.returnJson.RPTaskList;
import com.youchain.businessdata.service.InventoryLogService;
import com.youchain.businessdata.service.dto.*;
import com.youchain.exception.BadRequestException;
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 lombok.extern.slf4j.Slf4j;
import org.hibernate.SQLQuery;
import org.hibernate.transform.AliasToEntityMapResultTransformer;
import org.springframework.http.HttpStatus;
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.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;

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

    private final InventoryRepository inventoryRepository;
    private final InventoryMapper inventoryMapper;
    private final EntityManager entityManager;
    private final InventoryLogService invLogService;
    private final PointService pointService;

    @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 Exception {
        List<Map<String, Object>> list = ExcelDownUtils.CreateMap(all, "Inventory");
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public void downloadXb(List<InventoryDto> all, HttpServletResponse response) throws Exception {
        List<Map<String, Object>> list = ExcelDownUtils.CreateMap(all, "InvXb");
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public void downloadXt(List<InventoryDto> all, HttpServletResponse response) throws Exception {
        List<Map<String, Object>> list = ExcelDownUtils.CreateMap(all, "InvXt");
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public void downloadZz(List<InventoryDto> all, HttpServletResponse response) throws Exception {
        List<Map<String, Object>> list = ExcelDownUtils.CreateMap(all, "InvZz");
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public List<Inventory> queryInventoryAllocate(long itemId, long areaId, Long zzkwId) {
        String hql = " from Inventory inv where 1=1 " +
                " and inv.itemKey.item.id=" + itemId + " " +
                " and inv.area.id=" + areaId + " " +
                " and inv.quantity-inv.queuedQty>0 ";
        if (zzkwId != null) {
            hql += " and inv.zzkw.id=" + zzkwId;
            hql += "and inv.point.type in ('" + BaseStatus.HCKW + "','" + BaseStatus.ZZKW + "')";
        } else {
            hql += "and inv.point.type='" + BaseStatus.CH + "'";
        }
        hql += " order by inv.itemKey.propC1 asc ";
        Query query = entityManager.createQuery(hql);
        List<Inventory> inventoryList = query.getResultList();
        return inventoryList;
    }

    public Double getInvQty(long itemId, long areaId, Long zzkwId) {
        String hql = "select sum(inv.quantity-inv.queuedQty) from Inventory inv where 1=1 " +
                " and inv.itemKey.item.id=" + itemId + " " +
                " and inv.area.id=" + areaId + " " +
                " and inv.quantity>0 ";
        if (zzkwId != null) {
            hql += " and inv.zzkw.id=" + zzkwId;
            hql += "and inv.point.type in ('" + BaseStatus.HCKW + "','" + BaseStatus.ZZKW + "')";
        } else {
            hql += "and inv.point.type='" + BaseStatus.CH + "'";
        }
        Query query = entityManager.createQuery(hql);
        List inventoryList = query.getResultList();
        if (inventoryList.size() > 0) {
            Object obj = inventoryList.get(0);
            if (obj == null) {
                return 0d;
            } else {
                return (Double) obj;
            }
        }
        return 0d;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Inventory getInventory(ItemKey itemKey, Area area, Point point, Point zzkw, Dept dept, String type) {
        //生成Inventory
        String hql = " from Inventory inv where 1=1 ";
        if (type.equals(BizStatus.SL_ALL) || type.equals(BizStatus.ZZKW_TL)) {
            if (zzkw == null) {
                throw new BadRequestException(HttpStatus.NOT_FOUND, "制造库位必填");
            }
            if (!area.getBexb()) {
                throw new BadRequestException(HttpStatus.NOT_FOUND, "接收库区必须为线边仓");
            }
//            if(area.getPoint()==null){
            if (area.getPointId() == null) {
                throw new BadRequestException(HttpStatus.NOT_FOUND, "接收库区线边库位必填");
            }
        }
        if (type.equals(BizStatus.SL_ALL)) {
            //取库区默认
            hql += " and inv.point.id=" + area.getPointId() + " ";
        } else {
            if (point != null) {
                hql += " and inv.point.id=" + point.getId() + " ";
            }
        }
        if (itemKey != null) {
            hql += " and inv.itemKey.id=" + itemKey.getId() + " ";
        }
        hql += " and inv.area.id=" + area.getId() + " ";
        if (dept != null) {
            hql += " and inv.dept.id=" + dept.getId() + " ";
        }
        if (area.getBexb()) {
            if (zzkw != null) {
                hql += " and inv.zzkw.id=" + zzkw.getId() + " ";
            } else {
                throw new BadRequestException(HttpStatus.NOT_FOUND, "线边仓制造库位必填");
            }
        }

        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.ZZKW_TL) || type.equals(BizStatus.RECEIVING_UP) || type.equals(BizStatus.MOVE) || type.equals(BizStatus.PICK_DOWN) || type.equals(BizStatus.PICK_CANCEL) || type.equals(BizStatus.SL_ALL) || type.equals(BizStatus.MOVE)) {
                inventory = new Inventory();
                inventory.setItemKey(itemKey);
                inventory.setPoint(point);
                inventory.setPointCode(point.getCode());
                if (zzkw == null) {
                    zzkw = pointService.getPoint("ZZKW", null, null, null);
                }
                inventory.setZzkw(zzkw);
//                inventory.setStock(stock);
//                inventory.setStockCode(stock.getCode());
                inventory.setDept(dept);
                inventory.setArea(area);
                create(inventory);
            }
        }
        return inventory;
    }


    @Override
    public List<Inventory> getXbHyInv(Item item, Area area, String gw, Point zzkw, String type) {
        //生成Inventory
        String hql = " from Inventory inv where 1=1 and inv.point.type not in ('" + BaseStatus.BHZC + "','" + BaseStatus.SHZC + "')";
        if (item != null) {
            hql += " and inv.itemKey.item.id=" + item.getId() + " ";
        }
        hql += " and inv.area.workingStation='" + gw + "'";
        if (zzkw != null) {
            hql += " and inv.zzkw.id=" + zzkw.getId();
        }
        if (type.equals("耗用")) {//目前只能从暂存库位耗用
            hql += " and inv.point.id=" + area.getPointId();
        }
        hql += " order by inv.itemKey.propC1 asc";
        Query query = entityManager.createQuery(hql);
        List<Inventory> inventoryList = query.getResultList();
        return inventoryList;
    }

    @Override
    public List<Inventory> getInventoryXbTl(Item item, Area area, Point point, Point zzkw) {
        //生成Inventory
        String hql = " from Inventory inv where 1=1 and inv.point.id =" + point.getId();
        hql += " and inv.itemKey.item.id=" + item.getId() + " ";
        hql += " and inv.area.id=" + area.getId();
        hql += " and inv.zzkw.id=" + zzkw.getId();
        Query query = entityManager.createQuery(hql);
        List<Inventory> inventoryList = query.getResultList();
        return inventoryList;
    }

    @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;
    }

    public List<Inventory> queryInventory(Long areaId, Long pointId, Long itemKeyId) {
        String hql = " from Inventory inv where inv.area.id=" + areaId + "  and inv.point.id=" + pointId + " and inv.itemKey.id=" + itemKeyId;
        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
    public void kuneMovePosition(InventoryButton inventoryButton) {
        //操作类型=移位，增加/减少=减少 ，
        //原点位=之前记录的库位，目标库位=选择的库位  库区、品番、暂存库位、制造库位都取inv上的。 原数量取原纪录，目标数量取移出后的数量，   发生数量=输入的移位数量
        //操作类型=库存调整，增加/减少=根据实际数量判断，大于原数量为增加，小于原数量为减少，其他的类似上面数据
        //移位时，加入目标库位之前没有这个记录，则自动生成
        //库存唯一键：area，point，itemKey，zzkw
        //位移所需要的数据
        InventoryYW inventoryYW = inventoryButton.getInventoryYW();
        //原数据
        Inventory inventoryOld = inventoryYW.getInventory();
        // 位移数量
        double rmNumber = inventoryYW.getRmNumber();
        //判断 库存-要移动的数量
        double rmNum = inventoryOld.getQuantity() - rmNumber;
        if (rmNum > 0) {//移除数量小于库存数量
            //生成库存或生成记录
            Inventory inventory = this.getInventory(inventoryOld.getItemKey(), inventoryOld.getArea(), inventoryYW.getDstPoint(), inventoryOld.getZzkw(), inventoryOld.getDept(), BizStatus.MOVE);
            //生成移除的日志
            invLogService.storeInventoryLog(BizStatus.MOVE, BizStatus.REDUCE, null, inventoryOld.getArea(), inventoryOld.getItemKey(), inventoryOld.getPoint(), inventoryYW.getDstPoint(), inventoryOld.getStock(), inventoryOld.getStock(), inventoryOld.getQuantity(), rmNumber,
                    null, null, BizStatus.MOVE, inventoryOld.getId(), inventoryOld.getId(), inventoryOld.getDescription());
            //生成目标点位的日志
            invLogService.storeInventoryLog(BizStatus.MOVE, BizStatus.ADD, null, inventory.getArea(), inventory.getItemKey(), inventory.getPoint(), inventoryYW.getDstPoint(), inventoryOld.getStock(), inventory.getStock(), inventory.getQuantity(), rmNumber,
                    null, null, BizStatus.MOVE, inventoryOld.getId(), inventoryOld.getId(), inventoryOld.getDescription());
            //减库存
            inventoryOld.setQuantity(rmNum);
            this.update(inventoryOld);
            //加库存
            inventory.setQuantity(inventory.getQuantity() + rmNumber);
            this.update(inventory);
        } else if (rmNum < 0) {//移除数量大于库存数量
            throw new BadRequestException(HttpStatus.NOT_FOUND, "移除数量大于库存数量");
        } else {//移除数量等于库存数量
            //生成库存或生成记录
            Inventory inventory = this.getInventory(inventoryOld.getItemKey(), inventoryOld.getArea(), inventoryYW.getDstPoint(), inventoryOld.getZzkw(), inventoryOld.getDept(), BizStatus.MOVE);
            //生成移除的日志
            invLogService.storeInventoryLog(BizStatus.MOVE, BizStatus.REDUCE, null, inventoryOld.getArea(), inventoryOld.getItemKey(), inventoryOld.getPoint(), inventoryYW.getDstPoint(), inventoryOld.getStock(), inventoryOld.getStock(), inventoryOld.getQuantity(), rmNumber,
                    null, null, BizStatus.MOVE, inventoryOld.getId(), inventoryOld.getId(), inventoryOld.getDescription());
            //生成目标点位的日志
            invLogService.storeInventoryLog(BizStatus.MOVE, BizStatus.ADD, null, inventory.getArea(), inventory.getItemKey(), inventory.getPoint(), inventoryYW.getDstPoint(), inventoryOld.getStock(), inventory.getStock(), inventory.getQuantity(), rmNumber,
                    null, null, BizStatus.MOVE, inventoryOld.getId(), inventoryOld.getId(), inventoryOld.getDescription());
            inventoryRepository.delete(inventoryOld);
            //加库存
            inventory.setQuantity(inventory.getQuantity() + rmNumber);
            this.update(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;
    }

    public List<RInvQuery> queryInvApp(String code) {
        String sql = "SELECT inv.id invId,it.`code` itemCode,it.name itemName,inv.quantity qty,ik.prop_d1 propD1,p.code pointCode FROM `data_inventory` inv \n" +
                "left join data_item_key ik on ik.id=inv.item_key_id\n" +
                "left join base_item it on it.id=ik.item_id\n" +
                "left join base_point p on p.id=inv.point_id \n" +
                "left join base_area area on area.id=inv.area_id\n" +
                "where 1=1 and area.besh=1 and p.code!='BH_ZC' and inv.quantity!=0 and it.code='" + code + "'\n" +
                "order by it.code";
        List ts = entityManager.createNativeQuery(sql)
                .unwrap(SQLQuery.class)
                .setResultTransformer(
                        AliasToEntityMapResultTransformer.INSTANCE
                )
                .list();
        List<RInvQuery> list = JSON.parseArray(JSON.toJSONString(ts), RInvQuery.class);
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Inventory getInventory(ItemKey itemKey, Point point, Stock stock, Dept dept, String type,Area area) {
        List<Inventory> inventoryList = inventoryRepository.findByInventory(itemKey.getId(), point==null?null:point.getId(), stock.getId(), dept.getId());
        Inventory inventory = null;
        if (inventoryList.size() > 0) {
            inventory = inventoryList.get(0);
        } else {
            //创建Inventory
            inventory = new Inventory();
            inventory.setItemKey(itemKey);
            if (point != null) {
                inventory.setPoint(point);
                inventory.setPointCode(point.getCode());
            }
            inventory.setStock(stock);
            inventory.setStockCode(stock.getCode());
            inventory.setDept(dept);
            inventory.setArea(area);
            inventoryRepository.save(inventory);
        }
        return inventory;
    }

    @Override
    public List<Inventory> queryInventoryForShangJia(String status) {
        return inventoryRepository.queryInventoryForShangJia(status);
    }
}
