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

import cn.estsh.i3plus.ext.mes.pcn.api.busi.ISxThirdPartyDbParitySyncDispatchService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.ISxThirdPartyDbParitySyncSqlBuilderService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.SxThirdPartyDbCollectDataModel;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.mes.bean.MesObjectCfg;
import lombok.extern.slf4j.Slf4j;
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.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SxThirdPartyDbParitySyncDispatchService implements ISxThirdPartyDbParitySyncDispatchService {

    @Autowired
    private EntityManager entityManager;

    @Override
    public void exec(SxThirdPartyDbCollectDataModel collect, ISxThirdPartyDbParitySyncSqlBuilderService builderService) {

        if (CollectionUtils.isEmpty(collect.getMapList()) || StringUtils.isEmpty(collect.getParitySyncTableName())) return;

        List<MesObjectCfg> objectCfgList = collect.getObjectCfgList().stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getIsSave()) && CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue() == o.getIsSave())).collect(Collectors.toList());

        List<String> fieldList = CollectionUtils.isEmpty(objectCfgList) ? null :
                objectCfgList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getFieldCode()))).map(MesObjectCfg::getFieldCode).collect(Collectors.toList());

        for (Map<String, Object> map : collect.getMapList()) {
            if (null == map) continue;

            StringBuilder builder = builderService.builder(collect, map, fieldList);

            log.info("工厂{}第三方DB数据采集 --- CFG_CODE: {} EXEC --- CFG_KEY: {} EXEC ---EXEC PARITY SYNC --- SQL:{} ---", collect.getOrganizeCode(), collect.getCfgCode(), collect.getObjectCode(), builder.toString());

            Query insert = entityManager.createNativeQuery(builder.toString());

            insert.executeUpdate();
        }
    }
}
