package com.rehome.mqttclienttemperature.service.impl;

import com.google.gson.Gson;
import com.rehome.mqttclienttemperature.datasource.DataSource;
import com.rehome.mqttclienttemperature.dto.ResponseDto;
import com.rehome.mqttclienttemperature.entity.Temperature;
import com.rehome.mqttclienttemperature.service.OracleTemperatureService;
import com.rehome.mqttclienttemperature.utils.JdbcUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
@Service
public class OracleTemperatureServiceImpl implements OracleTemperatureService {
    public static DataSource ds = new DataSource();
    static {
        //配置数据源
        ds.setId("200");
        ds.setName("oracle");
        ds.setUrl("jdbc:oracle:thin:@192.168.3.9:1521/orcl");
        ds.setUsername("appserver");
        ds.setPassword("appserver");
        ds.setDriver("oracle.jdbc.driver.OracleDriver");
    }

    @Override
    public ResponseDto saveTemperature(Temperature temperature) {
        // 自定义一个线程池,内部包含8个线程
        ExecutorService customPool = Executors.newFixedThreadPool(8);
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            //SYSTIMESTAMP
            //CURRENT_TIMESTAMP
            String sql = "insert into temperature(id,temperature, humidity, data_date, data_hour, data_minute, topic, location_desc, create_date) values(temperature_seq_appserver.NEXTVAL, ?, ?, ?, ?, ?, ?, ?, SYSTIMESTAMP)";
            List<Object> jdbcParamValues = new ArrayList<>();

            jdbcParamValues.add(temperature.getTemperature());
            jdbcParamValues.add(temperature.getHumidity());
            jdbcParamValues.add(temperature.getDataDate());
            jdbcParamValues.add(temperature.getDataHour());
            jdbcParamValues.add(temperature.getDataMinute());
            jdbcParamValues.add(temperature.getTopic());
            jdbcParamValues.add(temperature.getLocationDesc());
            //jdbcParamValues.add(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(temperature.getCreateDate()));

            Gson gson = new Gson();
            ResponseDto responseDto = JdbcUtil.executeSql(ds, sql, jdbcParamValues);
            String dbQueryResult = gson.toJson(responseDto);
            log.info(dbQueryResult);
            jdbcParamValues.clear();

            if(responseDto.isSuccess()){
                return "数据库同步成功";
            }
            return "数据库同步失败";
        }, customPool);

        ResponseDto responseDto = future.thenApply(result -> {
            log.info("Result: " + result);
            if("数据库同步成功".equals(result)){
                return ResponseDto.successWithMsg(result);
            }
            return ResponseDto.fail(result);
        }).join();
        return responseDto;
    }
}
