import os
import sqlite3

from PyQt5.QtCore import QThread, QVariant
from PyQt5.QtWidgets import QButtonGroup
from qgis.PyQt import QtWidgets, uic, QtCore
from qgis.PyQt.QtCore import pyqtSignal

from .cyanlove_config_read_intfile import readconfig

FORM_CLASS, _ = uic.loadUiType(os.path.join(
    os.path.dirname(__file__), 'cyanlove_import_layer_tosqlite_base.ui'))

# 配置文件int格式
pathsaveint = os.path.join(os.path.dirname(__file__), 'config.ini')


class cyanlove_import_layerattribute_tosqlite(QtWidgets.QDockWidget, FORM_CLASS):

    def __init__(self, parent=None):
        super(cyanlove_import_layerattribute_tosqlite, self).__init__(parent)
        self.export_thread = None
        self.setupUi(self)
        self.setFloating(True)
        self.setWindowFlags(QtCore.Qt.Dialog)  # 使对话框始终在前
        self.btn_import_sqlite.clicked.connect(self.import_layer_tosqlite)
        self.checkBox_4g.toggled.connect(self.on_4g_toggled)
        self.checkBox_5g.toggled.connect(self.on_5g_toggled)
        self.checkBox_4g.stateChanged.connect(self.update_textedit_state)
        self.checkBox_5g.stateChanged.connect(self.update_textedit_state)

    def update_progress(self, value):
        self.progressBar.setValue(value)  # 更新进度条的值

    def on_4g_toggled(self, checked):
        if checked:
            self.checkBox_5g.setChecked(False)

    def on_5g_toggled(self, checked):
        if checked:
            self.checkBox_4g.setChecked(False)

    def update_textedit_state(self):
        # 获取当前两个复选框的状态
        check4g = self.checkBox_4g.isChecked()
        check5g = self.checkBox_5g.isChecked()

        # 如果两个都没选中，启用textEdit
        if not check4g and not check5g:
            self.textEdit.setEnabled(True)
        else:
            self.textEdit.setEnabled(False)

    def export_finished(self):
        print("导入完成！")
        self.label_show.setText('导入完成！')
        self.progressBar.setValue(100)

    def import_layer_tosqlite(self):
        tablename = self.textEdit.toPlainText()
        if self.checkBox_4g.isChecked():
            tablename = "TB_Cell4g"
        if self.checkBox_5g.isChecked():
            tablename = "TB_Cell5g"
        selected_layer = self.mMapLayerComboBox.currentLayer()
        if tablename == "":
            self.label_show.setText('没有输入表名称！')
            return
        if selected_layer is not None:
            # 开始导入
            self.label_show.setText('开始导入.....')
            # 确保使用现有的进度条
            self.progressBar.setRange(0, 100)  # 设置进度条范围
            self.progressBar.setValue(0)  # 初始化进度条值
            self.progressBar.show()  # 显示进度条 (如果之前是隐藏状态)
            # 启动导出线程
            self.export_thread = ExportThread(selected_layer, tablename)
            self.export_thread.progress.connect(self.update_progress)  # 连接信号到槽
            self.export_thread.finished.connect(self.export_finished)  # 导出完成后连接到槽
            self.export_thread.start()  # 启动线程


class ExportThread(QThread):
    progress = pyqtSignal(int)  # 声明一个信号

    def __init__(self, selected_layer, tablename):
        super().__init__()
        self.selected_layer = selected_layer
        self.tablename = tablename

    def run(self):
        # Get field names and initialize a list for creating table fields
        field_definitions = []
        field_names = [f"[{field.name()}]" for field in self.selected_layer.fields()]
        if self.tablename == "TB_Cell4g" or self.tablename == "TB_Cell5g":
            field_names.append("[边界P]")
        # Determine field types and prepare field definitions for the SQL CREATE TABLE statement
        for field in self.selected_layer.fields():
            field_type = field.type()
            if field_type in (QVariant.Int, QVariant.Double):
                field_definitions.append(f"[{field.name()}] DOUBLE")
            else:
                field_definitions.append(f"[{field.name()}] TEXT")
        if self.tablename == "TB_Cell4g" or self.tablename == "TB_Cell5g":
            field_definitions.append(f"[边界P] TEXT")
        # Get total feature count for progress calculation
        total_features = self.selected_layer.featureCount()
        db_path = readconfig.read_ini_file('Settings', 'sqlite_栅格分析')

        # Connect to SQLite database
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()

        # Drop table if it exists
        cursor.execute(f"DROP TABLE IF EXISTS [{self.tablename}]")

        # Create table with fields according to their types
        create_table_query = f"CREATE TABLE [{self.tablename}] ({', '.join(field_definitions)})"
        cursor.execute(create_table_query)

        # Start a transaction
        conn.execute('BEGIN TRANSACTION')

        try:
            for index, feature in enumerate(self.selected_layer.getFeatures()):
                row = []
                try:
                    for field in self.selected_layer.fields():
                        value = feature[field.name()]
                        # Check for None (null values) and handle accordingly
                        row.append(f'"{value}"' if value is not None else 'NULL')
                    if self.tablename == "TB_Cell4g" or self.tablename == "TB_Cell5g":
                        boundary_wkt = feature.geometry().asWkt()
                        row.append(f'"{boundary_wkt}"' if boundary_wkt is not None else '')
                    # Insert row into the database
                    insert_query = f"INSERT INTO [{self.tablename}] ({', '.join(field_names)}) VALUES ({', '.join(row)})"
                    cursor.execute(insert_query)

                except Exception as e:
                    print(f"Error processing feature {index}: {str(e)}")

                # Send progress update
                progress_value = int((index + 1) / total_features * 100)
                self.progress.emit(progress_value)

            # Commit the transaction
            conn.commit()

        except Exception as e:
            print(f"Transaction failed: {str(e)}")
            conn.rollback()  # Rollback in case of error

        finally:
            cursor.close()
            conn.close()
