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

import cn.estsh.i3plus.ext.mes.pcn.api.busi.ep.IEpBadCellDetailService;
import cn.estsh.i3plus.ext.mes.pcn.apiservice.dao.ep.IEpBadCellDetailDao;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesBadCellDetail;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.ep.EpQmsBadCellDetailModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesBadCellDetailRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.sqlpack.MesPcnExtHqlPack;
import cn.estsh.i3plus.pojo.base.bean.DdlPackBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wangjie
 * @version 1.0
 * @date 2021/1/13 9:28
 **/
@Slf4j
@Service
public class EpBadCellDetailService implements IEpBadCellDetailService {

    @Autowired
    private MesBadCellDetailRepository badCellDetailRepository;

    @Autowired
    private IEpBadCellDetailDao badCellDetailDao;

    @Override
    public List<EpQmsBadCellDetailModel> queryEpBadCellDetailList(EpQmsBadCellDetailModel badCellDetailModel, List<String> partNoList) {
        List<EpQmsBadCellDetailModel> resultList = null;

        int size = CollectionUtils.isEmpty(partNoList) ? 0 : partNoList.size() - 1;
        for (int i = 0; i <= size; i ++) {
            if (!CollectionUtils.isEmpty(partNoList)) {
                badCellDetailModel.setPartNo(partNoList.get(i));
            }

            List<MesBadCellDetail> detailList;
            if (StringUtils.isEmpty(badCellDetailModel.getLastDefectActionTimeStart()) && StringUtils.isEmpty(badCellDetailModel.getLastDefectActionTimeEnd())) {
                DdlPackBean packBean = MesPcnExtHqlPack.getEpBadCellDetail(badCellDetailModel);
                detailList = badCellDetailRepository.findByHqlWhere(packBean);
            } else {
                detailList = badCellDetailDao.queryEpQmsBadCellDetailList(badCellDetailModel);
            }

            if (!CollectionUtils.isEmpty(detailList)) {
                for (MesBadCellDetail badCellDetail : detailList) {
                    if (null == badCellDetail) {
                        continue;
                    }
                    EpQmsBadCellDetailModel result = new EpQmsBadCellDetailModel();
                    BeanUtils.copyProperties(badCellDetail, result);
                    if (CollectionUtils.isEmpty(resultList)) {
                        resultList = new ArrayList<>();
                    }
                    resultList.add(result);
                }
            }
        }
        return resultList;
    }

}
