package com.muyu.data.processing.strategy.leaves;

import com.muyu.common.iotdb.config.IotDBSessionConfig;
import com.muyu.data.processing.domain.BasicData;
import java.util.HashMap;

import com.muyu.data.processing.domain.Temporary2;
import com.muyu.data.processing.strategy.StrategyHandler;
import com.muyu.data.processing.strategy.abstractStrategyRouter;
import com.muyu.data.processing.strategy.core.RoutingStrategy;
import lombok.extern.slf4j.Slf4j;
import org.apache.iotdb.rpc.IoTDBConnectionException;
import org.apache.iotdb.rpc.StatementExecutionException;
import org.springframework.stereotype.Component;

/**
 * 数据持久化
 * 车辆数据进行持久化
 * @Author: 胡杨
 * @Name: BasicStrategy
 * @Description: 责任树 - 数据持久化
 * @CreatedDate: 2024/9/30 下午7:24
 * @FilePath: com.muyu.data.processing.strategy.branch
 */

@Slf4j
@Component
public class DataStorageStrategy extends abstractStrategyRouter<HashMap<String, BasicData>, Temporary2>
        implements StrategyHandler<HashMap<String, BasicData>, Temporary2> {

    @Override
    protected StrategyMapper<HashMap<String, BasicData>, Temporary2> registerStrategy() {
        log.info("数据持久化分支已完成。。。");
        return param -> new RoutingStrategy();
    }

    @Override
    public Temporary2 apply(HashMap<String, BasicData> basicDataMap) {
        // 执行持久化方法
        addCarData(basicDataMap);
        return applyStrategy(basicDataMap);
    }

    private void addCarData(HashMap<String, BasicData> hashMap) {
        StringBuilder sql = new StringBuilder("insert into root.one.");
        sql.append(hashMap.get("firmCode").getValue())
                .append(".")
                .append(hashMap.get("VIN").getValue())
                .append("(");
        hashMap.remove("firmCode");
        hashMap.remove("VIN");
        StringBuilder keys = new StringBuilder();
        StringBuilder values = new StringBuilder();
        hashMap.keySet().forEach(key -> {
            if (hashMap.get(key) != null) {
                keys.append(key).append(",");
                if ("String".equals(hashMap.get(key).getType())) {
                    values.append("'")
                            .append(hashMap.get(key).getValue())
                            .append("'")
                            .append(",");
                }else {
                    values.append(hashMap.get(key).getValue())
                            .append(",");
                }
            }
        });
        sql.append(keys.substring(0, keys.length() - 1))
                .append(") values (")
                .append(values.substring(0, values.length() - 1))
                .append(")");
        try {
            new IotDBSessionConfig().getSessionPool().executeNonQueryStatement(sql.toString());
        } catch (StatementExecutionException e) {
            throw new RuntimeException(e);
        } catch (IoTDBConnectionException e) {
            throw new RuntimeException(e);
        }
        log.info("成功执行sql语句: [{}]", sql);
    }
}
