package cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.busi;

import cn.estsh.i3plus.ext.mes.pcn.api.busi.IMesDefectRecordService;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.pojo.mes.bean.MesDefectRecord;
import cn.estsh.i3plus.pojo.mes.bean.MesWorkOrder;
import cn.estsh.i3plus.pojo.mes.repository.MesDefectRecordRepository;
import cn.estsh.i3plus.pojo.mes.repository.MesWorkOrderRepository;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @Description :
 * @Reference :
 * @Author :
 * @CreateDate : 2024-05-09 10:54
 * @Modify:
 **/

@Service
@Slf4j
public class MesDefectRecordService implements IMesDefectRecordService {

    @Autowired
    private MesWorkOrderRepository workOrderRepository;
    @Autowired
    private MesDefectRecordRepository defectRecordRepository;

    @Override
    public void saveDefect(String organizeCode, String userName, List<MesDefectRecord> recordList) {
//        //校验工单
//        MesWorkOrder workOrder = checkQty(recordList);

//        recordList.forEach(r -> {
//            r.setId(null);
////            r.setOrderId(workOrder.getId());
////            r.setOrderNo(workOrder.getOrderNo());
//            r.setOrganizeCode(organizeCode);
//            //更新工单表报废数量
////            workOrder.setRepairQty(workOrder.getRepairQtyVal() + r.getQty());
//            ConvertBean.serviceModelInitialize(r, userName);
//        });
        defectRecordRepository.saveAll(recordList);

//        ConvertBean.serviceModelUpdate(workOrder, userName);
//        workOrderExtRepository.update(workOrder);
    }

//    public MesWorkOrder checkQty(List<MesDefectRecord> recordList) {
//        MesDefectRecord recordExt = recordList.stream().findFirst().get();
//        MesWorkOrder workOrder = workOrderRepository.getById(recordExt.getWorkOrderNo());
//        if (workOrder == null) {
//            throw ImppExceptionBuilder.newInstance()
//                    .setErrorDetail("工单ID【%s】不存在", recordExt.getOrderId())
//                    .build();
//        }
//        //获取不良总数
//        double total = recordList.stream().filter(r -> r.getQty() != null).mapToDouble(MesDefectRecordMagna::getQty).sum();
//        if (total > workOrder.getQty()) {
//            throw ImppExceptionBuilder.newInstance()
//                    .setErrorDetail("不良数量总数不能大于工单数")
//                    .build();
//        }
//        return workOrder;
//    }

}
