package com.njcn.gather.storage.service.impl;

import com.njcn.gather.storage.mapper.TableGenMapper;
import com.njcn.gather.storage.service.TableGenService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class TableGenServiceImpl implements TableGenService {

    private final TableGenMapper tableGenMapper;

    private static final String[] AD_TABLE_PREFIXES = {
            "ad_non_harmonic_result_",
            "ad_harmonic_result_",
            "ad_non_harmonic_",
            "ad_harmonic_"
    };


    @Override
    public void genTable(String code, boolean isContrast) {
        tableGenMapper.genNonHarmonicTable(code, isContrast);
        // 添加索引
        tableGenMapper.genAdHarmonicTable("CREATE INDEX idx_ad_non_harmonic_" + code + "_dev_monitor_id" + " ON ad_non_harmonic_" + code + " (Dev_Monitor_Id);");
        tableGenMapper.genNonHarmonicResultTable(code, isContrast);
        // 添加索引
        tableGenMapper.genAdHarmonicTable("CREATE INDEX idx_ad_non_harmonic_result_" + code + "_dev_monitor_id" + " ON ad_non_harmonic_result_" + code + " (Dev_Monitor_Id);");

        StringBuilder A = new StringBuilder();
        StringBuilder B = new StringBuilder();
        StringBuilder C = new StringBuilder();
        for (int i = 1; i <= 50; i++) {
            if (i == 1) {
                A.append("A_Value_").append(i).append(" float(14,7)  NULL COMMENT 'A相基波',");
                B.append("B_Value_").append(i).append(" float(14,7)  NULL COMMENT 'B相基波',");
                C.append("C_Value_").append(i).append(" float(14,7)  NULL COMMENT 'C相基波',");
            } else {
                A.append("A_Value_").append(i).append(" float(14,7)  NULL COMMENT '").append(i).append("次A相谐波',");
                B.append("B_Value_").append(i).append(" float(14,7)  NULL COMMENT '").append(i).append("次B相谐波',");
                C.append("C_Value_").append(i).append(" float(14,7)  NULL COMMENT '").append(i).append("次C相谐波',");
            }
        }

        String sql = "CREATE TABLE AD_Harmonic_" + code + " (\n" +
                "    Dev_Monitor_Id CHAR(34) NOT NULL COMMENT '监测点Id',\n" +
                "    Time_Id DATETIME(3) NOT NULL COMMENT '时间',\n" +
                "    AD_Type CHAR(32) NOT NULL COMMENT '检测指标，字典表',\n" +
                "    Data_Type CHAR(32) NOT NULL COMMENT '数据指标，只有数据源为分钟统计时候才会使用（最大、最小、平均、CP95，默认平均值），字典表',\n" +
                "    Result_Flag int(1) NULL COMMENT '0不合格 1合格 4无法处理',\n" +
                A + B + C +
                (isContrast ?
                        "Id char(32) COLLATE utf8mb4_bin NOT NULL COMMENT '主键Id',\n" +
                                "Std_Dev_Monitor_Id CHAR(34) NOT NULL COMMENT '标准设备监测点Id',\n" +
                                "Num tinyint(1) unsigned DEFAULT 0 COMMENT '第几次检测',\n" +
                                "Flag tinyint(1) unsigned NOT NULL COMMENT '0表示被检设备数据，1表示标准设备数据',\n" +
                                "A_Value_0 float(14,7)  NULL COMMENT 'A相基波有效值',\n" +
                                "C_Value_0 float(14,7)  NULL COMMENT 'B相基波有效值',\n" +
                                "B_Value_0 float(14,7)  NULL COMMENT 'B相基波有效值',\n" +
                                "Wave_Num tinyint(1) unsigned DEFAULT null COMMENT '录波数据第几组',\n" +
                                "PRIMARY KEY (Id)\n"
                        :
                        "    Script_Id CHAR(32) NOT NULL COMMENT '检测脚本表Id',\n" +
                                "    Sort int(4) NOT NULL COMMENT '总检测脚本中的测试项序号',\n" +
                                "    PRIMARY KEY (Dev_Monitor_Id, Time_Id, Script_Id, Sort, AD_Type)\n"
                ) + ") COMMENT='谐波类原始数据表';";
        tableGenMapper.genAdHarmonicTable(sql);
        // 添加索引
        tableGenMapper.genAdHarmonicTable("CREATE INDEX idx_ad_harmonic_" + code + "_dev_monitor_id" + " ON ad_harmonic_" + code + " (Dev_Monitor_Id);");

        String a = A.toString().replaceAll("float\\(14,7\\)", "json");
        String b = B.toString().replaceAll("float\\(14,7\\)", "json");
        String c = C.toString().replaceAll("float\\(14,7\\)", "json");
        String sql2 = "CREATE TABLE AD_Harmonic_Result_" + code + " (\n" +
                "    Dev_Monitor_Id CHAR(34) NOT NULL COMMENT '监测点Id',\n" +
                "    Time_Id DATETIME(3) NULL COMMENT '时间',\n" +
                "    AD_Type CHAR(32) NOT NULL COMMENT '检测指标，字典表',\n" +
                "    Data_Type CHAR(32) NOT NULL COMMENT '数据指标，只有数据源为分钟统计时候才会使用（最大、最小、平均、CP95，默认平均值），字典表',\n" +
                "    Result_Flag int(1) NOT NULL COMMENT '1合格 2不合格 4无法处理',\n" +
                a + b + c +
                (isContrast ?
                        "Id char(32) COLLATE utf8mb4_bin NOT NULL COMMENT '主键Id',\n" +
                                "Std_Dev_Monitor_Id CHAR(34) NOT NULL COMMENT '标准设备监测点Id',\n" +
                                "Num tinyint(1) unsigned DEFAULT 0 COMMENT '第几次检测',\n" +
                                "Flag tinyint(1) unsigned DEFAULT NULL COMMENT '0表示被检设备数据，1表示标准设备数据',\n" +
                                "A_Value_0 json  NULL COMMENT 'A相基波有效值',\n" +
                                "B_Value_0 json  NULL COMMENT 'B相基波有效值',\n" +
                                "C_Value_0 json  NULL COMMENT 'B相基波有效值',\n" +
                                "Wave_Num tinyint(1) unsigned DEFAULT null COMMENT '录波数据第几组',\n" +
                                "PRIMARY KEY (Id)\n"
                        :
                        "    Script_Id CHAR(32) NOT NULL COMMENT '检测脚本表Id',\n" +
                                "    Sort int(4) NOT NULL COMMENT '总检测脚本中的测试项序号',\n" +
                                "    PRIMARY KEY (Dev_Monitor_Id,Script_Id, Sort, AD_Type)\n"
                ) + ") COMMENT='谐波类检测结果表';";
        tableGenMapper.genAdHarmonicTable(sql2);
        // 添加索引
        tableGenMapper.genAdHarmonicTable("CREATE INDEX idx_ad_harmonic_result_" + code + "_dev_monitor_id" + " ON ad_harmonic_result_" + code + " (Dev_Monitor_Id);");
    }

    @Override
    public void clearAdData(String code) {
        checkTableSuffix(code);
        for (String prefix : AD_TABLE_PREFIXES) {
            tableGenMapper.genAdHarmonicTable("DELETE FROM " + prefix + code);
        }
    }

    private void checkTableSuffix(String code) {
        if (code == null || !code.matches("[A-Za-z0-9_]+")) {
            throw new IllegalArgumentException("Invalid table suffix: " + code);
        }
    }

    @Override
    public void deleteTable(List<String> codeList) {
        StringBuilder sb = new StringBuilder();
        for (String code : codeList) {
            sb.append("ad_harmonic_").append(code)
                    .append(",ad_harmonic_result_").append(code)
                    .append(",ad_non_harmonic_").append(code)
                    .append(",ad_non_harmonic_result_").append(code).append(",");
        }
        sb.deleteCharAt(sb.length() - 1);
        tableGenMapper.genAdHarmonicTable("DROP TABLE IF EXISTS " + sb);
    }
}
