import csv
import os
import pathlib
import sqlite3
import threading

import chardet
import pandas as pd
from PyQt5.QtCore import QThread

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 CyanloveConfigCSVExcelReadV2
from .cyanlove_config_read_intfile import readconfig

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

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


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

    def __init__(self, parent=None):
        super(cyanlove_import_csv_excel_sqlite, self).__init__(parent)
        self.export_thread = None
        self.tbname = ''
        self.setupUi(self)
        self.setFloating(True)
        self.setWindowFlags(QtCore.Qt.Dialog)  # 使对话框始终在前
        self.textEdit_biaotou_settext.setEnabled(False)
        self.mQgsFileWidget.setFilter("*.csv;*.xlsx")
        self.mQgsFileWidget.setStorageMode(2)  # 设置文件为多选
        self.checkBox_biaotou.stateChanged.connect(self.oncheckBox_biaotouChanged)  # 连接信号和槽函数
        self.pushButton.clicked.connect(self.import_csv_excel_sqlite_thread)

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

    def oncheckBox_biaotouChanged(self):
        if self.checkBox_biaotou.isChecked():
            self.textEdit_biaotou_settext.setEnabled(False)
        else:
            self.textEdit_biaotou_settext.setEnabled(True)

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

    def import_csv_excel_sqlite_thread(self):
        # 获取选择的文件路径,形成列表
        filepathlist = self.mQgsFileWidget.splitFilePaths(self.mQgsFileWidget.filePath())
        tbname = self.textEdit_tbname.toPlainText()
        print(filepathlist)
        if tbname.strip() == "":
            self.label_3.setText("没有表名称，请填写！")
            return
        if len(filepathlist) != 0:
            # 启动导出线程
            self.label_3.setText('开始读取中...')
            isfirstcol = self.checkBox_biaotou.isChecked()  # 是否第一行为表头字段
            isfirstfile_createsheet = self.checkBox_createsheet_firstfile.isChecked()  # 是否根据第一个文件创建表
            text_biaotou = self.textEdit_biaotou_settext.toPlainText()  # 表头字段
            self.export_thread = ExportThread(filepathlist, tbname, isfirstcol, isfirstfile_createsheet, text_biaotou)
            self.export_thread.updatelabel.connect(self.update_label)
            self.export_thread.start()



        else:
            self.label_2.setText("没有选择文件")


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

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

    def run(self):
        # 获取第一个文件扩展名
        file_path = pathlib.Path(self.filepaths[0])
        file_extension = file_path.suffix

        if file_extension.lower() == '.csv':

            reads = CyanloveConfigCSVExcelReadV2(self.filepaths,  self.tbname,
                                                 self.isfirstcol, self.isfirstfile_createsheet, self.strtext,
                                                 self.updatelabel)
            reads.readcsvpath()
        if file_extension.lower() == '.xlsx':
            reads = CyanloveConfigCSVExcelReadV2(self.filepaths,  self.tbname,
                                                 self.isfirstcol, self.isfirstfile_createsheet, self.strtext,
                                                 self.updatelabel)
            reads.readexcelpath()
