/*
*  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 cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSON;
import com.youchain.basicdata.domain.Area;
import com.youchain.basicdata.domain.Point;
import com.youchain.basicdata.domain.Stock;
import com.youchain.businessdata.domain.InventoryLog;
import com.youchain.businessdata.domain.ItemKey;
import com.youchain.utils.*;
import lombok.RequiredArgsConstructor;
import com.youchain.businessdata.repository.InventoryLogRepository;
import com.youchain.businessdata.service.InventoryLogService;
import com.youchain.businessdata.service.dto.InventoryLogDto;
import com.youchain.businessdata.service.dto.InventoryLogQueryCriteria;
import com.youchain.businessdata.service.mapstruct.InventoryLogMapper;
import lombok.extern.slf4j.Slf4j;
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.sql.Date;
import java.sql.Timestamp;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author houjianlan
* @date 2023-08-31
**/
@Service
@RequiredArgsConstructor
@Slf4j
public class InventoryLogServiceImpl implements InventoryLogService {

    private final InventoryLogRepository inventoryLogRepository;
    private final InventoryLogMapper inventoryLogMapper;

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

    @Override
    public List<InventoryLogDto> queryAll(InventoryLogQueryCriteria criteria){
        List<InventoryLog> list=inventoryLogRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder));
        return inventoryLogMapper.toDto(inventoryLogRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public InventoryLogDto findById(Long id) {
        InventoryLog inventoryLog = inventoryLogRepository.findById(id).orElseGet(InventoryLog::new);
        ValidationUtil.isNull(inventoryLog.getId(),"InventoryLog","id",id);
        return inventoryLogMapper.toDto(inventoryLog);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public InventoryLogDto create(InventoryLog resources) {
        return inventoryLogMapper.toDto(inventoryLogRepository.save(resources));
    }

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

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

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

    /**
     * @Description
     * @Author Houjianlan
     * @Date
     */
    @Override
    public InventoryLog storeInventoryLog(String logType, int incDec, String relatedBill, Area area,ItemKey itemKey, Point srcPoint, Point dstPoint, Stock srcStock, Stock dstStock,
                                          Double srcQty, Double occurQty, String stockCode,String xpp,String refObj, Long refObjId, Long invId, String description) {
        InventoryLog log =new InventoryLog();
        log.setLogType(logType);
        log.setIncDec(incDec);
        log.setRelatedBill(relatedBill);
        log.setItemKey(itemKey);
        if (area != null){
            log.setArea(area);
        }
        if(srcPoint!=null) {
            log.setSrcPointCode(srcPoint.getCode());
            log.setSrcPoint(srcPoint);
        }
        if(dstPoint!=null){
            log.setDstPoint(dstPoint);
            log.setDstPointCode(dstPoint.getCode());
        }
        if(srcStock!=null){
            log.setSrcStock(srcStock);
        }
        if(dstStock!=null){
            log.setDstStock(dstStock);
        }
        log.setSrcStockCode(xpp);
        log.setDstStockCode(stockCode);
        log.setSrcQty(srcQty);
        log.setOccurQuantity(occurQty);
        if(incDec== BizStatus.ADD){
            log.setDstQty(srcQty+occurQty);
        }else  if(incDec== BizStatus.INVARIANT){
            log.setDstQty(srcQty);
        }else  if(incDec== BizStatus.REDUCE){
            log.setDstQty(srcQty-occurQty);
        }
        log.setOccurTime(new Timestamp(System.currentTimeMillis()));
        log.setRefObj(refObj);
        log.setRefObjId(refObjId);
        log.setInvId(invId);
        log.setDescription(description);
        create(log);
        return log;
    }

    public InventoryLog storeInventoryLog(String logType, int incDec, String relatedBill, Area area,ItemKey itemKey, Point srcPoint, Point dstPoint,Point zzkw,
                                          Double srcQty, Double occurQty,String xpp,String refObj, Long refObjId, Long invId, String description) {
        InventoryLog log =new InventoryLog();
        log.setLogType(logType);
        log.setIncDec(incDec);
        log.setRelatedBill(relatedBill);
        log.setItemKey(itemKey);
        if (area != null){
            log.setArea(area);
        }
        if(srcPoint!=null) {
            log.setSrcPointCode(srcPoint.getCode());
            log.setSrcPoint(srcPoint);
        }
        if(dstPoint!=null){
            log.setDstPoint(dstPoint);
            log.setDstPointCode(dstPoint.getCode());
        }
        log.setZzkw(zzkw);
//        if(srcStock!=null){
//            log.setSrcStock(srcStock);
//        }
//        if(dstStock!=null){
//            log.setDstStock(dstStock);
//        }
        log.setSrcStockCode(xpp);
        log.setSrcQty(srcQty);
        log.setOccurQuantity(occurQty);
        if(incDec== BizStatus.ADD){
            log.setDstQty(srcQty+occurQty);
        }else  if(incDec== BizStatus.INVARIANT){
            log.setDstQty(srcQty);
        }else  if(incDec== BizStatus.REDUCE){
            log.setDstQty(srcQty-occurQty);
        }
        log.setOccurTime(new Timestamp(System.currentTimeMillis()));
        log.setRefObj(refObj);
        log.setRefObjId(refObjId);
        log.setInvId(invId);
        log.setDescription(description);
        create(log);
        return log;
    }
}