package com.example.iot_controlhost.utils.old;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import androidx.annotation.Nullable;

import com.example.iot_controlhost.utils.MyUtil;

public class DBOpenHelper extends SQLiteOpenHelper {
    public DBOpenHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    String[] names = {"HeatUpType", "wsd1Type", "wsd2Type", "nhType", "CO2Type", "DMWDType", "HWYKType", "JDQType", "GZType"};

    @Override
    public void onCreate(SQLiteDatabase db) {
        //创建数据库sql语句并执行
        //保存日志记录的表
        String sql = "create table Logs(id integer primary key autoincrement,TAG varchar(20),level varchar(20),datetime TEXT," +
                "msg varchar(1024),areacode varchar(20))";
        db.execSQL(sql);
        //保存蚕房设置参数的表
        sql = "create table areas(id integer primary key autoincrement,RoomNum integer," +
                "RoomId varchar(20),RoomName varchar(20), TargetHumidity varchar(20),TargetTemperature varchar(20)," +
                "ventilator_Open_interval varchar(20),ventilator_Close_interval varchar(20),datetime TEXT," +
                "flag int,Heating_Type int,Temperature_mode int,Humidity_mode int,ventilator_mode int,YXMS int," +
                "Port_1 integer,Port_2 integer,Port_3 integer,Port_4 integer,Port_5 integer,Port_6 integer," +
                "Port_7 integer,Port_8 integer,Port_9 integer,Port_10 integer,HeatUpType integer,wsd1Type integer," +
                "wsd2Type integer,nhType integer,CO2Type integer,DMWDType integer,HWYKType integer,JDQType integer," +
                "GZType integer,Temp_Warning varchar(20),Hum_Warning integer,CO2MAX integer,ControlType integer,QrcodeCreateArea varchar(100)," +
                "DLJCType integer,AQCJType integer,SWWSDType integer,KTWDType integer,HeatUpType_Arr integer,AreaType integer,HeatingMaxGear integer,HeatUpModel integer,DeviceModel integer)";
        db.execSQL(sql);
        //保存温湿度等环境历史数据的表
        sql = "create table historicaldata(id integer primary key autoincrement,Temperature_1 varchar(10)," +
                "Temperature_2 varchar(10),Humidity_1 varchar(10),Humidity_2 varchar(10)," +
                "AverageTemperature varchar(10),AverageHumidity varchar(10),Voltage varchar(10)," +
                "Ampere varchar(10),RealTimePower varchar(10),TotalEnergy varchar(10),Heating_Gear integer," +
                "Humidifier_Type integer, ventilator_Type integer,Air_Type integer,ventilator_Open_Time TEXT," +
                "ventilator_Close_Time TEXT,Light TEXT,YXMS integer,datetime TEXT,areacode varchar(20))";
        db.execSQL(sql);

        //保存能耗历史数据的表
        sql = "create table TotalEnergyHistoricaldata(id integer primary key autoincrement,TotalEnergy varchar(10) ,datetime TEXT,areacode varchar(20))";
        db.execSQL(sql);

        //保存设备相关配置数据的表
        sql = "create table DevicesSetting(id integer primary key autoincrement,SensorCOMName integer,ControlCOMName integer)";
        db.execSQL(sql);

        //保存共育记录的表
        sql = "create table GongYuRecord(id integer primary key autoincrement,CanJiID varchar(50),CanJiName varchar(50),PinZhongName varchar(20),NumberCount varchar(10),StartTime varchar(20)," +
                "EndtTime varchar(20),areacode varchar(20),CreateTime varchar(20),flag integer)";
        db.execSQL(sql);

        //保存智能模式下各蚕种所需要的温湿度标准的表
        sql = "create table Template(id integer primary key autoincrement,PinZhongName varchar(20),Day integer,TargetHumidity varchar(10),TargetTemperature varchar(10)," +
                "ventilator_Open_interval varchar(10),ventilator_Close_interval varchar(10),areacode varchar(20),CreateTime varchar(20),flag integer)";
        db.execSQL(sql);

        //保存定时任务的表
        sql = "create table ScheduledTasks(id integer primary key autoincrement,HOUR integer,MINUTE integer,SECOND,DeviceType integer," +
                "Execute integer,TaskNum integer,areacode varchar(20),CreateTime varchar(20),flag integer)";
        db.execSQL(sql);

        //插入系统初始化设置
        ContentValues cV = new ContentValues();
        cV.put("SensorCOMName", 0);   //默认传感器采集端口
        cV.put("ControlCOMName", 1);  //默认控制指令端口
        db.insert("DevicesSetting", null, cV);

        //插入房间的初始化数据
        for (int num = 1; num < 3; num++) {
            ContentValues cValue = new ContentValues();
            cValue.put("RoomNum", num);
            cValue.put("RoomId", "");
            cValue.put("RoomName", num + "号");
            cValue.put("TargetHumidity", 80);
            cValue.put("TargetTemperature", 26);
            cValue.put("Hum_Warning", 5);
            cValue.put("Temp_Warning", 0.5);
            cValue.put("CO2MAX", 1000);
            cValue.put("ventilator_Open_interval", 1);
            cValue.put("ventilator_Close_interval", 30);
            if (num == 1) cValue.put("flag", 1);
            else cValue.put("flag", 0);
            cValue.put("Temperature_mode", 1);
            cValue.put("Humidity_mode", 1);
            cValue.put("ventilator_mode", 1);
            cValue.put("YXMS", 3);
            cValue.put("datetime", MyUtil.getDateTime());
            cValue.put("ControlType", 0);
            cValue.put("wsd1Type", 1);
            cValue.put("wsd2Type", 2);
            cValue.put("DLJCType", 0);
            cValue.put("AQCJType", 0);
            cValue.put("SWWSDType", 0);
            cValue.put("KTWDType", 0);
            cValue.put("HeatUpType_Arr", 0);
            cValue.put("HeatingMaxGear", 5);
            cValue.put("HeatUpModel", 0);
            cValue.put("DeviceModel", 0);
            for (int i = 1; i < 11; i++) {
                String name = "Port_" + i;
                if (i == 1)
                    cValue.put(name, 4);
                else if (i == 2)
                    cValue.put(name, 3);
                else if (i == 3)
                    cValue.put(name, 1);
                else if (i == 4)
                    cValue.put(name, 1);
                else if (i == 5) {
                    cValue.put(name, 2);
                } else {
                    cValue.put(name, 0);
                }
            }
            for (int i = 0; i < names.length; i++) {
                if (i == 0 | i == 1 | i == 2)
                    cValue.put(names[i], 1);
                else cValue.put(names[i], 0);
            }
        }

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.d("TAG", "onUpgrade: 数据库更新了" + oldVersion + " -> " + newVersion);
        //添加控制模式字段
        if (!checkColumnExists(db, "areas", "ControlType")) {
            String sql = "alter table areas add ControlType int";
            db.execSQL(sql);
            ContentValues cv = new ContentValues();
            cv.put("ControlType", 0);
            db.update("areas", cv, "", null);
        }

        //调压模块地址
        if (!checkColumnExists(db, "areas", "HeatUpType_Arr")) {
            String sql = "alter table areas add HeatUpType_Arr integer";
            db.execSQL(sql);
            ContentValues cv = new ContentValues();
            cv.put("HeatUpType_Arr", 0);
            db.update("areas", cv, "", null);
        }


        //地暖控制模块型号
        if (!checkColumnExists(db, "areas", "HeatUpModel")) {
            String sql = "alter table areas add HeatUpModel integer";
            db.execSQL(sql);
            ContentValues cv = new ContentValues();
            cv.put("HeatUpModel", 0);
            db.update("areas", cv, "", null);
        }

        //继电器模块型号
        if (!checkColumnExists(db, "areas", "DeviceModel")) {
            String sql = "alter table areas add DeviceModel integer";
            db.execSQL(sql);
            ContentValues cv = new ContentValues();
            cv.put("DeviceModel", 0);
            db.update("areas", cv, "", null);
        }

        //QrcodeCreateArea
        //添加区域二维码连接地址字段
        if (!checkColumnExists(db, "areas", "QrcodeCreateArea")) {
            String sql = "alter table areas add QrcodeCreateArea varchar(100)";
            db.execSQL(sql);
        }

        //地暖允许最大挡位字段
        if (!checkColumnExists(db, "areas", "HeatingMaxGear")) {
            String sql = "alter table areas add HeatingMaxGear integer";
            db.execSQL(sql);
            ContentValues cv = new ContentValues();
            cv.put("HeatingMaxGear", 5);
            db.update("areas", cv, "", null);
        }

        if (!checkColumnExists(db, "TotalEnergyHistoricaldata", "TotalEnergy")) {
            //保存温湿度等环境历史数据的表
            String sql = "create table TotalEnergyHistoricaldata(id integer primary key autoincrement,TotalEnergy varchar(20) ,datetime TEXT,areacode varchar(20))";
            db.execSQL(sql);
        }

        if (!checkColumnExists(db, "ScheduledTasks", "id")) {
            //保存定时任务的表
            String sql = "create table ScheduledTasks(id integer primary key autoincrement,HOUR integer,MINUTE integer,SECOND,DeviceType integer," +
                    "Execute integer,TaskNum integer,areacode varchar(20),CreateTime varchar(20),flag integer)";
            db.execSQL(sql);
        }

        //保存设备相关配置参数的表
        if (!checkColumnExists(db, "DevicesSetting", "SensorCOMName")) {
            //保存设备相关配置数据的表
            String sql = "create table DevicesSetting(id integer primary key autoincrement,SensorCOMName integer,ControlCOMName integer)";
            db.execSQL(sql);
            //插入系统初始化设置
            ContentValues cV = new ContentValues();
            cV.put("SensorCOMName", 0);   //默认传感器采集端口
            cV.put("ControlCOMName", 1);  //默认控制指令端口
            db.insert("DevicesSetting", null, cV);
        }

        //电流检测字段
        if (!checkColumnExists(db, "areas", "DLJCType")) {
            String sql = "alter table areas add DLJCType integer";
            db.execSQL(sql);
            ContentValues cv = new ContentValues();
            cv.put("DLJCType", 0);
            db.update("areas", cv, "", null);
        }

        //氨气采集字段
        if (!checkColumnExists(db, "areas", "AQCJType")) {
            String sql = "alter table areas add AQCJType integer";
            db.execSQL(sql);
            ContentValues cv = new ContentValues();
            cv.put("AQCJType", 0);
            db.update("areas", cv, "", null);
        }

        //室外温湿度采集字段
        if (!checkColumnExists(db, "areas", "SWWSDType")) {
            String sql = "alter table areas add SWWSDType integer";
            db.execSQL(sql);
            ContentValues cv = new ContentValues();
            cv.put("SWWSDType", 0);
            db.update("areas", cv, "", null);
        }

        //空调温度采集字段
        if (!checkColumnExists(db, "areas", "KTWDType")) {
            String sql = "alter table areas add KTWDType integer";
            db.execSQL(sql);
            ContentValues cv = new ContentValues();
            cv.put("KTWDType", 0);
            db.update("areas", cv, "", null);
        }

        //共育记录表
        if (!checkColumnExists(db, "GongYuRecord", "CanJiName")) {
            //保存共育记录的表
            String sql = "create table GongYuRecord(id integer primary key autoincrement,CanJiID varchar(50),CanJiName varchar(50),PinZhongName varchar(20),NumberCount varchar(10),StartTime varchar(20)," +
                    "EndtTime varchar(20),areacode varchar(20),CreateTime varchar(20),flag integer)";
            db.execSQL(sql);
        }

        //共育记录表
        if (!checkColumnExists(db, "GongYuRecord", "CanJiID")) {
            //蚕季id
            String sql = "alter table GongYuRecord add CanJiID varchar(50)";
            db.execSQL(sql);
        }

        //保存智能模式下各蚕种所需要的温湿度标准的表
        if (!checkColumnExists(db, "Template", "PinZhongName")) {
            //保存智能模式下各蚕种所需要的温湿度标准的表
            String sql = "create table Template(id integer primary key autoincrement,PinZhongName varchar(20),Day integer,TargetHumidity varchar(10),TargetTemperature varchar(10)," +
                    "ventilator_Open_interval varchar(10),ventilator_Close_interval varchar(10),areacode varchar(20),CreateTime varchar(20),flag integer)";
            db.execSQL(sql);
        }

        //蚕房类别字段
        if (!checkColumnExists(db, "areas", "AreaType")) {
            String sql = "alter table areas add AreaType integer";
            db.execSQL(sql);
            ContentValues cv = new ContentValues();
            cv.put("AreaType", 0);
            db.update("areas", cv, "", null);
        }

        //二氧化碳最大值字段
        if (!checkColumnExists(db, "areas", "CO2MAX")) {
            String sql = "alter table areas add CO2MAX integer";
            db.execSQL(sql);
            ContentValues cv = new ContentValues();
            cv.put("CO2MAX", 1000);
            db.update("areas", cv, "", null);
        }

    }

    /**
     * 检查表里的某个字段是否存在
     *
     * @param db
     * @param tableName  表名
     * @param columnName 字段名
     * @return
     */
    private static boolean checkColumnExists(SQLiteDatabase db, String tableName, String columnName) {
        boolean result = false;
        Cursor cursor = null;
        try {
            cursor = db.rawQuery("select * from " + tableName, null);
            result = cursor != null && cursor.getColumnIndex(columnName) != -1;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != cursor && !cursor.isClosed()) {
                cursor.close();
            }
        }
        return result;
    }
}