package com.ximai.mes.remote.process;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ximai.mes.aspect.IExtendedProcess;
import com.ximai.mes.pro.domain.proWorkOrder.ProWorkOrderProcess;
import com.ximai.mes.pro.domain.task.ProTask;
import com.ximai.mes.pro.dto.task.FeedbackDto;
import com.ximai.mes.pro.service.proWorkOrder.IProWorkOrderProcessService;
import com.ximai.mes.remote.ErpService;
import com.ximai.mes.remote.dto.ProcessReportCreate;
import com.ximai.mes.remote.util.ErpMachineTimeConverter;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;

@ApiOperation("工序报工")
@Component
public class ProcessReportCreateProcess implements IExtendedProcess {

    @Autowired
    ErpService erpService;
    @Autowired
    IProWorkOrderProcessService workOrderProcessService;

    @Override
    public void process(Object[] args, Object returnResult) {
        FeedbackDto feedbackDto = (FeedbackDto) args[0];
        BigDecimal qualifyQuantity = (BigDecimal) args[1];
        ProTask currTask = feedbackDto.getCurrTask();

        ProcessReportCreate create = new ProcessReportCreate();
        create.setWorkOrderType(feedbackDto.getWorkorder().getWorkorderType());
        create.setWorkOrderNo(feedbackDto.getWorkorder().getWorkorderCode());
        create.setProcessSeq(currTask.getIdx());
        create.setProcessName(currTask.getProcessName());
        create.setReportQty(qualifyQuantity);
        create.setUnQualifyQty(BigDecimal.ZERO);
        create.setType("1");
        create.setMachineHours(ErpMachineTimeConverter.toMachineSeconds(feedbackDto.getMachineTime()));

        List<ProWorkOrderProcess> workorderProcessList = workOrderProcessService.selectListByQw(
                new QueryWrapper<ProWorkOrderProcess>()
                        .eq("t1.workorder_id", feedbackDto.getWorkorder().getWorkorderId())
                        .eq("t1.process_id", currTask.getProcessId()));
        String processNo = currTask.getProcessCode();
        if (!workorderProcessList.isEmpty()) {
            ProWorkOrderProcess workOrderProcess = workorderProcessList.get(0);
            if (StringUtils.isBlank(processNo)) {
                processNo = workOrderProcess.getProcessRef();
            }
        }
        if (StringUtils.isBlank(processNo)) {
            processNo = currTask.getIdx();
        }
        create.setProcessRef(StringUtils.left(processNo, 4));
        erpService.processReportCreate(create);
    }
}
