package com.neusoft.smart.pos.inventory.service;

import com.neusoft.smart.pos.dto.inventory.request.PostInventoryStoreBatchRequest;
import com.neusoft.smart.pos.dto.inventory.request.PutInventoryStoreBatchRequest;
import com.neusoft.smart.pos.dto.inventory.response.PostInventoryStoreBatchResponse;
import com.neusoft.smart.pos.framework.exception.BusinessCommonException;
import com.neusoft.smart.pos.inventory.constants.InventoryConstant;
import com.neusoft.smart.pos.inventory.constants.InventoryErrorCode;
import com.neusoft.smart.pos.dto.inventory.response.InventoryGoodsResponse;
import com.neusoft.smart.pos.inventory.persistent.domain.InventoryStoreBatch;
import com.neusoft.smart.pos.inventory.persistent.domain.InventoryStoreInout;
import com.neusoft.smart.pos.inventory.repository.InventoryStoreBatchRepository;
import com.neusoft.smart.pos.inventory.repository.InventoryStoreInoutRepository;
import com.neusoft.smart.pos.utils.RequestHeaderUtil;
import lombok.val;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
public class InventoryStoreBatchService {
    
    @Resource
    public InventoryStoreBatchRepository inventoryBatchRepository;
    
    @Resource
    public InventoryStoreInoutRepository inventoryInoutRepository;
    
    @Resource
    GoodsDefaultService goodsDefaultService;
    
    public PostInventoryStoreBatchResponse increaseInventory(PostInventoryStoreBatchRequest inventoryStoreBatchRequest, int actionDire, String actionType) {
        String operator;
        if (StringUtils.isEmpty(inventoryStoreBatchRequest.getOperator())) operator = RequestHeaderUtil.getUsername();
        else operator = inventoryStoreBatchRequest.getOperator();
        inventoryStoreBatchRequest.setOperator(operator);
        inventoryStoreBatchRequest.setActionDire(actionDire);
        inventoryStoreBatchRequest.setActionType(actionType);
        goodsDefaultService.warehouseIn(inventoryStoreBatchRequest);
        PostInventoryStoreBatchResponse storeBatchResponse = new PostInventoryStoreBatchResponse();
        BeanUtils.copyProperties(inventoryStoreBatchRequest, storeBatchResponse);
        return storeBatchResponse;
    }
    
    public PostInventoryStoreBatchResponse reduceInventory(PutInventoryStoreBatchRequest inventoryStoreBatchRequest, int actionDire, String actionType) {
        if (inventoryStoreBatchRequest.getStorageNum().compareTo(new BigDecimal(0)) <= 0) {
            throw new BusinessCommonException(InventoryErrorCode.NUM_NO_ZERO);
        }
        String operator = "";
        if (StringUtils.isEmpty(inventoryStoreBatchRequest.getOperator())) operator = RequestHeaderUtil.getUsername();
        else operator = inventoryStoreBatchRequest.getOperator();
        
        InventoryStoreBatch storeBatch = new InventoryStoreBatch();
        BeanUtils.copyProperties(inventoryStoreBatchRequest, storeBatch);
        //查询商品当前库存剩余数量
        storeBatch.setStatus(InventoryConstant.USABLE_BATCH);
        BigDecimal totalNum = inventoryBatchRepository.sumStockNumByGoodsId(storeBatch);
        List<InventoryStoreBatch> batchs = new ArrayList<InventoryStoreBatch>();
        if (totalNum == null) {
            totalNum = new BigDecimal(0);
            batchs = inventoryBatchRepository.selectMaxIdZeroBatchByGoodsId(storeBatch);
        } else {
            //查询商品的所有批次信息
            batchs = inventoryBatchRepository.selectAllBatchByGoodsId(storeBatch);
        }
        if (batchs.size() <= 0) {
            throw new BusinessCommonException(InventoryErrorCode.NO_INVENTORY_RECORD);
        }
        Iterator<InventoryStoreBatch> it = batchs.iterator();
//        BigDecimal deduction_num = new BigDecimal(storeBatch.getStorageNum() / (storeBatch.getScale() == 0 ? 1 : Math.pow(10, storeBatch.getScale())));
        BigDecimal totalPrice = new BigDecimal(0);
        //FIXME 需要重新考虑库存，有可能不在这个地方处理
//        while (it.hasNext()) {
//            InventoryStoreBatch batch = it.next();
//            if (batch.getStorageNum().compareTo(deduction_num) > 0) {//当前批次数量够减
//                totalPrice = totalPrice.add(batch.getInPrice().multiply(deduction_num));
//                storeBatch.setStorageNum(batch.getStorageNum().subtract(deduction_num));
//                storeBatch.setStatus(InventoryConstant.USABLE_BATCH);
//                storeBatch.setId(batch.getId());
//                storeBatch.setUpdatedBy(operator);
//                storeBatch.setUpdatedTime(new Date());
//                inventoryBatchRepository.updateSelective(storeBatch);
//                break;
//            } else if (batch.getStorageNum().compareTo(deduction_num) == 0) {//当前批次数量与扣减数量一致
//                totalPrice = totalPrice.add(batch.getInPrice().multiply(deduction_num));
//                storeBatch.setStorageNum(new BigDecimal(0));
//                storeBatch.setStatus(InventoryConstant.ZERO_BATCH);
//                storeBatch.setId(batch.getId());
//                storeBatch.setUpdatedBy(operator);
//                storeBatch.setUpdatedTime(new Date());
//                inventoryBatchRepository.updateSelective(storeBatch);
//                break;
//            } else {
//                if (it.hasNext()) {
//                    //当前批次不够减，需要继续扣减下一批次
//                    totalPrice = totalPrice.add(batch.getInPrice().multiply(batch.getStorageNum()));
//                    deduction_num = deduction_num.subtract(batch.getStorageNum());
//                    storeBatch.setStorageNum(new BigDecimal(0));
//                    storeBatch.setStatus(InventoryConstant.ZERO_BATCH);
//                } else {
//                    //库存不够减，出现负库存的情况
//                    totalPrice = totalPrice.add(batch.getInPrice().multiply(deduction_num));
//                    deduction_num = batch.getStorageNum().subtract(deduction_num);
//                    storeBatch.setStorageNum(deduction_num);
//                    storeBatch.setStatus(InventoryConstant.USABLE_BATCH);
//                }
//                storeBatch.setId(batch.getId());
//                storeBatch.setUpdatedBy(operator);
//                storeBatch.setUpdatedTime(new Date());
//                inventoryBatchRepository.updateSelective(storeBatch);
//            }
//        }
        //插入库存变动流水
        InventoryStoreInout inout = new InventoryStoreInout();
        BeanUtils.copyProperties(inventoryStoreBatchRequest, inout);
        //inout.setGoodsId(inventoryStoreBatchRequest.getGoodsId());
        //inout.setShopId(shopId);
        inout.setResidueNum(totalNum);
        inout.setVarNum(inventoryStoreBatchRequest.getStorageNum());
        inout.setInPrice(totalPrice.divide(inventoryStoreBatchRequest.getStorageNum(), 2));
        //inout.setSalePrice(inventoryStoreBatchRequest.getSalePrice());
        inout.setActionDire(actionDire);
        inout.setActionType(actionType);
        inout.setCreatedBy(operator);
        inventoryInoutRepository.insertSelective(inout);
        
        PostInventoryStoreBatchResponse storeBatchResponse = new PostInventoryStoreBatchResponse();
        BeanUtils.copyProperties(inventoryStoreBatchRequest, storeBatchResponse);
        return storeBatchResponse;
    }
    
    public List<InventoryStoreBatch> selectMaxIdBatchByGoodsId(InventoryStoreBatch inventoryStoreBatch) {
        return inventoryBatchRepository.selectMaxIdBatchByGoodsId(inventoryStoreBatch);
    }
    
    public PostInventoryStoreBatchRequest bindGoodsInfoForRequest(PostInventoryStoreBatchRequest request) {
        InventoryStoreBatch storeBatch = new InventoryStoreBatch();
        BeanUtils.copyProperties(request, storeBatch);
        val maxBatch = this.selectMaxIdBatchByGoodsId(storeBatch);
        if (maxBatch.size() > 0) {
            //FIXME 下边注释掉的
//            request.setUnit(maxBatch.get(0).getUnit());
            if (StringUtils.isEmpty(request.getSupplier())) request.setSupplier(maxBatch.get(0).getSupplier());
            if (StringUtils.isEmpty(request.getMadeDate())) request.setMadeDate(maxBatch.get(0).getMadeDate());
            if (StringUtils.isEmpty(request.getQualityDate())) request.setQualityDate(maxBatch.get(0).getQualityDate());
            if (!StringUtils.isEmpty(request.getInPrice())) request.setPulPrice(request.getInPrice());
        }
        request.setInPrice(new BigDecimal(0));
        return request;
    }
    
    public PostInventoryStoreBatchRequest bindPriceForRequest(PostInventoryStoreBatchRequest request) {
        InventoryStoreInout inout = new InventoryStoreInout();
        BeanUtils.copyProperties(request, inout);
        InventoryStoreBatch storeBatch = new InventoryStoreBatch();
        BeanUtils.copyProperties(request, storeBatch);
        val saleRecord = inventoryInoutRepository.selectSaleRecordByUniqId(inout);
        if (saleRecord.size() > 0) {
            request.setInPrice(saleRecord.get(0).getInPrice());
            request.setSalePrice(saleRecord.get(0).getSalePrice());
        } else {
            BigDecimal avgPrice = inventoryBatchRepository.getAvgPrice(storeBatch);
            if (StringUtils.isEmpty(request.getPulPrice())) request.setInPrice(avgPrice);
            else request.setInPrice(request.getPulPrice());
            InventoryGoodsResponse goods = goodsDefaultService.getGoods(request.getGoodsId());
            request.setSalePrice(goods.getPrice());
        }
        return request;
    }
}
