package cn.estsh.i3plus.ext.mes.pcn.apiservice.daoimpl;

import cn.estsh.i3plus.ext.mes.pcn.apiservice.dao.IProduceSnTravelDao;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.ProduceSnTravelModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.SnAndPackageNoCorrelationModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.List;

/**
 * @PROJECT_NAME: i3plus-mes-panasonic-bu
 * @DESCRIPTION:
 * @USER: xinwang.yi
 * @DATE: 2022-01-09 15:14
 */
@Service
public class ProduceSnTravelDao implements IProduceSnTravelDao {

    @Autowired
    private EntityManager entityManager;

    @Override
    public List<ProduceSnTravelModel> queryProduceSnTravel(String organizeCode, String workCellCode, String workCenterCode, String workOrderNo) {
        StringBuffer hql = new StringBuffer();
        hql.append(" select new " + ProduceSnTravelModel.class.getName() + "(pst.serialNumber, pst.modifyDatetime) ");
        hql.append(" from MesProduceSnTravel as pst LEFT JOIN MesProduceSn sn on sn.serialNumber = pst.serialNumber ");
        hql.append(" where pst.organizeCode = :organizeCode ");
        hql.append(" and pst.isValid = :isValid ");
        hql.append(" and pst.isDeleted = :isDeleted ");
        hql.append(" and sn.isValid = :isValid ");
        hql.append(" and sn.isDeleted = :isDeleted ");
        hql.append(" and sn.organizeCode = :organizeCode ");
        hql.append(" and sn.workOrderNo = :workOrderNo ");
        hql.append(" and pst.workOrderNo = :workOrderNo ");
        hql.append(" and pst.workCenterCode = :workCenterCode ");
        hql.append(" and pst.workCellCode = :workCellCode ");

        hql.append(" group by pst.serialNumber, pst.modifyDatetime ");
        hql.append(" order by pst.modifyDatetime desc ");
        Query query = entityManager.createQuery(hql.toString(), ProduceSnTravelModel.class);

        query.setParameter(MesPcnExtConstWords.IS_VALID, CommonEnumUtil.IS_VAILD.VAILD.getValue());
        query.setParameter(MesPcnExtConstWords.IS_DELETED, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue());
        query.setParameter(MesPcnExtConstWords.ORGANIZE_CODE, organizeCode);
        query.setParameter(MesPcnExtConstWords.WORK_ORDER_NO, workOrderNo);
        query.setParameter(MesPcnExtConstWords.WORK_CENTER_CODE, workCenterCode);
        query.setParameter(MesPcnExtConstWords.WORK_CELL_CODE, workCellCode);

        return query.getResultList();
    }
}
