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

import cn.estsh.i3plus.ext.mes.pcn.api.busi.ISxWorkOrderTravelService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesWorkOrderExt;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesWorkOrderTravel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesWorkOrderTravelRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtEnumUtil;
import cn.estsh.i3plus.pojo.base.bean.DdlPackBean;
import cn.estsh.i3plus.pojo.base.tool.DdlPreparedPack;
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;

/**
 * @PROJECT_NAME: i3plus-mes-panasonic
 * @DESCRIPTION:
 * @USER: xinwang.yi
 * @DATE: 2022-10-25 9:58
 */
@Service
public class MesWorkOrderTravelService implements ISxWorkOrderTravelService {

    @Autowired
    private MesWorkOrderTravelRepository workOrderTravelRepository;

    @Override
    public MesWorkOrderTravel insertWorkOrderTravel(MesWorkOrderExt workOrderExt) {
        MesWorkOrderTravel workOrderTravel = new MesWorkOrderTravel();
        BeanUtils.copyProperties(workOrderExt, workOrderTravel, MesPcnExtConstWords.ID);
        workOrderTravel.setPid(workOrderExt.getId());
        MesWorkOrderTravel maxSeqWorkOrderTravel = getMaxSeqWorkOrderTravel(workOrderExt.getOrganizeCode(), workOrderExt.getOrderNo());
        workOrderTravel.setSyncSeq(maxSeqWorkOrderTravel == null ? 1 : maxSeqWorkOrderTravel.getSyncSeq() + 1);
        workOrderTravel.setSystemSyncStatus(MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
        return workOrderTravelRepository.insert(workOrderTravel);
    }

    @Override
    public MesWorkOrderTravel getMaxSeqWorkOrderTravel(String organizeCode, String workOrderNo) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getStringEqualPack(workOrderNo, MesPcnExtConstWords.ORDER_NO, packBean);
        packBean.setOrderByStr(" order by syncSeq desc ");
        return workOrderTravelRepository.getByProperty(packBean);
    }

    @Override
    public void deleteWorkOrderTravel(String organizeCode, String modifyDatetime) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getStringSmallerPack(modifyDatetime, MesPcnExtConstWords.MODIFY_DATE_TIME, packBean);
        DdlPreparedPack.getNumEqualPack(MesPcnExtEnumUtil.IF_SYNC_STATUS.ALREADY_SYNC.getValue(), MesPcnExtConstWords.SYSTEM_SYNC_STATUS, packBean);
        List<MesWorkOrderTravel> workOrderTravelList = workOrderTravelRepository.findByHqlWhere(packBean);
        if(!CollectionUtils.isEmpty(workOrderTravelList)) workOrderTravelRepository.deleteAll(workOrderTravelList);
    }
}
