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

import cn.estsh.i3plus.ext.mes.api.busi.IWorkOrderLogExtService;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesWorkOrderExt;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesWorkOrderLogExt;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesWorkOrderLogExtRepository;
import cn.estsh.i3plus.ext.mes.pojo.util.ConvertBeanExt;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtConstWords;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.pojo.base.bean.DdlPackBean;
import cn.estsh.i3plus.pojo.base.tool.DdlPreparedPack;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wangjie
 * @version 1.0
 * @date 2021/1/13 9:28
 **/
@Slf4j
@Service
public class WorkOrderLogExtService implements IWorkOrderLogExtService {

    @Autowired
    private MesWorkOrderLogExtRepository workOrderLogExtRepository;

    @Override
    public MesWorkOrderLogExt insertMesWorkOrderLogExt(MesWorkOrderExt workOrderExt) {
        MesWorkOrderLogExt workOrderLogExt = new MesWorkOrderLogExt();
        BeanUtils.copyProperties(workOrderExt, workOrderLogExt, MesExtConstWords.ID);
        ConvertBean.serviceModelInitialize(workOrderLogExt, workOrderExt.getModifyUser());
        new ConvertBeanExt(workOrderLogExt).convertBean(workOrderLogExt);
        return workOrderLogExtRepository.insert(workOrderLogExt);
    }

    @Override
    public void doDeleteWorkOrderLogExt(String organizeCode, List<Integer> workOrderStatusList, String modifyDatetime) {

        for (Integer workOrderStatus : workOrderStatusList) {
            DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
            DdlPreparedPack.getNumEqualPack( workOrderStatus, MesExtConstWords.WORK_ORDER_STATUS, packBean);
            DdlPreparedPack.getStringSmallerPack(modifyDatetime, MesExtConstWords.MODIFY_DATE_TIME, packBean);
            List<MesWorkOrderLogExt> mesWorkOrderLogExts = workOrderLogExtRepository.findByHqlWhere(packBean);

            List<String> workOrderNoList = CollectionUtils.isEmpty(mesWorkOrderLogExts) ? null : mesWorkOrderLogExts.stream().map(MesWorkOrderLogExt::getOrderNo).distinct().collect(Collectors.toList());

            if(!CollectionUtils.isEmpty(workOrderNoList)){
                for (String workOrderNo : workOrderNoList) {
                    workOrderLogExtRepository.deleteByProperties(new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.ORDER_NO}, new Object[]{ organizeCode, workOrderNo });
                }
            }
            //
            //if(!CollectionUtils.isEmpty(mesWorkOrderLogExts)) workOrderLogExtRepository.deleteAll(mesWorkOrderLogExts);
        }

    }
}
