package com.jsh.erp.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jsh.erp.datasource.entities.*;
import com.jsh.erp.datasource.mappers.MaterialBatchMapper;
import com.jsh.erp.datasource.mappers.MaterialCategoryMapperEx;
import com.jsh.erp.datasource.vo.TaskStocktakingItemVO;
import com.jsh.erp.exception.JshException;
import com.jsh.erp.query.LambdaQueryWrapperX;
import com.jsh.erp.service.*;
import com.jsh.erp.utils.DateUtils;
import com.jsh.erp.utils.RandomHelper;
import com.jsh.erp.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

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

@Service
public class MaterialBatchServiceImpl extends ServiceImpl<MaterialBatchMapper,MaterialBatch> implements MaterialBatchService {
    private Logger logger = LoggerFactory.getLogger(MaterialBatchServiceImpl.class);

    @Resource
    private MaterialBatchMapper materialBatchMapper;

    @Resource
    private UserService userService;

    @Resource
    private DepotItemService depotItemService;

    @Resource
    private MaterialExtendService materialExtendService;

    @Resource
    private InventoryLogService inventoryLogService;

    @Resource
    private MaterialService materialService;


    @Override
    public void generateMaterialBatchByDepotItemId(DepotItem depotItem, Long supplierId) throws Exception {
        //获取单据子表信息
        //获取条码信息
        MaterialExtend materialExtend = materialExtendService.getMaterialExtend(depotItem.getMaterialExtendId());
        //创建批次信息
        MaterialBatch materialBatch = new MaterialBatch();
        //设置单据id
        materialBatch.setDepotItemId(depotItem.getId());
        //设置商品id
        materialBatch.setMaterialId(depotItem.getMaterialId());
        //设置供应商id
        materialBatch.setSupplierId(supplierId);
        //设置商品单位
        materialBatch.setCommodityUnit(depotItem.getMaterialUnit());
        User user = userService.getCurrentUser();
        //创建人编码
        materialBatch.setCreateSerial(user.getLoginName());
        //创建日期
        materialBatch.setCreateTime(new Date());
        //生产日期
        materialBatch.setProductionDate(depotItem.getProductionDate());
        //保质期天数
        materialBatch.setExpiryNum(depotItem.getExpiryNum());
        //批次号
        String batchNumber = DateUtils.dateTimeNow("yyyyMMdd") + RandomHelper.getRandomStr(6);
        materialBatch.setBatchNumber(batchNumber);
        //设置库存(订单基础单位数量)
        materialBatch.setInventory(depotItem.getBasicNumber());
        //仓库id
        materialBatch.setDepotId(depotItem.getDepotId());
        //仓位货架
        materialBatch.setPosition(depotItem.getPosition());
        //条码
        materialBatch.setBarCode(materialExtend.getBarCode());
        materialBatchMapper.insert(materialBatch);
    }

    @Override
    public void handleMaterialBatchByDepotItemId(Long diId) throws Exception {
        DepotItem depotItem = depotItemService.getDepotItem(diId);
        //根据单据商品id查询商品批次数据
        List<MaterialBatch> list = materialBatchMapper.getMaterialBatchByMaterialId(depotItem.getMaterialId(),depotItem.getDepotId());
        //根据单据子表基础单位数量减去批次库存
        BigDecimal basicNumber = depotItem.getBasicNumber();
        for (MaterialBatch materialBatch : list) {
            if (materialBatch.getInventory().compareTo(basicNumber) >= 0){
                //批次库存足够，扣除库存，结束循环
                BigDecimal inventory = materialBatch.getInventory().subtract(basicNumber);
                materialBatch.setInventory(inventory);
                updateInventory("出库",diId,materialBatch);
                break;
            }else {
                //库存不足,扣除当前批次库存,继续循环
                basicNumber = basicNumber.subtract(materialBatch.getInventory());
                materialBatch.setInventory(BigDecimal.ZERO);
                updateInventory("出库",diId,materialBatch);
            }
        }
    }

    @Override
    public synchronized void updateInventory(String type, Long id, MaterialBatch materialBatch) throws Exception {
        if (materialBatch.getInventory() != null){
            //获取修改前库存
            int originalStock = materialBatchMapper.selectOne("id",materialBatch.getId()).getInventory().intValue();
                User user = userService.getCurrentUser();
                InventoryLog log = new InventoryLog();
                log.setUpdateUser(user.getId());
                log.setUpdateTime(new Date());
                log.setMaterialId(materialBatch.getMaterialId());
                log.setMaterialExtendId(materialBatch.getId());
                log.setOriginalStock(originalStock);
                log.setCurrentStock(materialBatch.getInventory().intValue());
                log.setItemId(id);
                log.setType(type);
                inventoryLogService.save(log);
                update(new UpdateWrapper<MaterialBatch>().set("inventory",materialBatch.getInventory()).eq("id",materialBatch.getId()));
                depotItemService.updateCurrentStockFun(materialBatch.getMaterialId(),materialBatch.getDepotId());
        }
    }

    /**
     * 根据仓库id和商品id查询商品批次库存
     * @param depotList 仓库id
     * @param mid       商品id
     */
    @Override
    public BigDecimal getInventorySumByDepotAndMid(List<Long> depotList, Long mid) {
        return materialBatchMapper.getInventorySumByDepotAndMid(depotList,mid);
    }

    /**
     * 获取批次号字符
     */
    @Override
    public List<MaterialVo4Unit> findBySelectWithBarCode(Long categoryId, String q, String standardOrModel, String color, String brand, String mfrs, String enableSerialNumber, String enableBatchNumber, Integer offset, Integer rows, Long depotId) throws Exception {
        List<MaterialVo4Unit> list =null;
        try{

            if(StringUtil.isNotEmpty(q)) {
                q = q.replace("'", "");
                q = q.trim();
            }
            list=  materialBatchMapper.findBySelectWithBarCode(q, standardOrModel, color, brand, mfrs,
                    enableSerialNumber, enableBatchNumber, offset, rows,depotId);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }

    /**
     * 根据商品条码和仓库id获取商品批次信息
     * @param barCodes 商品条码字符集合
     */
    @Override
    public List<MaterialBatch> findBySelectWithBarCode(String barCodes,Long depotId) {
        List<String> barCodeList = null;
        if (barCodes != null && !barCodes.isEmpty()){
            barCodeList = Arrays.asList(barCodes.split(","));
        }
        List<Long> ids = materialExtendService.selectIdsByBarCode(barCodeList);
        List<MaterialBatch> list = materialBatchMapper.selectList(new LambdaQueryWrapperX<MaterialBatch>().eq(MaterialBatch::getDepotId,depotId).inIfPresent(MaterialBatch::getMaterialId,ids).gt(MaterialBatch::getInventory,BigDecimal.ZERO));
        return list;
    }

    /**
     * 根据批次号数组查询商品批次信息
     * @param batchNumbers 批次号数组
     */
    @Override
    public List<TaskStocktakingItemVO> getMaterialByBatchNumber(String[] batchNumbers) {
        List<TaskStocktakingItemVO> list =  materialBatchMapper.getMaterialByBatchNumber(batchNumbers);
        return list;
    }

}
