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

import cn.estsh.i3plus.ext.mes.pcn.apiservice.dao.bu3.IOuterPackageDao;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.bu3.InnerPackageModel;
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.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 OuterPackageDao implements IOuterPackageDao {

    @Autowired
    private EntityManager entityManager;

    @Override
    public List<InnerPackageModel> getPackageListByOuterPackageNo(String organizeCode, String outerPackageNo) {
        StringBuffer hql = new StringBuffer();
        hql.append(" select new " + InnerPackageModel.class.getName() + "(opd.workOrderNo, opd.innerPackageNo as packageNo , pack.partNo, pack.partNameRdd, opd.workCenterCode, pack.packageLabelTemplate) ");

        packHqlForQuerySnListByOuterPackageNo(hql);

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

        packParameterForQuerySnListByOuterPackageNo(query, organizeCode, outerPackageNo);

        return query.getResultList();
    }

    private void packHqlForQuerySnListByOuterPackageNo(StringBuffer hql) {
        hql.append(" from MesOuterPackageDetail as opd ");
        hql.append(" left join MesPackage as pack on (pack.packageNo = opd.innerPackageNo and pack.organizeCode = :organizeCode and pack.isValid = :isValid and pack.isDeleted = :isDeleted) ");
        hql.append(" where opd.organizeCode = :organizeCode ");
        hql.append(" and opd.isValid = :isValid ");
        hql.append(" and opd.isDeleted = :isDeleted ");
        hql.append(" and opd.outerPackageNo = :outerPackageNo ");
        hql.append(" and opd.bindStatus = :bindStatus ");
    }

    private void packParameterForQuerySnListByOuterPackageNo(Query query, String organizeCode, String outerPackageNo) {
        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.BIND_STATUS, MesPcnExtEnumUtil.PACKAGE_BIND_STATUS.BINGDING.getValue());
        query.setParameter(MesPcnExtConstWords.OUTER_PACKAGE_NO, outerPackageNo);
    }
}
