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

import cn.estsh.i3plus.ext.mes.pcn.apiservice.dao.bu.IBuProduceSnExtDao;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.bu.BuOqcProduceSnModel;
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;

/**
 * @Author: wangjie
 * @CreateDate: 2019/11/21 11:29 上午
 * @Description:
 **/
@Service
public class BuProduceSnExtDao implements IBuProduceSnExtDao {

    @Autowired
    private EntityManager entityManager;

    @Override
    public List<BuOqcProduceSnModel> querySnListByOrderNoAndWorkTime4Oqc(String organizeCode, String workOrderNo, String workTime, String shiftCode) {
        StringBuffer hql = new StringBuffer();
        hql.append(" select new " + BuOqcProduceSnModel.class.getName() + "(pse.productSn, pse.serialNumber, pse.workOrderNo, pse.qcStatus, pse.snStatus, pse.outWorkCenterTime, pse.lastWorkOrderNo, pd.packageNo, pse.workCenterCode) ");

        packHqlForQuerySnListByOrderNoAndWorkTime4Oqc(hql);

        hql.append(" order by pse.serialNumber asc ");
        Query query = entityManager.createQuery(hql.toString(), BuOqcProduceSnModel.class);

        packParameterForQuerySnListByOrderNoAndWorkTime4Oqc(query, organizeCode, workOrderNo, workTime, shiftCode);

        return query.getResultList();
    }

    private void packHqlForQuerySnListByOrderNoAndWorkTime4Oqc(StringBuffer hql) {
        hql.append(" from MesProduceSnExt as pse ");
        hql.append(" left join MesPackageDetail as pd on (pse.serialNumber = pd.serialNumber and pd.organizeCode = :organizeCode and pd.isValid = :isValid and pd.isDeleted = :isDeleted) ");
        hql.append(" where pse.organizeCode = :organizeCode ");
        hql.append(" and pse.isValid = :isValid ");
        hql.append(" and pse.isDeleted = :isDeleted ");
        hql.append(" and pse.workOrderNo = :workOrderNo ");
        hql.append(" and pse.workTime = :workTime ");
        hql.append(" and pse.shiftCode = :shiftCode ");
    }

    private void packParameterForQuerySnListByOrderNoAndWorkTime4Oqc(Query query, String organizeCode, String workOrderNo, String workTime, String shiftCode) {
        query.setParameter(MesPcnExtConstWords.ORGANIZE_CODE, organizeCode);
        query.setParameter(MesPcnExtConstWords.IS_VALID, CommonEnumUtil.IS_VAILD.VAILD.getValue());
        query.setParameter(MesPcnExtConstWords.IS_DELETED, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue());
        query.setParameter(MesPcnExtConstWords.WORK_ORDER_NO, workOrderNo);
        query.setParameter(MesPcnExtConstWords.WORK_TIME, workTime);
        query.setParameter(MesPcnExtConstWords.SHIFT_CODE, shiftCode);
    }

}
