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


import cn.estsh.i3plus.ext.mes.apiservice.dao.IPartExtDao;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesPartExt;
import cn.estsh.i3plus.ext.mes.pojo.model.MesPartExtModel;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtConstWords;
import cn.estsh.i3plus.pojo.base.common.Pager;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

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

/**
 * @Description : MES物料信息Dao
 * @Reference :
 * @Author : xiangming.liao
 * @CreateDate : 2020-02-21
 * @Modify:
 **/
@Service
public class PartExtDao implements IPartExtDao {

    @Autowired
    private EntityManager entityManager;


    @Override
    public int queryPartByPagerCount(MesPartExt partExt) {
        StringBuffer hql = new StringBuffer();
        hql.append(" select count(pe.id) ");

        packHqlForQueryPart(hql, partExt);

        Query query = entityManager.createQuery(hql.toString(), Long.class);

        packParameterForQueryPart(query, partExt);

        return ((Long) query.getSingleResult()).intValue();
    }

    private void packHqlForQueryPart(StringBuffer hql, MesPartExt partExt) {
        hql.append(" from MesPartExt as pe ");
        hql.append(" left join MesFile as f on (pe.fileId = f.id and f.organizeCode = :organizeCode and f.isValid = :isValid and f.isDeleted = :isDeleted) ");
        hql.append(" where pe.organizeCode = :organizeCode ");
        hql.append(" and pe.isValid = :isValid ");
        hql.append(" and pe.isDeleted = :isDeleted ");
        if (!StringUtils.isEmpty(partExt.getPartNo())) {
            hql.append(" and pe.partNo = :partNo ");
        }
        if (!StringUtils.isEmpty(partExt.getPartName())) {
            hql.append(" and pe.partName like :partName ");
        }
        if (!StringUtils.isEmpty(partExt.getCategoryCode1())) {
            hql.append(" and pe.categoryCode1 = :categoryCode1 ");
        }
        if (!StringUtils.isEmpty(partExt.getCategoryCode2())) {
            hql.append(" and pe.categoryCode2 = :categoryCode2 ");
        }
        if (!StringUtils.isEmpty(partExt.getCategoryCode3())) {
            hql.append(" and pe.categoryCode3 = :categoryCode3 ");
        }
        if(partExt.getPackNoPrintTimes() != null){
            hql.append(" and pe.packNoPrintTimes = :packNoPrintTimes ");
        }
        if(partExt.getSnPrintTimes() != null){
            hql.append(" and pe.snPrintTimes = :snPrintTimes ");
        }
        if(partExt.getSnPrintColumnNumber() != null){
            hql.append(" and pe.snPrintColumnNumber = :snPrintColumnNumber ");
        }
    }
    private void packParameterForQueryPart(Query query, MesPartExt partExt) {
        query.setParameter(MesExtConstWords.ORGANIZE_CODE, partExt.getOrganizeCode());
        query.setParameter(MesExtConstWords.IS_VALID, partExt.getIsValid());
        query.setParameter(MesExtConstWords.IS_DELETED, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue());
        if (!StringUtils.isEmpty(partExt.getPartNo())) {
            query.setParameter(MesExtConstWords.PART_NO, partExt.getPartNo());
        }
        if (!StringUtils.isEmpty(partExt.getPartName())) {
            query.setParameter(MesExtConstWords.PART_NAME, "%" + partExt.getPartName() + "%");
        }
        if (!StringUtils.isEmpty(partExt.getCategoryCode1())) {
            query.setParameter(MesExtConstWords.CATEGORY_CODE1, partExt.getCategoryCode1());
        }
        if (!StringUtils.isEmpty(partExt.getCategoryCode2())) {
            query.setParameter(MesExtConstWords.CATEGORY_CODE2, partExt.getCategoryCode2());
        }
        if (!StringUtils.isEmpty(partExt.getCategoryCode3())) {
            query.setParameter(MesExtConstWords.CATEGORY_CODE3, partExt.getCategoryCode3());
        }
        if(partExt.getPackNoPrintTimes() != null){
            query.setParameter(MesExtConstWords.PACK_NOPRINT_TIMES, partExt.getPackNoPrintTimes());
        }
        if(partExt.getSnPrintTimes() != null){
            query.setParameter(MesExtConstWords.SN_PRINT_TIMES, partExt.getSnPrintTimes());
        }
        if(partExt.getSnPrintColumnNumber() != null){
            query.setParameter(MesExtConstWords.SN_PRINT_COLUMN_NUMBER, partExt.getSnPrintColumnNumber());
        }
    }

    @Override
    public List<MesPartExtModel> queryPartByPager(MesPartExt partExt, Pager pager) {
        StringBuffer hql = new StringBuffer();
        hql.append(" select new " + MesPartExtModel.class.getName() + "(pe.id, pe.partNo, pe.partName, pe.briefText, pe.unit, " +
                " pe.categoryCode1, pe.categoryCode2, pe.categoryCode3, pe.processMatchType, pe.productMatchType, pe.packageMatchType, pe.qty2, " +
                " pe.pptCode, pe.colorCode, pe.colorName, pe.salesTo, pe.isOqc, pe.isCreateSn, pe.isPSParts, pe.standardWork, " +
                " pe.japanDesc, pe.goodsCode, pe.prefix, pe.qualityAssureCode, pe.identifyCode, pe.snLastCode, pe.fileId, " +
                " pe.fileOriginName, pe.uploadDatetime, pe.organizeCode, pe.createUser, pe.createDatetime, pe.modifyUser, pe.modifyDatetime, " +
                " f.fileUrl, pe.packNoPrintTimes, pe.snPrintTimes, pe.bigProcessMatchType, pe.snPrintColumnNumber, pe.isPrintQualityAssureIndia , pe.shiXiangDiCode," +
                " pe.model , pe.productNumber , pe.snPackagePrintColumnNumber , pe.bigPackageMatchType , pe.isRepairWorkReport, pe.partPrice, pe.isManualReport ) ");
        packHqlForQueryPart(hql, partExt);

        hql.append(" order by pe.modifyDatetime desc ");
        Query query = entityManager.createQuery(hql.toString(), MesPartExtModel.class);

        packParameterForQueryPart(query, partExt);

        query.setMaxResults(pager.getPageSize());
        if (pager.getCurrentPage() == 0) {
            pager.setCurrentPage(1);
        }
        query.setFirstResult(pager.getCurrentPage() * pager.getPageSize() - pager.getPageSize());
        return query.getResultList();
    }

    @Override
    public Map<String, Double> queryPartExtStandardWorkMap(String organizeCode) {
        Map<String, Double> resultMap = new HashMap<>();
        StringBuffer hql = new StringBuffer();
        hql.append(" select pe.part_no_ext, pe.standard_work ");
        hql.append(" from mes_part_ext pe where pe.organize_code_ext = :organizeCode ");
        Query query = entityManager.createNativeQuery(hql.toString());
        query.setParameter(MesExtConstWords.ORGANIZE_CODE, organizeCode);
        List list = query.getResultList();
        if (!CollectionUtils.isEmpty(list)) {
            list.stream().forEach(o -> {
                Object[] cellArr = (Object[]) o;
                if (null != cellArr && cellArr.length == 2 && !StringUtils.isEmpty(cellArr[0]) && !StringUtils.isEmpty(cellArr[1])) {
                    resultMap.put(cellArr[0].toString(), Double.parseDouble(cellArr[1].toString()));
                }
            });
        }
        return resultMap;
    }

    @Override
    public Map<String, String> queryPartExtStandardWorkStrMap(String organizeCode) {
        Map<String, String> resultMap = new HashMap<>();
        StringBuffer hql = new StringBuffer();
        hql.append(" select pe.part_no_ext, pe.standard_work ");
        hql.append(" from mes_part_ext pe where pe.organize_code_ext = :organizeCode ");
        Query query = entityManager.createNativeQuery(hql.toString());
        query.setParameter(MesExtConstWords.ORGANIZE_CODE, organizeCode);
        List list = query.getResultList();
        if (!CollectionUtils.isEmpty(list)) {
            list.stream().forEach(o -> {
                Object[] cellArr = (Object[]) o;
                if (null != cellArr && cellArr.length == 2 && !StringUtils.isEmpty(cellArr[0]) && !StringUtils.isEmpty(cellArr[1])) {
                    resultMap.put(cellArr[0].toString(), cellArr[1].toString());
                }
            });
        }
        return resultMap;
    }

    @Override
    public Map<String, String> queryPartCategoryCode3Map(String organizeCode, String categoryCode3) {
        Map<String, String> resultMap = new HashMap<>();
        StringBuffer hql = new StringBuffer();
        hql.append(" select p.part_no, p.category_code3 ");
        hql.append(" from mes_part p where p.organize_code = :organizeCode ");
        if (!StringUtils.isEmpty(categoryCode3)) hql.append(" and p.category_code3 = :categoryCode3 ");
        Query query = entityManager.createNativeQuery(hql.toString());
        query.setParameter(MesExtConstWords.ORGANIZE_CODE, organizeCode);
        if (!StringUtils.isEmpty(categoryCode3)) query.setParameter(MesExtConstWords.CATEGORY_CODE3, categoryCode3);
        List list = query.getResultList();
        if (!CollectionUtils.isEmpty(list)) {
            list.stream().forEach(o -> {
                Object[] cellArr = (Object[]) o;
                if (null != cellArr && cellArr.length == 2 && !StringUtils.isEmpty(cellArr[0]) && !StringUtils.isEmpty(cellArr[1])) {
                    resultMap.put(cellArr[0].toString(), cellArr[1].toString());
                }
            });
        }
        return resultMap;
    }

    @Override
    public Map<String, String> queryPartCategoryCode3Map(String organizeCode, Map<String, String> categoryCode3Map) {
        Map<String, String> resultMap = new HashMap<>();
        StringBuffer hql = new StringBuffer();
        hql.append(" select p.part_no, p.category_code3 ");
        hql.append(" from mes_part p where p.organize_code = :organizeCode ");
        Query query = entityManager.createNativeQuery(hql.toString());
        query.setParameter(MesExtConstWords.ORGANIZE_CODE, organizeCode);
        List list = query.getResultList();
        if (!CollectionUtils.isEmpty(list)) {
            list.stream().forEach(o -> {
                Object[] cellArr = (Object[]) o;
                if (null != cellArr && cellArr.length == 2 && !StringUtils.isEmpty(cellArr[0]) && (StringUtils.isEmpty(cellArr[1]) || categoryCode3Map.containsKey(cellArr[1]))) {
                    resultMap.put(cellArr[0].toString(), !StringUtils.isEmpty(cellArr[1]) ? cellArr[1].toString() : MesExtConstWords.EMPTY);
                }
            });
        }
        return resultMap;
    }

    @Override
    public Map<String, Double> queryPartExtPartPriceMap(String organizeCode) {
        Map<String, Double> resultMap = new HashMap<>();
        StringBuffer hql = new StringBuffer();
        hql.append(" select pe.part_no_ext, pe.part_price ");
        hql.append(" from mes_part_ext pe where pe.organize_code_ext = :organizeCode ");
        Query query = entityManager.createNativeQuery(hql.toString());
        query.setParameter(MesExtConstWords.ORGANIZE_CODE, organizeCode);
        List list = query.getResultList();
        if (!CollectionUtils.isEmpty(list)) {
            list.stream().forEach(o -> {
                Object[] cellArr = (Object[]) o;
                if (null != cellArr && cellArr.length == 2 && !StringUtils.isEmpty(cellArr[0]) && !StringUtils.isEmpty(cellArr[1])) {
                    resultMap.put(cellArr[0].toString(), Double.parseDouble(cellArr[1].toString()));
                }
            });
        }
        return resultMap;
    }

}
