package cn.ezhizao.project.business.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Resource;

import cn.ezhizao.project.business.domain.BizOutsourcedOrderDetail;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import cn.ezhizao.project.business.mapper.BizOutsourcedOrderDetailProcessMapper;
import cn.ezhizao.project.business.domain.BizOutsourcedOrderDetailProcess;
import cn.ezhizao.project.business.service.IBizOutsourcedOrderDetailProcessService;

/**
 * 外协单从对应的外协工序的从Service业务层处理
 *
 * @author ezhizao
 * @date 2024-04-26
 */
@Service
public class BizOutsourcedOrderDetailProcessServiceImpl  extends ServiceImpl<BizOutsourcedOrderDetailProcessMapper, BizOutsourcedOrderDetailProcess> implements IBizOutsourcedOrderDetailProcessService
{
    @Resource
    private BizOutsourcedOrderDetailProcessMapper bizOutsourcedOrderDetailProcessMapper;

    /**
     * 查询外协单从对应的外协工序的从列表
     *
     * @param bizOutsourcedOrderDetailProcess 外协单从对应的外协工序的从
     * @return 外协单从对应的外协工序的从
     */
    @Override
    public List<BizOutsourcedOrderDetailProcess> getList(BizOutsourcedOrderDetailProcess bizOutsourcedOrderDetailProcess)
    {
        return bizOutsourcedOrderDetailProcessMapper.getList(bizOutsourcedOrderDetailProcess);
    }
    @Override
    public List<BizOutsourcedOrderDetailProcess> getDetailList(BizOutsourcedOrderDetailProcess bizOutsourcedOrderDetailProcess)
    {
        return bizOutsourcedOrderDetailProcessMapper.getDetailList(bizOutsourcedOrderDetailProcess);
    }

    /**
     * 物理删除
     * @param bizOutsourcedOrderDetailProcess
     * @return 删除结果
     */
    @Override
    public int physicalDelete(BizOutsourcedOrderDetailProcess bizOutsourcedOrderDetailProcess){ return bizOutsourcedOrderDetailProcessMapper.physicalDelete(bizOutsourcedOrderDetailProcess); }

    @Override
    public boolean batchSave(List<BizOutsourcedOrderDetail> outsourcedOrderDetails) {
        List<BizOutsourcedOrderDetailProcess> processesList=new ArrayList<>();
        outsourcedOrderDetails.forEach(detail -> {
            detail.getProcesses().forEach(process -> {
                process.setId(null);
                process.setMasterId(detail.getMasterId());
                process.setDetailId(detail.getId());
                process.setLotId(detail.getLotId());
                process.setLotCode(detail.getLotCode());
                process.setFormDate(detail.getFormDate());
                process.setDayworkId(detail.getDayworkId());
                process.setFormCode(detail.getFormCode());
                process.setProductDescription(detail.getProductDescription());
                process.setTechnologicalProcessId(detail.getTechnologicalProcessId());
                process.setSupplierId(detail.getSupplierId());
                process.setSupplierName(detail.getSupplierName());
                process.setDeliveryMethod(detail.getDeliveryMethod());
                process.setProductId(detail.getProductId());
                process.setTechnologyVersion(detail.getTechnologyVersion());
                process.setPackagingMethod(detail.getPackagingMethod());
                process.setProductNum(detail.getProductNum());
                process.setTenantId(detail.getTenantId());
                processesList.add(process);
            });
        });
        return saveBatch(processesList);
    }
    @Override
    public boolean updateOrSave(List<BizOutsourcedOrderDetail> outsourcedOrderDetails) {
        //查找已经添加的process
        List<Long> masterIds = outsourcedOrderDetails.stream().map(BizOutsourcedOrderDetail::getMasterId).collect(Collectors.toList());
        //外协单明细绑定的工序
        List<BizOutsourcedOrderDetailProcess> detaillist = query().in("master_id", masterIds).list();
        //直接删除发出单明细（新的外协明细和旧的外协明细比较，如果新的里面没有旧的明细，则把差别的外协发出工序删除）
        if(!detaillist.isEmpty()) {
            List<Long> newDetailId = outsourcedOrderDetails.stream().map(BizOutsourcedOrderDetail::getId).distinct().collect(Collectors.toList());
            List<Long> oldDetailId = detaillist.stream().map(BizOutsourcedOrderDetailProcess::getDetailId).distinct().collect(Collectors.toList());
            List<Long> ids = oldDetailId.stream().filter(item ->!newDetailId.contains(item)).collect(Collectors.toList());
            if(!ids.isEmpty()){
                removeBatchByIds( query().in("detail_id",ids).list());
            }
        }
        //存放需要修改的外协发出工序
        List<BizOutsourcedOrderDetailProcess> updateList = new ArrayList<>();
        //需要新增的外协发出工序
        List<BizOutsourcedOrderDetailProcess> saveList=new ArrayList<>();
        outsourcedOrderDetails.forEach(detail -> {
            List<BizOutsourcedOrderDetailProcess> oldList = detaillist.size()>0?detaillist.stream().filter(item ->item.getDetailId().equals(detail.getId())).collect(Collectors.toList()):new ArrayList<>();
            List<String> oldProcessStepNumberList = oldList.stream().map(BizOutsourcedOrderDetailProcess::getProcessStepNumber).collect(Collectors.toList());
            List<String> newProcessStepNumberList = detail.getProcesses().stream().map(BizOutsourcedOrderDetailProcess::getProcessStepNumber).collect(Collectors.toList());
            List<String> differentInOld = oldProcessStepNumberList.size()>0?oldProcessStepNumberList.stream()
                    .filter(process -> !newProcessStepNumberList.contains(process))
                    .collect(Collectors.toList()):new ArrayList<>();
            //发出单明细的工序进行修改时，把多出来的工序删除
            if(!differentInOld.isEmpty()) {
                List<BizOutsourcedOrderDetailProcess> differentList = query().eq("detail_id", detail.getId()).in("process_step_number", differentInOld).list();
                removeBatchByIds(differentList);
            }
            detail.getProcesses().forEach(process -> {
                //如果这道工序已经添加过,则修改
                if(oldProcessStepNumberList.contains(process.getProcessStepNumber())) {
                    BizOutsourcedOrderDetailProcess updateProcess = oldList.stream().filter(info -> info.getProcessStepNumber().equals(process.getProcessStepNumber())).collect(Collectors.toList()).get(0);
                    updateProcess.setMasterId(detail.getMasterId());
                    updateProcess.setDetailId(detail.getId());
                    updateProcess.setLotId(detail.getLotId());
                    updateProcess.setLotCode(detail.getLotCode());
                    updateProcess.setFormDate(detail.getFormDate());
                    updateProcess.setDayworkId(detail.getDayworkId());
                    updateProcess.setFormCode(detail.getFormCode());
                    updateProcess.setProductDescription(detail.getProductDescription());
                    updateProcess.setTechnologicalProcessId(detail.getTechnologicalProcessId());
                    updateProcess.setSupplierId(detail.getSupplierId());
                    updateProcess.setSupplierName(detail.getSupplierName());
                    updateProcess.setDeliveryMethod(detail.getDeliveryMethod());
                    updateProcess.setProductId(detail.getProductId());
                    updateProcess.setTechnologyVersion(detail.getTechnologyVersion());
                    updateProcess.setPackagingMethod(detail.getPackagingMethod());
                    updateProcess.setProductNum(detail.getProductNum());
                    updateProcess.setTenantId(detail.getTenantId());
                    updateList.add(updateProcess);
                }else{
                    //没有则新增
                    process.setMasterId(detail.getMasterId());
                    process.setDetailId(detail.getId());
                    process.setLotId(detail.getLotId());
                    process.setLotCode(detail.getLotCode());
                    process.setFormDate(detail.getFormDate());
                    process.setDayworkId(detail.getDayworkId());
                    process.setFormCode(detail.getFormCode());
                    process.setProductDescription(detail.getProductDescription());
                    process.setTechnologicalProcessId(detail.getTechnologicalProcessId());
                    process.setSupplierId(detail.getSupplierId());
                    process.setSupplierName(detail.getSupplierName());
                    process.setDeliveryMethod(detail.getDeliveryMethod());
                    process.setProductId(detail.getProductId());
                    process.setTechnologyVersion(detail.getTechnologyVersion());
                    process.setPackagingMethod(detail.getPackagingMethod());
                    process.setProductNum(detail.getProductNum());
                    process.setTenantId(detail.getTenantId());
                    saveList.add(process);
                }
            });
        });
        if(!updateList.isEmpty()){
            updateBatchById(updateList);
        }
        if(!saveList.isEmpty()) {
            saveBatch(saveList);
        }
        return true;
    }
    @Override
    public int removeByMasterIds(List<Long> ids) {
      return  bizOutsourcedOrderDetailProcessMapper.removeByMasterIds(ids);
    };

}
