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

import cn.estsh.i3plus.ext.mes.pcn.api.busi.ISxThirdPartyDbParitySyncSqlBuilderService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.SxThirdPartyDbCollectDataModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class SxThirdPartyDbParitySyncSqlBuilderSqlServerService implements ISxThirdPartyDbParitySyncSqlBuilderService {

    @Override
    public StringBuilder builder(SxThirdPartyDbCollectDataModel collect, Map<String, Object> map, List<String> fieldList) {
        StringBuilder sqlBuilder = new StringBuilder();
        StringBuilder fieldBuilder = new StringBuilder();
        StringBuilder valueBuilder = new StringBuilder();

        sqlBuilder.append(" INSERT INTO [").append(collect.getParitySyncTableName()).append("](");
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (null == entry || !fieldList.contains(entry.getKey())) continue;

            if (!StringUtils.isEmpty(fieldBuilder.toString())) fieldBuilder.append(", ");
            if (!StringUtils.isEmpty(valueBuilder.toString())) valueBuilder.append(", ");

            fieldBuilder.append("[").append(entry.getKey()).append("]");

            if (StringUtils.isEmpty(entry.getValue())) {
                valueBuilder.append("NULL");
            } else {
                if (entry.getValue() instanceof String) {
                    valueBuilder.append("\'").append(entry.getValue()).append("\'");
                } else {
                    valueBuilder.append(entry.getValue());
                }
            }
        }

        sqlBuilder.append(fieldBuilder).append(")").append(" VALUES (").append(valueBuilder).append(") ");

        return sqlBuilder;
    }
}
