import csv
import os
import pathlib
import sqlite3
import threading

import chardet
import pandas as pd
from qgis.PyQt.QtCore import QThread
from PyQt5.QtWidgets import QFileDialog

from qgis.PyQt.QtCore import QVariant
from qgis.PyQt import QtWidgets, uic, QtCore
from qgis.PyQt.QtCore import pyqtSignal

from .cyanlove_config_csv_excel_read import CyanloveConfigCSVExcelRead
from .cyanlove_config_read_intfile import readconfig

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


class cyanlove_import_cell_neight_tosqlite(QtWidgets.QDockWidget, FORM_CLASS):
    closingPlugin = pyqtSignal()

    def __init__(self, parent=None):
        super(cyanlove_import_cell_neight_tosqlite, self).__init__(parent)
        self.export_thread = None
        self.tbname = ''
        self.setupUi(self)
        self.setFloating(True)
        self.setWindowFlags(QtCore.Qt.Dialog)  # 使对话框始终在前
        self.mQgsFileWidget.setFilter("*.csv;*.xlsx")
        self.pushButton.clicked.connect(self.import_csv_excel_sqlite_thread)

    def closeEvent(self, event):
        self.closingPlugin.emit()
        event.accept()

    def update_label(self, value):
        self.label_2.setText(value)  # 更新值

    def import_csv_excel_sqlite_thread(self):
        # 获取选择的文件路径

        filepath = self.mQgsFileWidget.filePath()
        if filepath:
            tbname = "TB_Neighbor4g"
            if self.radioButton_4G.isChecked():
                tbname = "TB_Neighbor4g"
            if self.radioButton_5G.isChecked():
                tbname = "TB_Neighbor5g"

            if tbname.strip():  # 检查是否为空（strip()去除前后空白）
                # 启动导出线程
                self.export_thread = ExportThread(filepath, tbname)
                self.export_thread.updatelabel.connect(self.update_label)
                self.export_thread.start()  # 启动线程
            else:
                self.label_2.setText("没有表名称，请填写！")
        else:
            self.label_2.setText("没有选择文件")


class ExportThread(QThread):
    updatelabel = pyqtSignal(str)  # 声明一个更新label新增信号

    def __init__(self, filepaths, tbnames=None):
        super().__init__()  # 初始化父类
        self.filepath = filepaths
        self.tbname = tbnames

    def run(self):
        # 获取文件扩展名
        file_path = pathlib.Path(self.filepath)
        file_extension = file_path.suffix

        if file_extension.lower() == '.csv':
            reads = CyanloveConfigCSVExcelRead(self.filepath, self.tbname, self.updatelabel)
            reads.readcsvpath()

        if file_extension.lower() == '.xlsx':
            reads = CyanloveConfigCSVExcelRead(self.filepath, self.tbname, self.updatelabel)
            reads.readexcelpath()
