package com.ximai.mes.remote.process;

import com.ximai.mes.aspect.IExtendedProcess;
import com.ximai.mes.constant.ItemTypeEnum;
import com.ximai.mes.md.domain.MdItem;
import com.ximai.mes.md.mapper.MdItemMapper;
import com.ximai.mes.pro.domain.proWorkOrder.ProWorkorder;
import com.ximai.mes.remote.ErpService;
import com.ximai.mes.remote.dto.FinishStockInCreate;
import com.ximai.mes.remote.dto.FinishStockInCreateDetail;
import com.ximai.system.strategy.AutoCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Component
public class FinishStockInCreateProcess implements IExtendedProcess {

    @Autowired
    ErpService erpService;
    @Autowired
    MdItemMapper mdItemMapper;
    @Autowired
    private AutoCodeUtil autoCodeUtil;
    @Override
    public void process(Object[] args, Object returnResult) {
        ProWorkorder workorder = (ProWorkorder)args[0];
        BigDecimal qualifyQuantity = (BigDecimal)args[1];
        String requestCode = autoCodeUtil.genSerialCode("ERP_FINISH_STOCK_IN","");
        MdItem item = mdItemMapper.selectById(workorder.getProductId());
        if(!Objects.equals(ItemTypeEnum.FINAL.getId(), item.getItemTypeId())){
            FinishStockInCreate create = new FinishStockInCreate();
            create.setStockInNo(requestCode);
            List<FinishStockInCreateDetail> details = new ArrayList<>();
            FinishStockInCreateDetail detail = new FinishStockInCreateDetail();
            detail.setStockInNo(requestCode);
            detail.setWorkorderType(workorder.getWorkorderType());
            detail.setWorkorderCode(workorder.getWorkorderCode());
            detail.setCheckQuantity(qualifyQuantity);
            detail.setInQuantity(qualifyQuantity);
            detail.setBatchNo(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")));
            details.add(detail);
            create.setDetails(details);
            erpService.finishStockInCreate(create);
        }
    }
}
