/*
*  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.InventoryBak;
import com.youchain.utils.*;
import lombok.RequiredArgsConstructor;
import com.youchain.businessdata.repository.InventoryBakRepository;
import com.youchain.businessdata.service.InventoryBakService;
import com.youchain.businessdata.service.dto.InventoryBakDto;
import com.youchain.businessdata.service.dto.InventoryBakQueryCriteria;
import com.youchain.businessdata.service.mapstruct.InventoryBakMapper;
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.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author houjianlan
* @date 2024-04-03
**/
@Service
@RequiredArgsConstructor
public class InventoryBakServiceImpl implements InventoryBakService {

    private final InventoryBakRepository inventoryBakRepository;
    private final InventoryBakMapper inventoryBakMapper;
    private final EntityManager entityManager;

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

    @Override
    public List<InventoryBakDto> queryAll(InventoryBakQueryCriteria criteria){
        return inventoryBakMapper.toDto(inventoryBakRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public InventoryBakDto findById(Long id) {
        InventoryBak inventoryBak = inventoryBakRepository.findById(id).orElseGet(InventoryBak::new);
        ValidationUtil.isNull(inventoryBak.getId(),"InventoryBak","id",id);
        return inventoryBakMapper.toDto(inventoryBak);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public InventoryBakDto create(InventoryBak resources) {
        return inventoryBakMapper.toDto(inventoryBakRepository.save(resources));
    }

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

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

    @Override
    public void download(List<InventoryBakDto> all, HttpServletResponse response) throws Exception {
        List<Map<String, Object>>  list= ExcelDownUtils.CreateMap(all,"InventoryBak");
        FileUtil.downloadExcel(list, response);
    }
    @Override
    public void insertBatch(Long detailId,Long areaId) {
        String sql="INSERT into data_inventory_bak(detail_id,bill_code,item_key_id,point_id,quantity,queued_qty,be_lock,be_reject,`status`,dept_id,area_id,zzkw,bf_date)   \n" +
                "select "+detailId+",bill_code,item_key_id,point_id,quantity,queued_qty,be_lock,be_reject,status,dept_id,area_id,zzkw,SYSDATE() from data_inventory where area_id="+areaId;
        Query query=entityManager.createNativeQuery(sql);
        query.executeUpdate();
    }

    @Override
    public void insertBhBatch(Long detailId,Long areaId) {
        String sql="INSERT into data_inventory_bak(detail_id,pick_detail_id,bill_code,item_id,point_id,quantity,queued_qty,be_lock,be_reject,`status`,dept_id,area_id,zzkw,bf_date)   \n" +
                "select "+detailId+",pd.id, pt.code,pd.item_id,pd.point_id,pd.allocated_qty,0,0,0,pt.`status`,pt.dept_id,pd.sh_area_id,pd.point_id,SYSDATE()  from data_pick_detail pd \n" +
                "left join data_pick_ticket pt on pt.id=pd.pick_ticket_id\n" +
                "where pt.`status` in ('PICKUP','PICK_ALL','ALLOCATE') and pd.point_id is not null and pd.allocated_qty>0 and pd.sh_area_id is not null and pd.sh_area_id="+areaId;
        Query query=entityManager.createNativeQuery(sql);
        query.executeUpdate();
    }

    public Double getXbQty(long itemId, long areaId,Long zzkwId,Long detailId) {
        String hql = "select sum(inv.quantity-inv.queuedQty) from InventoryBak inv where 1=1 " +
                " and inv.itemKey.item.id=" + itemId +
                " and inv.area.id=" + areaId +
                " and inv.detailId="+detailId+
                " and inv.quantity!=0 ";
        if(zzkwId!=null) {
            hql += " and inv.zzkw.id=" + zzkwId;
        }
        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
    public void insertInvHis() {
        String sql="INSERT INTO data_inventory_his (id,item_key_id,point_id,point_code,stock_code, quantity,queued_qty,description,dept_id,create_by,update_by,create_time,update_time,area_id,zzkw,back_time) \n" +
                "select id,item_key_id,point_id,point_code,stock_code, quantity,queued_qty,description,dept_id,create_by,update_by,create_time,update_time,area_id,zzkw,SYSDATE() from data_inventory inv ";
        Query query=entityManager.createNativeQuery(sql);
        query.executeUpdate();
    }
}