package com.foreverwin.mesnac.dispatch.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.foreverwin.mesnac.common.constant.Constants;
import com.foreverwin.mesnac.common.dto.LabelPrintDto;
import com.foreverwin.mesnac.common.enums.HandleEnum;
import com.foreverwin.mesnac.common.model.PrintLog;
import com.foreverwin.mesnac.common.service.PrintLogService;
import com.foreverwin.mesnac.common.util.ExceptionUtil;
import com.foreverwin.mesnac.common.util.NumberUtil;
import com.foreverwin.mesnac.common.util.StringUtil;
import com.foreverwin.mesnac.dispatch.mapper.SurplusReturnMapper;
import com.foreverwin.mesnac.dispatch.model.SurplusInventory;
import com.foreverwin.mesnac.dispatch.model.SurplusReturn;
import com.foreverwin.mesnac.dispatch.service.SurplusInventoryService;
import com.foreverwin.mesnac.dispatch.service.SurplusReturnService;
import com.foreverwin.mesnac.meapi.model.Inventory;
import com.foreverwin.mesnac.meapi.model.InventoryAssyData;
import com.foreverwin.mesnac.meapi.service.InventoryAssyDataService;
import com.foreverwin.mesnac.meapi.service.InventoryService;
import com.foreverwin.modular.core.exception.BusinessException;
import com.foreverwin.modular.core.meext.MEServices;
import com.foreverwin.modular.core.util.CommonMethods;
import com.sap.me.inventory.InventoryServiceInterface;
import com.sap.me.inventory.InventorySplitRequest;
import com.sap.me.inventory.NewSplitInventory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 余料退回 服务实现类
 * </p>
 *
 * @author Leon.L
 * @since 2021-07-19
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SurplusReturnServiceImpl extends ServiceImpl<SurplusReturnMapper, SurplusReturn> implements SurplusReturnService {


    @Autowired
    private InventoryService inventoryService;
    @Autowired
    private SurplusReturnMapper surplusReturnMapper;
    @Autowired
    private SurplusInventoryService surplusInventoryService;
    @Autowired
    private PrintLogService printLogService;
    @Autowired
    private InventoryAssyDataService inventoryAssyDataService;

    @Override
    public Map<String, Object> getInventoryData(String site, String inventory) {
        String inventoryBo = HandleEnum.INVENTORY.getHandle(site, inventory);
        Inventory inventoryModel = inventoryService.getById(inventoryBo);
        if (inventoryModel == null) {
            throw BusinessException.build("物料条码【" + inventory +"】不存在！");
        }
        if (inventoryModel.getQtyOnHand().compareTo(BigDecimal.ZERO) <= 0) {
            throw BusinessException.build("物料条码【" + inventory +"】没有可用数量！");
        }

        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        Map<String, Object> map = surplusReturnMapper.selectInventoryData(inventoryBo);
        if (map == null || map.size() <= 0) {
            throw BusinessException.build("物料条码【" + inventory +"】不存在！");
        }
        String item = (String) map.get("ITEM");
        String perMater = (String) map.get("PER_METER");
        String perSquareMeter = (String) map.get("PER_SQUARE_METER");
        if (StringUtil.isBlank(perMater) && StringUtil.isBlank(perSquareMeter)) {
            throw BusinessException.build("物料【" +item+ "】的自定义字段【每米重量】和【每平米重量】都没维护！");
        }
        if (StringUtil.notBlank(perMater) && !NumberUtil.isDouble(perMater)) {
            throw BusinessException.build("物料【" +item+ "】的自定义字段【每米重量】只能维护数值！");
        }
        if (StringUtil.notBlank(perSquareMeter) && !NumberUtil.isDouble(perSquareMeter)) {
            throw BusinessException.build("物料【" +item+ "】的自定义字段【每平米重量】只能维护数值！");
        }

        return map;
    }

    @Override
    public void surplusReturn(String site, String user, String inventory, String length, String width, BigDecimal numbers, BigDecimal qty) {
        String inventoryBo = HandleEnum.INVENTORY.getHandle(site, inventory);
        Inventory inventoryModel = inventoryService.getById(inventoryBo);
        if (inventoryModel == null) {
            throw BusinessException.build("物料条码【" + inventory +"】不存在！");
        }
        BigDecimal qtyOnHand = inventoryModel.getQtyOnHand();
        if (qtyOnHand.compareTo(BigDecimal.ZERO) <= 0) {
            throw BusinessException.build("物料条码【" + inventory +"】没有可用数量！");
        }
        if (qtyOnHand.compareTo(qty) < 0) {
            throw BusinessException.build("余料数量超过了物料条码现有数量【" +qtyOnHand+ "】！");
        }

        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        InventoryServiceInterface meInventoryService;
        try {
            meInventoryService = MEServices.create("com.sap.me.inventory", "InventoryService", site);
        } catch (Exception e) {
            throw BusinessException.build("获取标准库存操作服务失败：" + e.getMessage());
        }


        //余料库存
        StringBuffer _inventory = new StringBuffer(inventory);
        if (StringUtil.notBlank(length)) {
            _inventory.append("*"+length);
        }
        if (StringUtil.notBlank(width)) {
            _inventory.append("*"+width);
        }
        String surplusInventory = _inventory.toString();

        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        //库存拆分
        try {
            InventorySplitRequest request = new InventorySplitRequest();
            request.setInventoryRef(inventoryBo);
            request.setQuantityToSplit(qty);

            List<NewSplitInventory> splitList = new ArrayList<>();
            NewSplitInventory newSplitInventory = new NewSplitInventory();
            newSplitInventory.setNewInventoryId(surplusInventory);
            newSplitInventory.setQuantity(qty);
            splitList.add(newSplitInventory);
            request.setNewInventoryList(splitList);
            meInventoryService.split(request);
        } catch (Exception e) {
            ExceptionUtil.throwException(e);
        }

        LocalDateTime dateTime = LocalDateTime.now();
        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        //记录余料库存批次
        String surplusInventoryBo = HandleEnum.INVENTORY.getHandle(site, surplusInventory);
        SurplusInventory surplusInventoryModel = surplusInventoryService.getById(surplusInventoryBo);
        if (surplusInventoryModel == null) {
            surplusInventoryModel = new SurplusInventory();
            surplusInventoryModel.setHandle(surplusInventoryBo);
            surplusInventoryModel.setSite(site);
            surplusInventoryModel.setParentInventory(inventory);
            surplusInventoryModel.setInventory(surplusInventory);
            surplusInventoryModel.setLenght(length);
            surplusInventoryModel.setWidth(width);
            surplusInventoryModel.setQty(qty);
            surplusInventoryModel.setItemBo(inventoryModel.getItemBo());
            surplusInventoryModel.setCreateUser(user);
            surplusInventoryModel.setCreatedDateTime(dateTime);
            surplusInventoryModel.setModifyUser(user);
            surplusInventoryModel.setModifiedDateTime(dateTime);
            surplusInventoryService.save(surplusInventoryModel);
        } else {
            surplusInventoryModel.setModifyUser(user);
            surplusInventoryModel.setModifiedDateTime(dateTime);
            surplusInventoryModel.setQty(surplusInventoryModel.getQty().add(qty));
            surplusInventoryService.updateById(surplusInventoryModel);
        }

        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        //记录余料退回日志
        SurplusReturn surplusItemReturn = new SurplusReturn();
        surplusItemReturn.setHandle(UUID.randomUUID().toString());
        surplusItemReturn.setSite(site);
        surplusItemReturn.setParentInventory(inventory);
        surplusItemReturn.setInventory(surplusInventory);
        surplusItemReturn.setLenght(length);
        surplusItemReturn.setWidth(width);
        surplusItemReturn.setItemBo(inventoryModel.getItemBo());
        surplusItemReturn.setNumbers(numbers);
        surplusItemReturn.setQty(qty);
        surplusItemReturn.setCreateUser(user);
        surplusItemReturn.setCreatedDateTime(dateTime);
        surplusItemReturn.setModifyUser(user);
        surplusItemReturn.setModifiedDateTime(dateTime);
        surplusReturnMapper.insert(surplusItemReturn);

        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        // 记录余料信息，提供打印
        // {"ITEM":"500100010001","INVENTORY":"500100010001*20210721","ITEM_DESC":"测试物料","SUPPLIER":"BA002"}
        PrintLog printLog = new PrintLog();
        printLog.setHandle(UUID.randomUUID().toString());
        printLog.setSite(site);
        printLog.setCategory(Constants.PRINT_TYPE_EXM);
        printLog.setPrintTemplate(Constants.PRINT_TYPE_EXM);
        printLog.setPrintNum(0);
        // 查询供应商
        InventoryAssyData inventoryAssyData = new InventoryAssyData();
        inventoryAssyData.setInventoryBo(inventoryBo);
        inventoryAssyData.setDataField("VENDOR_NAME");
        List<InventoryAssyData> inventoryAssyDataList = inventoryAssyDataService.selectList(inventoryAssyData);

        // 记录打印参数：物料、物料编码、供应商、批次号
        LabelPrintDto labelPrintDto = new LabelPrintDto();
        labelPrintDto.setItem(inventoryModel.getItemBo().split(",")[1]);
        labelPrintDto.setItemDescription(inventoryModel.getDescription());
        if (inventoryAssyDataList.size() == 1){
            labelPrintDto.setSupplier(inventoryAssyDataList.get(0).getDataAttr());
            labelPrintDto.setBatch(inventoryAssyDataList.get(0).getDataField());
            //throw BusinessException.build("未正确找到当前批次的供应商！");
        }
        labelPrintDto.setLabel(surplusInventory);

        printLog.setPrintParam(JSON.toJSONString(labelPrintDto));
        printLog.setInventory(surplusInventory);

        printLog.setItemBo(inventoryModel.getItemBo());
        printLog.setCreateUser(user);
        printLog.setCreatedDateTime(dateTime);
        printLogService.save(printLog);
    }


}