import csv
import os

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

from qgis._core import QgsUnitTypes, QgsDistanceArea, QgsMapLayer, QgsWkbTypes
from qgis.utils import iface

from PyQt5 import QtCore,  QtWidgets

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


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

    def __init__(self, parent=None):
        super(cyanlove_calc_area, self).__init__(parent)

        self.export_thread = None
        self.iface = iface
        self.canvas = iface.mapCanvas()
        self.setupUi(self)
        self.setFloating(True)
        self.property_dict = None  # 存储搜索出来的名称，图元中心经纬度
        self.is_running = False  # 线程状态标志
        self.setWindowFlags(QtCore.Qt.Dialog)  # 使对话框始终在前
        # 设置为模态窗口
        # self.setWindowModality(QtCore.Qt.ApplicationModal)  # 或者使用 Qt.WindowModal
        self.btn_calc_area.clicked.connect(self.calc_area)

    # 调用内置算法，计算面积和周长
    def calc_area2(self):
        current_layer = self.mMapLayerComboBox.currentLayer()
        if current_layer is None or current_layer.type() != QgsMapLayer.VectorLayer:
            self.label_show.setText("选择的图层不是矢量图层！")
            return
        # 定义算法参数
        params = {
            'INPUT': current_layer,
            'uniqueGeometryType': 'yes',
            'CALC_METHOD': 2,  # 椭球体
            'OUTPUT': 'D:/方法2.csv'
        }
        # 运行算法
        result = processing.run("qgis:exportaddgeometrycolumns", params)

        # 输出结果信息
        print("Algorithm executed successfully!")
        print("Output file saved at:", result['OUTPUT'])

    def calc_area(self):
        options = QFileDialog.Options()  # 创建文件对话框选项
        options |= QFileDialog.ReadOnly  # 可以设置一些选项，例如只读
        csv_file_path, _ = QFileDialog.getSaveFileName(self,
                                                       "选择文件",
                                                       "",
                                                       "CSV文件 (*.csv);;所有文件 (*)",  # 可以添加其他过滤器
                                                       options=options)  # 传递 options 参数
        # 检查用户是否选择了文件
        if csv_file_path:
            current_layer = self.mMapLayerComboBox.currentLayer()
            if current_layer is None or current_layer.type() != QgsMapLayer.VectorLayer:
                self.label_show.setText("选择的图层不是矢量图层！")
                return
            # 确保使用现有的进度条
            self.progressBar.setRange(0, 100)  # 设置进度条范围
            self.progressBar.setValue(0)  # 初始化进度条值
            self.progressBar.show()  # 显示进度条 (如果之前是隐藏状态)
            geom_type = current_layer.wkbType()
            if geom_type in [QgsWkbTypes.Polygon, QgsWkbTypes.MultiPolygon]:
                # 启动导出线程
                self.export_thread = ExportThread(current_layer, csv_file_path)
                self.export_thread.progress.connect(self.update_progress)  # 连接信号到槽
                self.export_thread.finished.connect(self.export_finished)  # 导出完成后连接到槽
                self.export_thread.start()  # 启动线程
            else:
                self.label_show.setText("不是Polygon图层！")

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

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


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

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

    def run(self):
        context = QgsDistanceArea()
        # 创建处理上下文
        field_names = [f"{field.name()}" for field in self.selected_layer.fields()] + ['Area平方米']
        context.setEllipsoid('WGS84')
        total_features = self.selected_layer.featureCount()
        with open(self.csv_file_path, mode='w', newline='', encoding='gbk') as csv_file:
            writer = csv.writer(csv_file)
            writer.writerow(field_names)
            for index, feature in enumerate(self.selected_layer.getFeatures()):
                try:
                    row = []
                    for field_name in field_names[:-1]:  # 不包括 WKT_BJ
                        value = feature[field_name]  # 获取每个字段的值
                        row.append(f'{value}')  # 在每个值两边添加双引号
                    geometry = feature.geometry()
                    if geometry:
                        areauint = context.convertAreaMeasurement(context.measureArea(geometry),
                                                                  QgsUnitTypes.AreaSquareMeters)
                        row.append(f'{areauint}')  # 添加面积
                    # 发送进度更新
                    writer.writerow(row)

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

                except Exception as e:
                    pass


        # 输出结果信息
        print("计算完毕!")
