# -*- coding: utf-8 -*-
"""
/***************************************************************************
 TFB_Tools3
                                 A QGIS plugin
 圖資操作處理工具
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2019-06-20
        git sha              : $Format:%H$
        copyright            : (C) 2019 by FCU-GIS
        email                : gis.tw
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
"""
# from PyQt5.QtCore import QSettings, QTranslator, qVersion, QCoreApplication, Qt, QFileInfo
# from PyQt5.QtGui import QIcon
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
# Initialize Qt resources from file resources.py
from .resources import *

from qgis.core import *
from qgis.gui import *

# Import the code for the dialog
import getpass
import urllib.request
from urllib.request import urlopen
from xml.dom.minidom import *
import sys 
import base64
import csv
import glob
import xml

from .MouseClick import MouseClick
import platform
import uuid
from .getImg import *

import numpy as np
# from PIL import Image
# from PIL import ExifTags
# from PIL.ExifTags import TAGS, GPSTAGS
from datetime import datetime, timedelta
import xml.dom.minidom as xmini
import json
from math import sin, cos, sqrt, atan2, radians

# Import the code for the DockWidget
from .TFB_Tools3_dockwidget import *
import os.path
import os

# Import python module
CHECK_MODULE = ''
try:
    import exifread
    CHECK_MODULE = 'exifread'
except:
    pass

try:
    if CHECK_MODULE == '':
        from PIL import Image
        from PIL import ExifTags
        from PIL.ExifTags import TAGS, GPSTAGS
        CHECK_MODULE = 'PIL'
except:
    pass

rootPath = os.path.dirname(__file__)+'\\'
GPXtempPath = rootPath + 'gpxTemp.gpx'
geojsonPath = rootPath + 'geojsonTemp.geojson'
# rootPath = 'C:\\Users\\' + getpass.getuser() + '\\AppData\\Roaming\\QGIS\\QGIS3\\profiles\\default\\python\\plugins\\TFB-Tools3\\'
# GPXtempPath = 'C:\\Users\\' + getpass.getuser() + '\\AppData\\Roaming\\QGIS\\QGIS3\\profiles\\default\\python\\plugins\\TFB-Tools3\\gpxTemp.gpx'
# geojsonPath = 'C:\\Users\\' + getpass.getuser() + '\\AppData\\Roaming\\QGIS\\QGIS3\\profiles\\default\\python\\plugins\\TFB-Tools3\\geojsonTemp.geojson'    
dataPath = ''
filePathList = []

class TFB_Tools3:
    """QGIS Plugin Implementation."""

    def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface        
        self.canvas = iface.mapCanvas()

        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)

        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'TFB_Tools3_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)

            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&TFB_Tools3')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'TFB_Tools3')
        self.toolbar.setObjectName(u'TFB_Tools3')

        #print "** INITIALIZING TFB_Tools3"

        self.pluginIsActive = False
        self.dockwidget = None
        # Position dialog
        self.positioningDia = Ui_positioning(self.iface)
        self.positioningDia.comboBox_11.hide()
        self.positioningDia.comboBox_12.hide()
        self.positioningDia.label_8.hide()
        self.positioningDia.label_9.hide()

        self.inforDia = Ui_infor(self.iface)
        # Cadastre dialog 載入地籍圖
        self.cadastreDia = Ui_cadastre(self.iface)      

        
        self.WMTSDia = Ui_WMTS(self.iface)
        self.addWMTSDia = Ui_addWMTS(self.iface)
        self.csv2shpDia = Ui_csv2shp(self.iface)
        self.gpx2shpDia = Ui_gpx2shp(self.iface)
        self.exportSHPDia = Ui_exportSHP(self.iface)
        self.photogpxDia = Ui_photogpx(self.iface)
        self.ImportPhotosDia = ImportPhotosDialog(self.iface)
        self.gpxList = []
        self.GpxreviseDia = Ui_GPXrevise(self.iface)
        self.wmsDia = Ui_wms(self.iface)
        self.getImg = getImgFromFrame(self.iface)

        
        
        

    # noinspection PyMethodMayBeStatic
    def tr(self, message):
        """Get the translation for a string using Qt translation API.

        We implement this ourselves since we do not inherit QObject.

        :param message: String for translation.
        :type message: str, QString

        :returns: Translated version of message.
        :rtype: QString
        """
        # noinspection PyTypeChecker,PyArgumentList,PyCallByClass
        return QCoreApplication.translate('TFB_Tools3', message)


    def add_action(
        self,
        icon_path,
        text,
        callback,
        enabled_flag=True,
        add_to_menu=True,
        add_to_toolbar=True,
        status_tip=None,
        whats_this=None,
        parent=None):
        """Add a toolbar icon to the toolbar.

        :param icon_path: Path to the icon for this action. Can be a resource
            path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
        :type icon_path: str

        :param text: Text that should be shown in menu items for this action.
        :type text: str

        :param callback: Function to be called when the action is triggered.
        :type callback: function

        :param enabled_flag: A flag indicating if the action should be enabled
            by default. Defaults to True.
        :type enabled_flag: bool

        :param add_to_menu: Flag indicating whether the action should also
            be added to the menu. Defaults to True.
        :type add_to_menu: bool

        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the toolbar. Defaults to True.
        :type add_to_toolbar: bool

        :param status_tip: Optional text to show in a popup when mouse pointer
            hovers over the action.
        :type status_tip: str

        :param parent: Parent widget for the new action. Defaults None.
        :type parent: QWidget

        :param whats_this: Optional text to show in the status bar when the
            mouse pointer hovers over the action.

        :returns: The action that was created. Note that the action is also
            added to self.actions list.
        :rtype: QAction
        """

        icon = QIcon(icon_path)
        action = QAction(icon, text, parent)
        action.triggered.connect(callback)
        action.setEnabled(enabled_flag)

        if status_tip is not None:
            action.setStatusTip(status_tip)

        if whats_this is not None:
            action.setWhatsThis(whats_this)

        if add_to_toolbar:
            self.toolbar.addAction(action)

        if add_to_menu:
            self.iface.addPluginToMenu(
                self.menu,
                action)

        self.actions.append(action)

        return action


    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        icon_path = ''
        self.add_action(
            icon_path,
            text=self.tr(u'圖資操作處理工具v3.0'),
            callback=self.run,
            parent=self.iface.mainWindow())
        
        

        #照片EXIF定位ImportPhotos初始參數
        self.clickPhotos = self.add_action(
            icon_path,
            text=self.tr(u'檢視照片'),
            callback=self.mouseClick,
            parent=self.iface.mainWindow())
        
        self.clickPhotos.setCheckable(True)
        self.clickPhotos.setEnabled(True)
        # self.iface.addPluginToMenu(TFB_Tools3.description(), self.action)
        self.listPhotos = []
        self.layernamePhotos = []        
        self.toolMouseClick = MouseClick(self.canvas, self)
        

        self.fields = ['ID', 'Name', 'Date', 'Time', 'Lon', 'Lat', 'Altitude', 'North', 'Azimuth', 'Camera Maker',
                       'Camera Model', 'Title', 'Comment', 'Path', 'RelPath', 'Timestamp']

        self.extension_switch = {
            ".shp": "ESRI Shapefile",
            ".geojson": "GeoJSON",
            ".gpkg":"GPKG",
            ".csv": "CSV",
            ".kml": "KML",
            ".tab": "MapInfo File"
        }

        self.extension_switch2 = {
            "ESRI Shapefile (*.shp *.SHP)": ".shp",
            "GeoJSON (*.geojson *.GEOJSON)": ".geojson",
            "GeoPackage (*.gpkg *.GPKG)":".gpkg",
            "Comma Separated Value (*.csv *.CSV)": ".csv",
            "Keyhole Markup Language (*.kml *.KML)": ".kml",
            "Mapinfo TAB (*.tab *.TAB)": ".tab"
        }

        self.extension_switch_types = {
            ".shp": "ESRI Shapefile",
            ".geojson": "GeoJSON",
            ".gpkg":"GPKG",
            ".csv": "CSV",
            ".kml": "KML",
            ".tab": "MapInfo File"
        }

        ############################

        self.pointEmitter = QgsMapToolEmitPoint(self.iface.mapCanvas())
        self.iface.mapCanvas().setMapTool( self.pointEmitter ) 
        

    #--------------------------------------------------------------------------

    def onClosePlugin(self):
        """Cleanup necessary items here when plugin dockwidget is closed"""

        #print "** CLOSING TFB_Tools3"

        # disconnects
        self.dockwidget.closingPlugin.disconnect(self.onClosePlugin)

        # remove this statement if dockwidget is to remain
        # for reuse if plugin is reopened
        # Commented next statement since it causes QGIS crashe
        # when closing the docked window:
        # self.dockwidget = None

        self.pluginIsActive = False


    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""

        #print "** UNLOAD TFB_Tools3"
        
        for action in self.actions:
            self.iface.removePluginVectorMenu(
                self.tr(u'&TFB_Tools3'),
                action)
            self.iface.removeToolBarIcon(action)
        # remove the toolbar
        del self.toolbar

        # self.writeDefaultPath()

        

##---------快速定位功能------------####


    # def positioning_lyr(self):
    #     #QMessageBox.information(self.iface.mainWindow(), "X", "load")
    #     self.iface.mapCanvas().unsetMapTool( self.pointEmitter )
    #     # set positioning dia        
    #     #self.positioningDia.setFixedSize(385,168)
    #     self.positioningDia.comboBox_19.setCurrentIndex(0)
    #     self.positioningDia.groupBox.hide()
    #     self.positioningDia.groupBox_2.hide()
    #     self.positioningDia.groupBox_3.hide()
    #     self.positioningDia.tabWidget.hide()
    #     #self.positioningDia.groupBox_2.setGeometry(QtCore.QRect(20, 60, 341, 101))
    #     self.positioningDia.setFixedSize(385,58)
    #     self.positioningDia.show()
    #     # self.dockwidget.pushButton_10.setEnabled(False)

    def positioningDia_show(self):
        self.iface.mapCanvas().unsetMapTool(self.pointEmitter)
        self.positioningDia.comboBox_19.setCurrentIndex(0)
        self.positioningDia.groupBox.hide()
        self.positioningDia.groupBox_2.hide()
        self.positioningDia.groupBox_3.hide()
        self.positioningDia.tabWidget.hide()
        self.positioningDia.setFixedSize(385,58)
        self.positioningDia.show()
        self.dockwidget.pushButton_10.setEnabled(False)

    def reconnection_positioningButton(self):
        self.dockwidget.pushButton_10.setEnabled(True)

    def setSourceEncode(self):
        pass


    def switchPositioningDia(self):
        layers = self.canvas.layers()

        self.positioningDia.comboBox_6.setEnabled(False)
        self.positioningDia.comboBox_7.setEnabled(False)
        self.positioningDia.comboBox_8.setEnabled(False)
        self.positioningDia.comboBox_9.setEnabled(False)
        self.positioningDia.comboBox_6.clear()
        self.positioningDia.comboBox_7.clear()
        self.positioningDia.comboBox_8.clear()
        self.positioningDia.comboBox_9.clear()

        self.positioningDia.comboBox.setCurrentIndex(0)
        self.positioningDia.comboBox_2.setCurrentIndex(0)
        self.positioningDia.comboBox_3.setCurrentIndex(0)

        self.positioningDia.comboBox_5.setCurrentIndex(0)
        self.positioningDia.comboBox_6.setCurrentIndex(0)
        self.positioningDia.comboBox_7.setCurrentIndex(0)
        self.positioningDia.comboBox_8.setCurrentIndex(0)
        self.positioningDia.comboBox_9.setCurrentIndex(0)

        self.positioningDia.comboBox_10.setCurrentIndex(0)
        self.positioningDia.comboBox_11.setCurrentIndex(0)
        self.positioningDia.comboBox_12.setCurrentIndex(0)

        self.positioningDia.comboBox_4.setCurrentIndex(0)
        self.positioningDia.comboBox_13.setCurrentIndex(0)
        self.positioningDia.comboBox_14.setCurrentIndex(0)
        self.positioningDia.comboBox_15.setCurrentIndex(0)
        self.positioningDia.comboBox_16.setCurrentIndex(0)
        self.positioningDia.comboBox_17.setCurrentIndex(0)
        self.positioningDia.comboBox_18.setCurrentIndex(0)

        if self.positioningDia.comboBox_19.currentIndex()==0:
            self.positioningDia.groupBox.hide()
            self.positioningDia.groupBox_2.hide()
            self.positioningDia.groupBox_3.hide()
            self.positioningDia.tabWidget.hide()
            self.positioningDia.groupBox_2.setGeometry(QtCore.QRect(20, 60, 341, 101))
            self.positioningDia.setFixedSize(385,58)

        if self.positioningDia.comboBox_19.currentIndex()==1:
            filePath = rootPath + 'filePath.csv'
            filePathfile = open(filePath, 'r', encoding="utf-8")
            csvCursor = csv.reader(filePathfile)
            filePathList = []
            for row in csvCursor:
                filePathList.append(row)
            filePathName = self.dockwidget.lineEdit.text() + filePathList[0][2]
            if os.path.isfile(filePathName) :
                if len(QgsProject.instance().mapLayersByName(filePathList[0][1])) == 0:
                    i=0
                    self.iface.addVectorLayer(filePathName, "", "ogr")
                    self.positioningDia.comboBox.clear()
                    self.positioningDia.comboBox.insertItem(0, '請選擇林區')
                    fni = self.iface.activeLayer().fields().lookupField(filePathList[0][3])
                    unique_values = self.iface.activeLayer().dataProvider().uniqueValues(fni)
                    for value in unique_values:
                        if value != NULL:
                            self.positioningDia.comboBox.insertItem(i+1, value[0]+value[1])
                            i+=1
                    self.positioningDia.comboBox.setCurrentIndex(0)
                    # legend = self.iface.legendInterface()
                    layers = self.canvas.layers()
                    for each_layer in layers:
                        QgsProject.instance().layerTreeRoot().findLayer(each_layer.id()).setItemVisibilityChecked(False)
                        # legend.setLayerVisible(each_layer, False)
                    registry = QgsProject.instance()
                    target_layer = registry.mapLayersByName( filePathList[0][1] )[0]
                    self.iface.setActiveLayer(target_layer)
                    QgsProject.instance().layerTreeRoot().findLayer(target_layer.id()).setItemVisibilityChecked(True)
                    # legend.setLayerVisible(target_layer, True)
                    extent = target_layer.extent()
                    self.canvas.setExtent(extent)
                self.positioningDia.groupBox.show()
                self.positioningDia.groupBox_2.hide()
                self.positioningDia.groupBox_3.hide()
                self.positioningDia.tabWidget.hide()
                self.positioningDia.groupBox_2.setGeometry(QtCore.QRect(20, 60, 341, 101))
                self.positioningDia.setFixedSize(385,166)
            else:
                msg = "找不到\" " + filePathName + " \"圖層" + "\n請確認路徑"
                QMessageBox.information(self.iface.mainWindow(), "錯誤", msg)

        if self.positioningDia.comboBox_19.currentIndex()==2:
            filePath = rootPath + 'filePath.csv'
            filePathfile = open(filePath, 'r')
            csvCursor = csv.reader(filePathfile)
            filePathList = []
            for row in csvCursor:
                filePathList.append(row)
            filePathName = self.dockwidget.lineEdit.text() + filePathList[2][2]
            if os.path.isfile(filePathName) :
                if len(QgsProject.instance().mapLayersByName(filePathList[2][1])) == 0:
                    i=0
                    self.iface.addVectorLayer(filePathName, "", "ogr")
                    self.setSourceEncode()
                    self.positioningDia.comboBox_10.clear()
                    self.positioningDia.comboBox_10.insertItem(0, '請選擇保安林編號')
                    fni = self.iface.activeLayer().fields().lookupField(filePathList[2][3])
                    unique_values = self.iface.activeLayer().dataProvider().uniqueValues(fni)
                    for value in unique_values:
                        if value != NULL:
                            self.positioningDia.comboBox_10.insertItem(i+1, value)
                            i+=1
                    self.positioningDia.comboBox_10.setCurrentIndex(0)
                    # legend = self.iface.legendInterface()
                    layers = self.canvas.layers()
                    for each_layer in layers:
                        QgsProject.instance().layerTreeRoot().findLayer(each_layer.id()).setItemVisibilityChecked(False)
                        # legend.setLayerVisible(each_layer, False)
                    registry = QgsProject.instance()
                    target_layer = registry.mapLayersByName(filePathList[2][1])[0]
                    self.iface.setActiveLayer(target_layer)
                    QgsProject.instance().layerTreeRoot().findLayer(target_layer.id()).setItemVisibilityChecked(True)
                    # legend.setLayerVisible(target_layer, True)
                    extent = target_layer.extent()
                    self.canvas.setExtent(extent)
                self.positioningDia.comboBox_11.clear()
                self.positioningDia.comboBox_12.clear()
                self.positioningDia.groupBox.hide()
                self.positioningDia.groupBox_2.hide()
                self.positioningDia.groupBox_3.show()
                self.positioningDia.tabWidget.hide()
                self.positioningDia.groupBox_3.setGeometry(QtCore.QRect(20, 60, 341, 131))
                self.positioningDia.setFixedSize(385,203)
            else:
                msg = "找不到\" " + filePathName + " \"圖層" + "\n請確認路徑"
                QMessageBox.information(self.iface.mainWindow(), "錯誤", msg)

        if self.positioningDia.comboBox_19.currentIndex()==3:
            self.positioningDia.groupBox.hide()
            self.positioningDia.groupBox_2.hide()
            self.positioningDia.groupBox_3.hide()
            self.positioningDia.tabWidget.show()
            self.positioningDia.tabWidget.setGeometry(QtCore.QRect(20, 60, 491, 231))
            self.positioningDia.setFixedSize(524,306)

    def zoomTo_comboBox_18(self):
        self.positioningDia.comboBox_4.setCurrentIndex(0)
        self.positioningDia.comboBox_13.setCurrentIndex(0)
        self.positioningDia.comboBox_14.setCurrentIndex(0)
        self.positioningDia.comboBox_15.setCurrentIndex(0)
        self.positioningDia.comboBox_16.setCurrentIndex(0)
        self.positioningDia.comboBox_17.setCurrentIndex(0)
        self.positioningDia.comboBox_20.setCurrentIndex(0)
        # legend = self.iface.legendInterface()
        layers = self.canvas.layers()
        for each_layer in layers:
            QgsProject.instance().layerTreeRoot().findLayer(each_layer.id()).setItemVisibilityChecked(False)
            # legend.setLayerVisible(each_layer, False)
        registry = QgsProject.instance()
        filePath = rootPath + 'filePath.csv'
        filePathfile = open(filePath, 'r')
        csvCursor = csv.reader(filePathfile)
        filePathList = []
        for row in csvCursor:
            filePathList.append(row)
        target_layer = registry.mapLayersByName( filePathList[5][1] )[0]
        self.iface.setActiveLayer(target_layer)
        QgsProject.instance().layerTreeRoot().findLayer(target_layer.id()).setItemVisibilityChecked(True)
        # legend.setLayerVisible(target_layer, True)
        expr = QgsExpression( " \"{}\" ='{}' ".format(filePathList[5][3],self.positioningDia.comboBox_18.currentText() ) )
        it = target_layer.getFeatures( QgsFeatureRequest( expr ) )
        ids = [i.id() for i in it]
        target_layer.selectByIds( ids )
        self.canvas.zoomToSelected()

    def zoomTo_comboBox_17(self):
        self.positioningDia.comboBox_4.setCurrentIndex(0)
        self.positioningDia.comboBox_13.setCurrentIndex(0)
        self.positioningDia.comboBox_14.setCurrentIndex(0)
        self.positioningDia.comboBox_15.setCurrentIndex(0)
        self.positioningDia.comboBox_16.setCurrentIndex(0)
        self.positioningDia.comboBox_18.setCurrentIndex(0)
        self.positioningDia.comboBox_20.setCurrentIndex(0)
        # legend = self.iface.legendInterface()
        layers = self.canvas.layers()
        for each_layer in layers:
            QgsProject.instance().layerTreeRoot().findLayer(each_layer.id()).setItemVisibilityChecked(False)
            # legend.setLayerVisible(each_layer, False)
        registry = QgsProject.instance()
        filePath = rootPath + 'filePath.csv'
        filePathfile = open(filePath, 'r')
        csvCursor = csv.reader(filePathfile)
        filePathList = []
        for row in csvCursor:
            filePathList.append(row)
        target_layer = registry.mapLayersByName( filePathList[4][1] )[0]
        self.iface.setActiveLayer(target_layer)
        QgsProject.instance().layerTreeRoot().findLayer(target_layer.id()).setItemVisibilityChecked(True)
        # legend.setLayerVisible(target_layer, True)
        expr = QgsExpression( " \"{}\" ='{}' ".format(filePathList[4][3],self.positioningDia.comboBox_17.currentText() ) )
        it = target_layer.getFeatures( QgsFeatureRequest( expr ) )
        ids = [i.id() for i in it]
        target_layer.selectByIds( ids )
        self.canvas.zoomToSelected()

    def zoomTo_comboBox_16(self):
        self.positioningDia.comboBox_4.setCurrentIndex(0)
        self.positioningDia.comboBox_13.setCurrentIndex(0)
        self.positioningDia.comboBox_14.setCurrentIndex(0)
        self.positioningDia.comboBox_15.setCurrentIndex(0)
        self.positioningDia.comboBox_17.setCurrentIndex(0)
        self.positioningDia.comboBox_18.setCurrentIndex(0)
        self.positioningDia.comboBox_20.setCurrentIndex(0)
        # legend = self.iface.legendInterface()
        layers = self.canvas.layers()
        for each_layer in layers:
            QgsProject.instance().layerTreeRoot().findLayer(each_layer.id()).setItemVisibilityChecked(False)
            # legend.setLayerVisible(each_layer, False)
        registry = QgsProject.instance()
        filePath = rootPath + 'filePath.csv'
        filePathfile = open(filePath, 'r')
        csvCursor = csv.reader(filePathfile)
        filePathList = []
        for row in csvCursor:
            filePathList.append(row)
        target_layer = registry.mapLayersByName( filePathList[3][1] )[0]
        self.iface.setActiveLayer(target_layer)
        QgsProject.instance().layerTreeRoot().findLayer(target_layer.id()).setItemVisibilityChecked(True)
        # legend.setLayerVisible(target_layer, True)
        expr = QgsExpression( " \"{}\" ='{}' ".format(filePathList[3][3],self.positioningDia.comboBox_16.currentText() ) )
        it = target_layer.getFeatures( QgsFeatureRequest( expr ) )
        ids = [i.id() for i in it]
        target_layer.selectByIds( ids )
        self.canvas.zoomToSelected()

    def zoomTo_comboBox_15(self):
        self.positioningDia.comboBox_4.setCurrentIndex(0)
        self.positioningDia.comboBox_13.setCurrentIndex(0)
        self.positioningDia.comboBox_14.setCurrentIndex(0)
        self.positioningDia.comboBox_16.setCurrentIndex(0)
        self.positioningDia.comboBox_17.setCurrentIndex(0)
        self.positioningDia.comboBox_18.setCurrentIndex(0)
        self.positioningDia.comboBox_20.setCurrentIndex(0)
        # legend = self.iface.legendInterface()
        layers = self.canvas.layers()
        for each_layer in layers:
            QgsProject.instance().layerTreeRoot().findLayer(each_layer.id()).setItemVisibilityChecked(False)
            # legend.setLayerVisible(each_layer, False)
        registry = QgsProject.instance()
        filePath = rootPath + 'filePath.csv'
        filePathfile = open(filePath, 'r')
        csvCursor = csv.reader(filePathfile)
        filePathList = []
        for row in csvCursor:
            filePathList.append(row)
        target_layer = registry.mapLayersByName( filePathList[10][1] )[0]
        self.iface.setActiveLayer(target_layer)
        QgsProject.instance().layerTreeRoot().findLayer(target_layer.id()).setItemVisibilityChecked(True)
        # legend.setLayerVisible(target_layer, True)
        expr = QgsExpression( " \"{}\" ='{}' ".format(filePathList[10][3],self.positioningDia.comboBox_15.currentText() ) )
        it = target_layer.getFeatures( QgsFeatureRequest( expr ) )
        ids = [i.id() for i in it]
        target_layer.selectByIds( ids )
        self.canvas.zoomToSelected()

    def zoomTo_comboBox_14(self):
        self.positioningDia.comboBox_4.setCurrentIndex(0)
        self.positioningDia.comboBox_13.setCurrentIndex(0)
        self.positioningDia.comboBox_18.setCurrentIndex(0)
        self.positioningDia.comboBox_15.setCurrentIndex(0)
        self.positioningDia.comboBox_16.setCurrentIndex(0)
        self.positioningDia.comboBox_17.setCurrentIndex(0)
        self.positioningDia.comboBox_20.setCurrentIndex(0)
        # legend = self.iface.legendInterface()
        layers = self.canvas.layers()
        for each_layer in layers:
            QgsProject.instance().layerTreeRoot().findLayer(each_layer.id()).setItemVisibilityChecked(False)
            # legend.setLayerVisible(each_layer, False)
        registry = QgsProject.instance()

        filePath = rootPath + 'filePath.csv'
        filePathfile = open(filePath, 'r')
        csvCursor = csv.reader(filePathfile)
        filePathList = []
        for row in csvCursor:
            filePathList.append(row)
        target_layer = registry.mapLayersByName( filePathList[6][1] )[0]
        self.iface.setActiveLayer(target_layer)
        QgsProject.instance().layerTreeRoot().findLayer(target_layer.id()).setItemVisibilityChecked(True)
        # legend.setLayerVisible(target_layer, True)
        expr = QgsExpression( " \"{}\" ='{}' ".format(filePathList[6][3],self.positioningDia.comboBox_14.currentText() ) )
        it = target_layer.getFeatures( QgsFeatureRequest( expr ) )
        ids = [i.id() for i in it]
        target_layer.selectByIds( ids )
        self.canvas.zoomToSelected()

    def zoomTo_comboBox_13(self):
        self.positioningDia.comboBox_4.setCurrentIndex(0)
        self.positioningDia.comboBox_14.setCurrentIndex(0)
        self.positioningDia.comboBox_15.setCurrentIndex(0)
        self.positioningDia.comboBox_16.setCurrentIndex(0)
        self.positioningDia.comboBox_17.setCurrentIndex(0)
        self.positioningDia.comboBox_18.setCurrentIndex(0)
        self.positioningDia.comboBox_20.setCurrentIndex(0)
        # legend = self.iface.legendInterface()
        layers = self.canvas.layers()
        for each_layer in layers:
            QgsProject.instance().layerTreeRoot().findLayer(each_layer.id()).setItemVisibilityChecked(False)
            # legend.setLayerVisible(each_layer, False)
        registry = QgsProject.instance()
        filePath = rootPath + 'filePath.csv'
        filePathfile = open(filePath, 'r')
        csvCursor = csv.reader(filePathfile)
        filePathList = []
        for row in csvCursor:
            filePathList.append(row)
        target_layer = registry.mapLayersByName( filePathList[9][1] )[0]
        self.iface.setActiveLayer(target_layer)
        QgsProject.instance().layerTreeRoot().findLayer(target_layer.id()).setItemVisibilityChecked(True)
        # legend.setLayerVisible(target_layer, True)
        expr = QgsExpression( " \"{}\" ='{}' ".format(filePathList[9][3],self.positioningDia.comboBox_13.currentText() ) )
        it = target_layer.getFeatures( QgsFeatureRequest( expr ) )
        ids = [i.id() for i in it]
        target_layer.selectByIds( ids )
        self.canvas.zoomToSelected()

    def zoomTo_comboBox_4(self):
        self.positioningDia.comboBox_13.setCurrentIndex(0)
        self.positioningDia.comboBox_14.setCurrentIndex(0)
        self.positioningDia.comboBox_15.setCurrentIndex(0)
        self.positioningDia.comboBox_16.setCurrentIndex(0)
        self.positioningDia.comboBox_17.setCurrentIndex(0)
        self.positioningDia.comboBox_18.setCurrentIndex(0)
        self.positioningDia.comboBox_20.setCurrentIndex(0)
        # legend = self.iface.legendInterface()
        layers = self.canvas.layers()
        for each_layer in layers:
            QgsProject.instance().layerTreeRoot().findLayer(each_layer.id()).setItemVisibilityChecked(False)
            # legend.setLayerVisible(each_layer, False)
        registry = QgsProject.instance()
        filePath = rootPath + 'filePath.csv'
        filePathfile = open(filePath, 'r')
        csvCursor = csv.reader(filePathfile)
        filePathList = []
        for row in csvCursor:
            filePathList.append(row)
        target_layer = registry.mapLayersByName( filePathList[8][1] )[0]
        self.iface.setActiveLayer(target_layer)
        QgsProject.instance().layerTreeRoot().findLayer(target_layer.id()).setItemVisibilityChecked(True)
        # legend.setLayerVisible(target_layer, True)
        expr = QgsExpression( " \"{}\" ='{}' ".format(filePathList[8][3],self.positioningDia.comboBox_4.currentText() ) )
        it = target_layer.getFeatures( QgsFeatureRequest( expr ) )
        ids = [i.id() for i in it]
        target_layer.selectByIds( ids )
        self.canvas.zoomToSelected()

    def zoomTo_comboBox_20(self):
        self.positioningDia.comboBox_4.setCurrentIndex(0)
        self.positioningDia.comboBox_13.setCurrentIndex(0)
        self.positioningDia.comboBox_14.setCurrentIndex(0)
        self.positioningDia.comboBox_15.setCurrentIndex(0)
        self.positioningDia.comboBox_16.setCurrentIndex(0)
        self.positioningDia.comboBox_17.setCurrentIndex(0)
        self.positioningDia.comboBox_18.setCurrentIndex(0)
        # legend = self.iface.legendInterface()
        layers = self.canvas.layers()
        for each_layer in layers:
            QgsProject.instance().layerTreeRoot().findLayer(each_layer.id()).setItemVisibilityChecked(False)
            # legend.setLayerVisible(each_layer, False)
        registry = QgsProject.instance()
        filePath = rootPath + 'filePath.csv'
        filePathfile = open(filePath, 'r')
        csvCursor = csv.reader(filePathfile)
        filePathList = []
        for row in csvCursor:
            filePathList.append(row)
        target_layer = registry.mapLayersByName( filePathList[7][1] )[0]
        self.iface.setActiveLayer(target_layer)
        QgsProject.instance().layerTreeRoot().findLayer(target_layer.id()).setItemVisibilityChecked(True)
        # legend.setLayerVisible(target_layer, True)
        expr = QgsExpression( " \"{}\" ='{}' ".format(filePathList[7][3],self.positioningDia.comboBox_20.currentText() ) )
        it = target_layer.getFeatures( QgsFeatureRequest( expr ) )
        ids = [i.id() for i in it]
        target_layer.selectByIds( ids )
        self.canvas.zoomToSelected()

    def ComboBox_change(self):
        self.positioningDia.comboBox_2.clear()
        self.positioningDia.comboBox_3.clear()
        self.positioningDia.comboBox_2.setEnabled(True)
        self.positioningDia.comboBox_3.setEnabled(False)
        # legend = self.iface.legendInterface()
        layers = self.canvas.layers()
        for each_layer in layers:
            QgsProject.instance().layerTreeRoot().findLayer(each_layer.id()).setItemVisibilityChecked(False)
            # legend.setLayerVisible(each_layer, False)
        registry = QgsProject.instance()
        filePath = rootPath + 'filePath.csv'
        filePathfile = open(filePath, 'r')
        csvCursor = csv.reader(filePathfile)
        filePathList = []
        for row in csvCursor:
            filePathList.append(row)
        filePathName = self.dockwidget.lineEdit.text() + filePathList[0][2]
        if os.path.isfile(filePathName) :
            if len(QgsProject.instance().mapLayersByName(filePathList[0][1])) == 0:
                i=0
                self.iface.addVectorLayer(filePathName, "", "ogr")
                self.setSourceEncode()
            registry = QgsProject.instance()
            target_layer = registry.mapLayersByName( filePathList[0][1] )[0]
            self.iface.setActiveLayer(target_layer)
            QgsProject.instance().layerTreeRoot().findLayer(target_layer.id()).setItemVisibilityChecked(True)
            # legend.setLayerVisible(target_layer, True)
            self.positioningDia.comboBox_2.clear()
            self.positioningDia.comboBox_2.insertItem(0, '請選擇事業區')
            fni = self.iface.activeLayer().fields().lookupField(filePathList[0][3])
            valueList=[]
            unique_values = self.iface.activeLayer().dataProvider().uniqueValues(fni)
            for value in unique_values:
                if value != NULL:
                    valueList.append(value)
            expr = QgsExpression( " \"{}\" ='{}' ".format( filePathList[0][3], valueList[self.positioningDia.comboBox.currentIndex()-1] ) )
            it = target_layer.getFeatures( QgsFeatureRequest( expr ) )
            idx_1 = self.iface.activeLayer().fields().lookupField(filePathList[0][4])
            valueList_2 =[j.attributes()[idx_1] for j in it]
            it = target_layer.getFeatures( QgsFeatureRequest( expr ) )
            ids = [i.id() for i in it]
            self.iface.activeLayer().removeSelection()
            target_layer.selectByIds( ids )
            self.canvas.zoomToSelected()
            uniqueValue = set(valueList_2)
            i=0
            self.positioningDia.comboBox_2.clear()
            for v in uniqueValue:
                if v != NULL:
                    self.positioningDia.comboBox_2.insertItem(i+1, v)
                    i+=1
            self.positioningDia.comboBox_2.setCurrentIndex(0)
        else:
            msg = "找不到\" " + filePathName + " \"圖層" + "\n請確認路徑"
            QMessageBox.information(self.iface.mainWindow(), "錯誤", msg)

    def ComboBox_2_change(self):
        # legend = self.iface.legendInterface()
        layers = self.canvas.layers()
        for each_layer in layers:
            QgsProject.instance().layerTreeRoot().findLayer(each_layer.id()).setItemVisibilityChecked(False)
            # legend.setLayerVisible(each_layer, False)
        registry = QgsProject.instance()
        filePath = rootPath + 'filePath.csv'
        filePathfile = open(filePath, 'r')
        csvCursor = csv.reader(filePathfile)
        filePathList = []
        for row in csvCursor:
            filePathList.append(row)
        filePathName = self.dockwidget.lineEdit.text() + filePathList[1][2]
        if os.path.isfile(filePathName) :
            if len(QgsProject.instance().mapLayersByName(filePathList[1][1])) == 0:
                i=0
                self.iface.addVectorLayer(filePathName, "", "ogr")
                self.setSourceEncode()
            registry = QgsProject.instance()
            target_layer = registry.mapLayersByName( filePathList[1][1] )[0]
            self.iface.setActiveLayer(target_layer)
            QgsProject.instance().layerTreeRoot().findLayer(target_layer.id()).setItemVisibilityChecked(True)
            # legend.setLayerVisible(target_layer, True)
            expr = QgsExpression( " \"{}\" ='{}' ".format( filePathList[1][3], self.positioningDia.comboBox_2.currentText() ) )
            it = target_layer.getFeatures( QgsFeatureRequest( expr ) )
            ids = [i.id() for i in it]
            self.iface.activeLayer().removeSelection()
            target_layer.selectByIds( ids )
            self.canvas.zoomToSelected()
            self.positioningDia.comboBox_3.setEnabled(True)
            self.positioningDia.comboBox_3.clear()
            self.positioningDia.comboBox_3.insertItem(0, '請選擇林班')
            fni = self.iface.activeLayer().fields().lookupField(filePathList[1][4])
            unique_values = self.iface.activeLayer().dataProvider().uniqueValues(fni)
            i=0
            for value in unique_values:
                if value != NULL:
                    self.positioningDia.comboBox_3.insertItem(i+1, str(value))
                    i+=1
            self.positioningDia.comboBox_3.setCurrentIndex(0)
        else:
            msg = "找不到\" " + filePathName + " \"圖層" + "\n請確認路徑"
            QMessageBox.information(self.iface.mainWindow(), "錯誤", msg)

    def ComboBox_3_change(self):
        # legend = self.iface.legendInterface()
        layers = self.canvas.layers()
        for each_layer in layers:
            QgsProject.instance().layerTreeRoot().findLayer(each_layer.id()).setItemVisibilityChecked(False)
            # legend.setLayerVisible(each_layer, False)
        registry = QgsProject.instance()
        filePath = rootPath + 'filePath.csv'
        filePathfile = open(filePath, 'r')
        csvCursor = csv.reader(filePathfile)
        filePathList = []
        for row in csvCursor:
            filePathList.append(row)
        filePathName = self.dockwidget.lineEdit.text() + filePathList[1][2]
        if os.path.isfile(filePathName) :
            if len(QgsProject.instance().mapLayersByName(filePathList[1][1])) == 0:
                i=0
                self.iface.addVectorLayer(filePathName, "", "ogr")
                self.setSourceEncode()
            registry = QgsProject.instance()
            target_layer = registry.mapLayersByName( filePathList[1][1] )[0]
            self.iface.setActiveLayer(target_layer)
            QgsProject.instance().layerTreeRoot().findLayer(target_layer.id()).setItemVisibilityChecked(True)
            # legend.setLayerVisible(target_layer, True)
            expr = QgsExpression( " \"{}\" ='{}' AND \"{}\" ='{}' ".format( filePathList[1][4], self.positioningDia.comboBox_3.currentText(), filePathList[1][3],  self.positioningDia.comboBox_2.currentText()))
            it = target_layer.getFeatures( QgsFeatureRequest( expr ) )
            ids = [i.id() for i in it]
            self.iface.activeLayer().removeSelection()
            target_layer.selectByIds( ids )
            self.canvas.zoomToSelected()
        else:
            msg = "找不到\" " + filePathName + " \"圖層" + "\n請確認路徑"
            QMessageBox.information(self.iface.mainWindow(), "錯誤", msg)

    def ComboBox_5_change(self):
        registry = QgsProject.instance()
        target_layer = registry.mapLayersByName( '國有林地籍圖' )[0]
        self.iface.setActiveLayer(target_layer)
        self.positioningDia.comboBox_6.setEnabled(True)
        self.positioningDia.comboBox_7.setEnabled(False)
        self.positioningDia.comboBox_8.setEnabled(False)
        self.positioningDia.comboBox_9.setEnabled(False)
        self.positioningDia.comboBox_6.clear()
        self.positioningDia.comboBox_7.clear()
        self.positioningDia.comboBox_8.clear()
        self.positioningDia.comboBox_9.clear()
        self.positioningDia.comboBox_6.insertItem(0, '請選擇鄉鎮')
        self.positioningDia.comboBox_6.setCurrentIndex(0)
        expr = QgsExpression( " \"{}\" ='{}' ".format( '縣市', self.positioningDia.comboBox_5.currentText() ) )
        it = target_layer.getFeatures( QgsFeatureRequest( expr ) )
        idx_1 = self.iface.activeLayer().fields().lookupField('鄉鎮市')
        valueList =[j.attributes()[idx_1] for j in it]
        it = target_layer.getFeatures( QgsFeatureRequest( expr ) )
        ids = [i.id() for i in it]
        self.iface.activeLayer().removeSelection()
        target_layer.selectByIds( ids )
        self.canvas.zoomToSelected()
        uniqueValue = set(valueList)
        i=0
        self.positioningDia.comboBox_6.clear()
        for v in uniqueValue:
            self.positioningDia.comboBox_6.insertItem(i+1, v)
            i+=1

    def ComboBox_6_change(self):
        self.positioningDia.comboBox_7.setEnabled(True)
        self.positioningDia.comboBox_8.setEnabled(True)
        self.positioningDia.comboBox_9.setEnabled(False)
        self.positioningDia.comboBox_7.clear()
        self.positioningDia.comboBox_8.clear()
        self.positioningDia.comboBox_9.clear()
        self.positioningDia.comboBox_7.insertItem(0, '請選擇事務所')
        self.positioningDia.comboBox_7.setCurrentIndex(0)
        registry = QgsProject.instance()
        target_layer = registry.mapLayersByName( '國有林地籍圖' )[0]
        self.iface.setActiveLayer(target_layer)
        expr = QgsExpression( " \"{}\" ='{}' ".format( '鄉鎮市', self.positioningDia.comboBox_6.currentText() ) )
        it = target_layer.getFeatures( QgsFeatureRequest( expr ) )
        idx_1 = self.iface.activeLayer().fields().lookupField('事務所')
        valueList =[j.attributes()[idx_1] for j in it]
        it = target_layer.getFeatures( QgsFeatureRequest( expr ) )
        ids = [i.id() for i in it]
        self.iface.activeLayer().removeSelection()
        target_layer.selectByIds( ids )
        self.canvas.zoomToSelected()
        uniqueValue = set(valueList)
        i=0
        self.positioningDia.comboBox_7.clear()
        for v in uniqueValue:
            self.positioningDia.comboBox_7.insertItem(i+1, v)
            i+=1
        self.positioningDia.comboBox_8.insertItem(0, '請選擇段')
        self.positioningDia.comboBox_8.setCurrentIndex(0)
        self.iface.activeLayer().removeSelection()
        expr = QgsExpression( " \"{}\" ='{}' ".format( '鄉鎮市', self.positioningDia.comboBox_6.currentText() ) )
        it = target_layer.getFeatures( QgsFeatureRequest( expr ) )
        idx_1 = self.iface.activeLayer().fields().lookupField('段')
        valueList =[j.attributes()[idx_1] for j in it]
        it = target_layer.getFeatures( QgsFeatureRequest( expr ) )
        ids = [i.id() for i in it]
        self.iface.activeLayer().removeSelection()
        target_layer.selectByIds( ids )
        self.canvas.zoomToSelected()
        uniqueValue = set(valueList)
        i=0
        self.positioningDia.comboBox_8.clear()
        for v in uniqueValue:
            self.positioningDia.comboBox_8.insertItem(i+1, v)
            i+=1

    def ComboBox_7_change(self):
        self.positioningDia.comboBox_8.setEnabled(True)
        self.positioningDia.comboBox_9.setEnabled(False)
        self.positioningDia.comboBox_8.clear()
        self.positioningDia.comboBox_9.clear()
        self.positioningDia.comboBox_8.insertItem(0, '請選擇段')
        self.positioningDia.comboBox_8.setCurrentIndex(0)
        registry = QgsProject.instance()
        target_layer = registry.mapLayersByName( '國有林地籍圖' )[0]
        self.iface.setActiveLayer(target_layer)
        expr = QgsExpression( " \"{}\" ='{}' AND \"{}\" ='{}' ".format('鄉鎮市', self.positioningDia.comboBox_6.currentText(), '事務所',  self.positioningDia.comboBox_7.currentText()))
        it = target_layer.getFeatures( QgsFeatureRequest( expr ) )
        idx_1 = self.iface.activeLayer().fields().lookupField('段')
        valueList =[j.attributes()[idx_1] for j in it]
        it = target_layer.getFeatures( QgsFeatureRequest( expr ) )
        ids = [i.id() for i in it]
        self.iface.activeLayer().removeSelection()
        target_layer.selectByIds( ids )
        self.canvas.zoomToSelected()
        uniqueValue = set(valueList)
        i=0
        self.positioningDia.comboBox_8.clear()
        for v in uniqueValue:
            self.positioningDia.comboBox_8.insertItem(i+1, v)
            i+=1

    def ComboBox_8_change(self):
        self.positioningDia.comboBox_9.setEnabled(True)
        self.positioningDia.comboBox_9.clear()
        self.positioningDia.comboBox_9.insertItem(0, '請選擇小段')
        self.positioningDia.comboBox_9.setCurrentIndex(0)
        registry = QgsProject.instance()
        target_layer = registry.mapLayersByName( '國有林地籍圖' )[0]
        self.iface.setActiveLayer(target_layer)
        expr = QgsExpression( " \"{}\" ='{}' ".format( '段', self.positioningDia.comboBox_8.currentText() ) )
        it = target_layer.getFeatures( QgsFeatureRequest( expr ) )
        idx_1 = self.iface.activeLayer().fields().lookupField('小段')
        valueList =[j.attributes()[idx_1] for j in it]
        it = target_layer.getFeatures( QgsFeatureRequest( expr ) )
        ids = [i.id() for i in it]
        self.iface.activeLayer().removeSelection()
        target_layer.selectByIds( ids )
        self.canvas.zoomToSelected()
        uniqueValue = set(valueList)
        i=0
        self.positioningDia.comboBox_9.clear()
        for v in uniqueValue:
            if v != NULL:
                self.positioningDia.comboBox_9.insertItem(i+1, v)
                i+=1

    def ComboBox_9_change(self):
        registry = QgsProject.instance()
        target_layer = registry.mapLayersByName( '國有林地籍圖' )[0]
        self.iface.setActiveLayer(target_layer)
        expr = QgsExpression( " \"{}\" ='{}' ".format( '小段', self.positioningDia.comboBox_9.currentText() ) )
        it = target_layer.getFeatures( QgsFeatureRequest( expr ) )
        it = target_layer.getFeatures( QgsFeatureRequest( expr ) )
        ids = [i.id() for i in it]
        self.iface.activeLayer().removeSelection()
        target_layer.selectByIds( ids )
        self.canvas.zoomToSelected()

    def ComboBox_10_change(self):
        registry = QgsProject.instance()
        filePath = rootPath + 'filePath.csv'
        filePathfile = open(filePath, 'r')
        csvCursor = csv.reader(filePathfile)
        filePathList = []
        for row in csvCursor:
            filePathList.append(row)
        target_layer = registry.mapLayersByName( filePathList[2][1] )[0]
        self.iface.setActiveLayer(target_layer)
        self.positioningDia.comboBox_11.setEnabled(True)
        self.positioningDia.comboBox_12.setEnabled(False)
        self.positioningDia.comboBox_11.clear()
        self.positioningDia.comboBox_12.clear()
        self.positioningDia.comboBox_11.insertItem(0, '請選擇段號')
        self.positioningDia.comboBox_11.setCurrentIndex(0)
        expr = QgsExpression( " \"{}\" ='{}' ".format( filePathList[2][3], self.positioningDia.comboBox_10.currentText() ) )
        it = target_layer.getFeatures( QgsFeatureRequest( expr ) )
        idx_1 = self.iface.activeLayer().fields().lookupField(filePathList[2][4])
        valueList =[j.attributes()[idx_1] for j in it]
        it = target_layer.getFeatures( QgsFeatureRequest( expr ) )
        ids = [i.id() for i in it]
        self.iface.activeLayer().removeSelection()
        target_layer.selectByIds( ids )
        self.canvas.zoomToSelected()

    def ComboBox_11_change(self):
        registry = QgsProject.instance()
        filePath = rootPath + 'filePath.csv'
        filePathfile = open(filePath, 'r')
        csvCursor = csv.reader(filePathfile)
        filePathList = []
        for row in csvCursor:
            filePathList.append(row)
        target_layer = registry.mapLayersByName( filePathList[2][1] )[0]
        self.iface.setActiveLayer(target_layer)
        self.positioningDia.comboBox_12.setEnabled(True)
        self.positioningDia.comboBox_12.clear()
        self.positioningDia.comboBox_12.insertItem(0, '請選擇地號-母號')
        self.positioningDia.comboBox_12.setCurrentIndex(0)
        expr = QgsExpression( " \"{}\" ='{}' AND \"{}\" ='{}' ".format('PF_ID', self.positioningDia.comboBox_10.currentText(), 'C_SECT',  self.positioningDia.comboBox_11.currentText()))
        it = target_layer.getFeatures( QgsFeatureRequest( expr ) )
        idx_1 = self.iface.activeLayer().fields().lookupField('LAND_NO0')
        valueList =[j.attributes()[idx_1] for j in it]
        it = target_layer.getFeatures( QgsFeatureRequest( expr ) )
        ids = [i.id() for i in it]
        self.iface.activeLayer().removeSelection()
        target_layer.selectByIds( ids )
        self.canvas.zoomToSelected()
        uniqueValue = set(valueList)
        i=0
        self.positioningDia.comboBox_12.clear()
        for v in uniqueValue:
            self.positioningDia.comboBox_12.insertItem(i+1, v)
            i+=1

    def ComboBox_12_change(self):
        registry = QgsProject.instance()
        filePath = rootPath + 'filePath.csv'
        filePathfile = open(filePath, 'r')
        csvCursor = csv.reader(filePathfile)
        filePathList = []
        for row in csvCursor:
            filePathList.append(row)
        target_layer = registry.mapLayersByName( filePathList[2][1] )[0]
        self.iface.setActiveLayer(target_layer)
        expr = QgsExpression( " \"{}\" ='{}' AND \"{}\" ='{}' AND \"{}\" ='{}'".format('PF_ID', self.positioningDia.comboBox_10.currentText(), 'C_SECT',  self.positioningDia.comboBox_11.currentText(), 'LAND_NO0', self.positioningDia.comboBox_12.currentText()))
        it = target_layer.getFeatures( QgsFeatureRequest( expr ) )
        ids = [i.id() for i in it]
        self.iface.activeLayer().removeSelection()
        target_layer.selectByIds( ids )
        self.canvas.zoomToSelected()

    def addlayer_comboBox_18(self):
        filePath = rootPath + 'filePath.csv'
        filePathfile = open(filePath, 'r')
        csvCursor = csv.reader(filePathfile)
        filePathList = []
        for row in csvCursor:
            filePathList.append(row)
        i=0
        filePathName = self.dockwidget.lineEdit.text() + filePathList[5][2]
        if os.path.isfile(filePathName) :
            if len(QgsProject.instance().mapLayersByName(filePathList[5][1])) == 0:
                self.iface.addVectorLayer(filePathName, "", "ogr")
                self.setSourceEncode()
                self.positioningDia.comboBox_18.clear()
                self.positioningDia.comboBox_18.insertItem(0, '請選擇欲定位區位')
                features = self.iface.activeLayer().getFeatures()
                idx_1 = self.iface.activeLayer().fields().lookupField(filePathList[5][3])
                for feat in features:
                    attrs_1 = feat.attributes()[idx_1]
                    self.positioningDia.comboBox_18.insertItem(i+1, attrs_1)
                    i+=1
                self.positioningDia.comboBox_18.setCurrentIndex(0)
        else:
            msg = "找不到\" " + filePathName + " \"圖層" + "\n請確認路徑"
            QMessageBox.information(self.iface.mainWindow(), "錯誤", msg)

    def addlayer_comboBox_17(self):
        filePath = rootPath + 'filePath.csv'
        filePathfile = open(filePath, 'r')
        csvCursor = csv.reader(filePathfile)
        filePathList = []
        for row in csvCursor:
            filePathList.append(row)
        i=0
        filePathName = self.dockwidget.lineEdit.text() + filePathList[4][2]
        if os.path.isfile(filePathName) :
            if len(QgsProject.instance().mapLayersByName(filePathList[4][1])) == 0:
                self.iface.addVectorLayer(filePathName, "", "ogr")
                self.setSourceEncode()
                self.positioningDia.comboBox_17.clear()
                self.positioningDia.comboBox_17.insertItem(0, '請選擇欲定位區位')
                features = self.iface.activeLayer().getFeatures()
                idx_1 = self.iface.activeLayer().fields().lookupField(filePathList[4][3])
                for feat in features:
                    attrs_1 = feat.attributes()[idx_1]
                    self.positioningDia.comboBox_17.insertItem(i+1, attrs_1)
                    i+=1
                self.positioningDia.comboBox_17.setCurrentIndex(0)
        else:
            msg = "找不到\" " + filePathName + " \"圖層" + "\n請確認路徑"
            QMessageBox.information(self.iface.mainWindow(), "錯誤", msg)

    def addlayer_comboBox_16(self):
        filePath = rootPath + 'filePath.csv'
        filePathfile = open(filePath, 'r')
        csvCursor = csv.reader(filePathfile)
        filePathList = []
        for row in csvCursor:
            filePathList.append(row)
        i=0
        filePathName = self.dockwidget.lineEdit.text() + filePathList[3][2]
        if os.path.isfile(filePathName) :
            if len(QgsProject.instance().mapLayersByName(filePathList[3][1])) == 0:
                self.iface.addVectorLayer(filePathName, "", "ogr")
                self.setSourceEncode()
                self.positioningDia.comboBox_16.clear()
                self.positioningDia.comboBox_16.insertItem(0, '請選擇欲定位區位')
                features = self.iface.activeLayer().getFeatures()
                idx_1 = self.iface.activeLayer().fields().lookupField(filePathList[3][3])
                for feat in features:
                    attrs_1 = feat.attributes()[idx_1]
                    self.positioningDia.comboBox_16.insertItem(i+1, attrs_1)
                    i+=1
                self.positioningDia.comboBox_16.setCurrentIndex(0)
        else:
            msg = "找不到\" " + filePathName + " \"圖層" + "\n請確認路徑"
            QMessageBox.information(self.iface.mainWindow(), "錯誤", msg)

    def addlayer_comboBox_15(self):
        filePath = rootPath + 'filePath.csv'
        filePathfile = open(filePath, 'r')
        csvCursor = csv.reader(filePathfile)
        filePathList = []
        for row in csvCursor:
            filePathList.append(row)
        i=0
        filePathName = self.dockwidget.lineEdit.text() + filePathList[10][2]
        if os.path.isfile(filePathName) :
            if len(QgsProject.instance().mapLayersByName(filePathList[10][1])) == 0:
                self.iface.addVectorLayer(filePathName, "", "ogr")
                self.setSourceEncode()
                self.positioningDia.comboBox_15.clear()
                self.positioningDia.comboBox_15.insertItem(0, '請選擇欲定位區位')
                features = self.iface.activeLayer().getFeatures()
                idx_1 = self.iface.activeLayer().fields().lookupField(filePathList[10][3])
                for feat in features:
                    attrs_1 = feat.attributes()[idx_1]
                    self.positioningDia.comboBox_15.insertItem(i+1, attrs_1)
                    i+=1
                self.positioningDia.comboBox_15.setCurrentIndex(0)
        else:
            msg = "找不到\" " + filePathName + " \"圖層" + "\n請確認路徑"
            QMessageBox.information(self.iface.mainWindow(), "錯誤", msg)

    def addlayer_comboBox_14(self):
        filePath = rootPath + 'filePath.csv'
        filePathfile = open(filePath, 'r')
        csvCursor = csv.reader(filePathfile)
        filePathList = []
        for row in csvCursor:
            filePathList.append(row)
        i=0
        filePathName = self.dockwidget.lineEdit.text() + filePathList[6][2]
        if os.path.isfile(filePathName) :
            if len(QgsProject.instance().mapLayersByName(filePathList[6][1])) == 0:
                self.iface.addVectorLayer(filePathName, "", "ogr")
                self.setSourceEncode()
                self.positioningDia.comboBox_14.clear()
                self.positioningDia.comboBox_14.insertItem(0, '請選擇欲定位區位')
                features = self.iface.activeLayer().getFeatures()
                idx_1 = self.iface.activeLayer().fields().lookupField(filePathList[6][3])
                for feat in features:
                    attrs_1 = feat.attributes()[idx_1]
                    self.positioningDia.comboBox_14.insertItem(i+1, attrs_1)
                    i+=1
                self.positioningDia.comboBox_14.setCurrentIndex(0)
        else:
            msg = "找不到\" " + filePathName + " \"圖層" + "\n請確認路徑"
            QMessageBox.information(self.iface.mainWindow(), "錯誤", msg)

    def addlayer_comboBox_13(self):
        filePath = rootPath + 'filePath.csv'
        filePathfile = open(filePath, 'r')
        csvCursor = csv.reader(filePathfile)
        filePathList = []
        for row in csvCursor:
            filePathList.append(row)
        i=0
        filePathName = self.dockwidget.lineEdit.text() + filePathList[9][2]
        if os.path.isfile(filePathName) :
            if len(QgsProject.instance().mapLayersByName(filePathList[9][1])) == 0:
                self.iface.addVectorLayer(filePathName, "", "ogr")
                self.setSourceEncode()
                self.positioningDia.comboBox_13.clear()
                self.positioningDia.comboBox_13.insertItem(0, '請選擇欲定位區位')
                features = self.iface.activeLayer().getFeatures()
                idx_1 = self.iface.activeLayer().fields().lookupField(filePathList[9][3])
                for feat in features:
                    attrs_1 = feat.attributes()[idx_1]
                    self.positioningDia.comboBox_13.insertItem(i+1, attrs_1)
                    i+=1
                self.positioningDia.comboBox_13.setCurrentIndex(0)
        else:
            msg = "找不到\" " + filePathName + " \"圖層" + "\n請確認路徑"
            QMessageBox.information(self.iface.mainWindow(), "錯誤", msg)

    def addlayer_comboBox_4(self):
        filePath = rootPath + 'filePath.csv'
        filePathfile = open(filePath, 'r')
        csvCursor = csv.reader(filePathfile)
        filePathList = []
        for row in csvCursor:
            filePathList.append(row)
        i=0
        filePathName = self.dockwidget.lineEdit.text() + filePathList[8][2]
        if os.path.isfile(filePathName) :
            if len(QgsProject.instance().mapLayersByName(filePathList[8][1])) == 0:
                self.iface.addVectorLayer(filePathName, "", "ogr")
                self.setSourceEncode()
                self.positioningDia.comboBox_4.clear()
                self.positioningDia.comboBox_4.insertItem(0, '請選擇欲定位區位')
                features = self.iface.activeLayer().getFeatures()
                idx_1 = self.iface.activeLayer().fields().lookupField(filePathList[8][3])
                for feat in features:
                    attrs_1 = feat.attributes()[idx_1]
                    self.positioningDia.comboBox_4.insertItem(i+1, attrs_1)
                    i+=1
                self.positioningDia.comboBox_4.setCurrentIndex(0)
        else:
            msg = "找不到\" " + filePathName + " \"圖層" + "\n請確認路徑"
            QMessageBox.information(self.iface.mainWindow(), "錯誤", msg)

    def addlayer_comboBox_20(self):
        filePath = rootPath + 'filePath.csv'
        filePathfile = open(filePath, 'r')
        csvCursor = csv.reader(filePathfile)
        filePathList = []
        for row in csvCursor:
            filePathList.append(row)
        i=0
        filePathName = self.dockwidget.lineEdit.text() + filePathList[7][2]
        if os.path.isfile(filePathName) :
            if len(QgsProject.instance().mapLayersByName(filePathList[7][1])) == 0:
                self.iface.addVectorLayer(filePathName, "", "ogr")
                self.setSourceEncode()
                self.positioningDia.comboBox_20.clear()
                self.positioningDia.comboBox_20.insertItem(0, '請選擇欲定位區位')
                features = self.iface.activeLayer().getFeatures()
                idx_1 = self.iface.activeLayer().fields().lookupField(filePathList[7][3])
                for feat in features:
                    attrs_1 = feat.attributes()[idx_1]
                    self.positioningDia.comboBox_20.insertItem(i+1, attrs_1)
                    i+=1
                self.positioningDia.comboBox_20.setCurrentIndex(0)
        else:
            msg = "找不到\" " + filePathName + " \"圖層" + "\n請確認路徑"
            QMessageBox.information(self.iface.mainWindow(), "錯誤", msg)

    def queryNo(self):
        registry = QgsProject.instance()
        target_layer = registry.mapLayersByName( '國有林地籍圖' )[0]
        self.iface.setActiveLayer(target_layer)
        expr = QgsExpression( " \"{}\" ='{}' AND \"{}\" ='{}' ".format('段', self.positioningDia.comboBox_8.currentText(), '地號',  self.positioningDia.lineEdit.text()))
        it = target_layer.getFeatures( QgsFeatureRequest( expr ) )
        # it = target_layer.getFeatures( QgsFeatureRequest( expr ) )
        ids = [i.id() for i in it]
        self.iface.activeLayer().removeSelection()
        target_layer.selectByIds( ids )
        self.canvas.zoomToSelected()

        
    # End of Positioning Dialog Function


#########################################


# Cadastre Dialog Function
    def internet_on(self):
      try:
          urlopen('http://maps.nlsc.gov.tw/T09/pro/setCountry.jsp', timeout=1)
          return 1
      except:
          return 0   

    def cadastreDia_show(self):
        if self.internet_on()== 0:
            QMessageBox.information(self.iface.mainWindow(), "錯誤", "請檢查網路連線狀態")
        else:
            self.cadastreDia.comboBox.clear()
            self.cadastreDia.comboBox.insertItem(0, '請選擇縣市')

            getCountyUrl = 'http://maps.nlsc.gov.tw/T09/pro/setCountry.jsp'
            response = urlopen(getCountyUrl)
            xmlDoc = xml.dom.minidom.parse(response)
            root = xmlDoc.documentElement
            countyL = []
            for i in range(0, len(root.getElementsByTagName('name')), 1):
                node = root.getElementsByTagName('name')[i]
                countyID = root.getElementsByTagName('id')[i]
                county = countyID.childNodes[0].data + '-' + node.childNodes[0].data
                countyL.append(county)

            filePath = rootPath + 'countySort.csv'
            countyListfile = open(filePath, 'r')
            csvCursor = csv.reader(countyListfile)

            cL = []
            for row in csvCursor:
                cL.append(row)

            cLD = []
            for i in range(0, len(cL), 1):
                cLD.append(cL[i][1])

            finalList=[]
            for i in range(0, len(cLD), 1):
                if countyL.count(cLD[i]) == 1:
                    finalList.append(cLD[i])

            for i in range(0, len(finalList), 1):
                self.cadastreDia.comboBox.insertItem(i+1, finalList[i])
            self.cadastreDia.show()

    def getTownCode(self, countyID):
        self.cadastreDia.comboBox_3.clear()
        self.cadastreDia.comboBox_2.clear()
        self.cadastreDia.listWidget.clear()
        self.cadastreDia.tableWidget.clearContents()
        self.cadastreDia.tableWidget_2.clearContents()
        self.cadastreDia.tableWidget_3.clearContents()
        self.cadastreDia.tableWidget_4.clearContents()
        self.cadastreDia.comboBox_2.insertItem(0, '請選擇鄉鎮')
        countyToTownUrl = 'http://maps.nlsc.gov.tw/T09/pro/setArea.jsp?city=' + countyID
        response = urlopen(countyToTownUrl)
        xmlDoc = xml.dom.minidom.parse(response)
        root = xmlDoc.documentElement
        nameList = root.getElementsByTagName('name')
        countyIDList = root.getElementsByTagName('id')
        countyList = []
        for i in range(0, len(root.getElementsByTagName('name')), 1):
            name = nameList[i]
            countyID = countyIDList[i]
            county = countyID.childNodes[0].data + '-' + name.childNodes[0].data
            countyList.append(county)
        countyList.sort()
        for i in range(0, len(countyList), 1):
            self.cadastreDia.comboBox_2.insertItem(i+1, countyList[i])

    def getCadastreCode(self, countyID, townID):
        self.cadastreDia.comboBox_3.clear()
        self.cadastreDia.listWidget.clear()
        townToCadastreUrl = 'http://maps.nlsc.gov.tw/T09/pro/setSection.jsp?city=' + countyID + '&area=' + townID
        response = urlopen(townToCadastreUrl)
        xmlDoc = xml.dom.minidom.parse(response)
        root = xmlDoc.documentElement
        nameList = root.getElementsByTagName('name')
        countyIDList = root.getElementsByTagName('id')
        officeIDList = root.getElementsByTagName('office')
        cadastreNameList=[]
        for i in range(0, len(root.getElementsByTagName('name')), 1):
            name = nameList[i]
            countyID = countyIDList[i]
            officeID = officeIDList[i]
            cadastreName = officeID.childNodes[0].data + countyID.childNodes[0].data + '-' + name.childNodes[0].data
            cadastreNameList.append(cadastreName)
        cadastreNameList.sort()
        for i in range(0, len(cadastreNameList), 1):
            self.cadastreDia.comboBox_3.insertItem(i, cadastreNameList[i])

    def countyToTown(self):
        self.cadastreDia.listWidget.clear()
        self.cadastreDia.listWidget_2.clear()
        self.cadastreDia.comboBox_5.clear()
        if self.cadastreDia.comboBox.currentIndex() == 0:
            self.cadastreDia.comboBox_2.clear()
            self.cadastreDia.comboBox_2.setEnabled(False)
            self.cadastreDia.comboBox_3.clear()
            self.cadastreDia.comboBox_3.setEnabled(False)
        else:
            self.getTownCode(self.cadastreDia.comboBox.currentText()[0])
            self.cadastreDia.comboBox_2.setEnabled(True)

    def townToCadastre(self):
        self.cadastreDia.listWidget.clear()
        self.cadastreDia.listWidget_2.clear()
        self.cadastreDia.comboBox_5.clear()
        if self.cadastreDia.comboBox_2.currentIndex() == 0:
            self.cadastreDia.comboBox_3.clear()
            self.cadastreDia.comboBox_3.setEnabled(False)
        else:
            townID = self.cadastreDia.comboBox_2.currentText()[0] + self.cadastreDia.comboBox_2.currentText()[1] + self.cadastreDia.comboBox_2.currentText()[2]
            self.getCadastreCode(self.cadastreDia.comboBox.currentText()[0], townID)
            self.cadastreDia.comboBox_3.setEnabled(True)

    def cadastreToNo(self):
        self.cadastreDia.listWidget.clear()
        self.cadastreDia.listWidget_2.clear()
        self.cadastreDia.comboBox_5.clear()

    def changeCRS(self):
        if self.cadastreDia.comboBox_4.currentIndex()==1:
            crs=QgsCoordinateReferenceSystem("epsg:4326")
            self.cadastreDia.lineEdit_2.setText("121.612359")
            self.cadastreDia.lineEdit_3.setText("25.04219")
        if self.cadastreDia.comboBox_4.currentIndex()==0:
            crs=QgsCoordinateReferenceSystem("epsg:3826")
            self.cadastreDia.lineEdit_2.setText("311791.151")
            self.cadastreDia.lineEdit_3.setText("2770590.391")
    

    # # 取得地號(內網用)
    # def loadWFS(self):
    #     filePath = rootPath + 'cadastreService.csv'
    #     urlPathfile = open(filePath, 'r')
    #     csvCursor = csv.reader(urlPathfile)
    #     urlPathList = []
    #     for row in csvCursor:
    #         urlPathList.append(row)
    #     unit = self.cadastreDia.comboBox_3.currentText()[0] + self.cadastreDia.comboBox_3.currentText()[1]
    #     sec = self.cadastreDia.comboBox_3.currentText()[2] + self.cadastreDia.comboBox_3.currentText()[3] + self.cadastreDia.comboBox_3.currentText()[4] + self.cadastreDia.comboBox_3.currentText()[5]
    #     url_1 =  urlPathList[0][1] + 'LandQuerySec.php?UNIT=' + unit + '&SEC=' + sec + '&ZONE='
    #     response_1 = urlopen(url_1)
    #     html_1 = response_1.read()
    #     j_1 = json.loads(html_1)

    #     # no = j_1['RESPONSE'][0]['NO']
    #     # no.sort()
    #     # self.cadastreDia.listWidget.clear()
    #     # for i in range(0, len(no), 1):
    #     #     self.cadastreDia.listWidget.addItem(no[i])

    #     if j_1['RESPONSE'][0]['NO']!=NULL:
    #         no = j_1['RESPONSE'][0]['NO']            
    #         no.sort()

    #         self.cadastreDia.listWidget.clear()
    #         for i in range(0, len(no), 1):
    #             self.cadastreDia.listWidget.addItem(no[i])

    #     else:
    #         QMessageBox.information(self.iface.mainWindow(), "error",  '此地段查無地號')

        
        
    # 取得地號(教學用)
    def loadWFS(self):
        filePath = rootPath + 'testlandnum.csv'
        landListFile = open(filePath, 'r')        
        csvCursor = csv.reader(landListFile)
        landList = []
        for row in csvCursor:
            landList.append(row)
        
        landList.sort()
        self.cadastreDia.listWidget.clear()
        for i in range(0, len(landList), 1):
            self.cadastreDia.listWidget.addItems(landList[i])

    def cadastreItemDel(self):
        #QMessageBox.information(self.iface.mainWindow(), 'del', 'deldel')
        listItems = self.cadastreDia.listWidget_2.selectedItems()
        
        if not listItems: return        
        
        for item in listItems:
            self.cadastreDia.listWidget_2.takeItem(self.cadastreDia.listWidget_2.row(item))      

        itemList = []

        for i in range(0, self.cadastreDia.listWidget_2.count(), 1):
            itemList.append(self.cadastreDia.listWidget_2.item(i).text())

        items = list(set(itemList))
        
        self.cadastreDia.listWidget_2.clear()
        self.cadastreDia.comboBox_5.clear()

        for i in range(0, len(items), 1):
            #QMessageBox.information(self.iface.mainWindow(),"x",  str(i))
            self.cadastreDia.listWidget_2.addItem(items[i])

        for i in range(0, self.cadastreDia.listWidget_2.count(), 1):  
            self.cadastreDia.comboBox_5.insertItem(i, self.cadastreDia.listWidget_2.item(i).text())


    def addCadastreItem(self):

        out = self.cadastreDia.listWidget.findItems(self.cadastreDia.lineEdit.text(), QtCore.Qt.MatchExactly)
        
        if len(out) != 0:
            self.cadastreDia.listWidget_2.addItem(self.cadastreDia.lineEdit.text())
            itemList = []

            for i in range(0, self.cadastreDia.listWidget_2.count(), 1):
                itemList.append(self.cadastreDia.listWidget_2.item(i).text())

            items = list(set(itemList))
        
            self.cadastreDia.listWidget_2.clear()
            self.cadastreDia.comboBox_5.clear()

            for i in range(0, len(items), 1):
                #QMessageBox.information(self.iface.mainWindow(),"x",  str(i))
                self.cadastreDia.listWidget_2.addItem(items[i])

            for i in range(0, self.cadastreDia.listWidget_2.count(), 1):  
                self.cadastreDia.comboBox_5.insertItem(i, self.cadastreDia.listWidget_2.item(i).text()) 

        else:
            QMessageBox.information(self.iface.mainWindow(), "error",  '輸入地號並不存在此地段!')    


    def copyForm(self):
        if self.cadastreDia.tabWidget_2.currentIndex() == 0:
            rowCount = self.cadastreDia.tableWidget_2.rowCount()
            columnCount = self.cadastreDia.tableWidget_2.columnCount()
            clipboard = []
            for i in range(0, 1, 1):
                clipboard.append([])
                for j in range(0, rowCount, 1):
                    clipboard[i].append(self.cadastreDia.tableWidget_2.verticalHeaderItem(j).text())
            for i in range(0, columnCount, 1):
                clipboard.append([])
                for j in range(0, rowCount, 1):
                    if self.cadastreDia.tableWidget_4.item(j, i) != NULL:
                        clipboard[i+1].append(self.cadastreDia.tableWidget_2.item(j, i).text())
                    else:
                        clipboard[i+1].append('')
            tempStr=''
            for j in range(0, rowCount, 1):
                tempStr += '\n'
                for i in range(0, len(clipboard), 1):
                    tempStr += clipboard[i][j]
                    tempStr += '\t'
            sys_clip = QApplication.clipboard()
            sys_clip.setText(tempStr)

        if self.cadastreDia.tabWidget_2.currentIndex() == 1:
            rowCount = self.cadastreDia.tableWidget.rowCount()
            columnCount = self.cadastreDia.tableWidget.columnCount()
            clipboard = []
            for i in range(0, 1, 1):
                clipboard.append([])
                for j in range(0, rowCount, 1):
                    clipboard[i].append(self.cadastreDia.tableWidget.verticalHeaderItem(j).text())
            for i in range(0, columnCount, 1):
                clipboard.append([])
                for j in range(0, rowCount, 1):
                    if self.cadastreDia.tableWidget_4.item(j, i) != NULL:
                        clipboard[i+1].append(self.cadastreDia.tableWidget.item(j, i).text())
                    else:
                        clipboard[i+1].append('')
            tempStr=''
            for j in range(0, rowCount, 1):
                tempStr += '\n'
                for i in range(0, len(clipboard), 1):
                    tempStr += clipboard[i][j]
                    tempStr += '\t'
            sys_clip = QApplication.clipboard()
            sys_clip.setText(tempStr)

        if self.cadastreDia.tabWidget_2.currentIndex() == 2:
            rowCount = self.cadastreDia.tableWidget_3.rowCount()
            columnCount = self.cadastreDia.tableWidget_3.columnCount()
            clipboard = []
            for i in range(0, 1, 1):
                clipboard.append([])
                for j in range(0, rowCount, 1):
                    clipboard[i].append(self.cadastreDia.tableWidget_3.verticalHeaderItem(j).text())
            for i in range(0, columnCount, 1):
                clipboard.append([])
                for j in range(0, rowCount, 1):
                    if self.cadastreDia.tableWidget_3.item(j, i) != NULL:
                        clipboard[i+1].append(self.cadastreDia.tableWidget_3.item(j, i).text())
                    else:
                        clipboard[i+1].append('')
            tempStr=''
            for j in range(0, rowCount, 1):
                tempStr += '\n'
                for i in range(0, len(clipboard), 1):
                    tempStr += clipboard[i][j]
                    tempStr += '\t'
            sys_clip = QApplication.clipboard()
            sys_clip.setText(tempStr)

        if self.cadastreDia.tabWidget_2.currentIndex() == 3:
            rowCount = self.cadastreDia.tableWidget_4.rowCount()
            columnCount = self.cadastreDia.tableWidget_4.columnCount()
            clipboard = []
            for i in range(0, 1, 1):
                clipboard.append([])
                for j in range(0, rowCount, 1):
                    clipboard[i].append(self.cadastreDia.tableWidget_4.verticalHeaderItem(j).text())
            for i in range(0, columnCount, 1):
                clipboard.append([])
                for j in range(0, rowCount, 1):
                    if self.cadastreDia.tableWidget_4.item(j, i) != NULL:
                        clipboard[i+1].append(self.cadastreDia.tableWidget_4.item(j, i).text())
                    else:
                        clipboard[i+1].append('')
            tempStr=''
            for j in range(0, rowCount, 1):
                tempStr += '\n'
                for i in range(0, len(clipboard), 1):
                    tempStr += clipboard[i][j]
                    tempStr += '\t'
            sys_clip = QApplication.clipboard()
            sys_clip.setText(tempStr)

    # # XY座標取地籍圖(內網用)
    # def loadWFS_XY_Position(self):
    #     if self.cadastreDia.comboBox_4.currentIndex()==0:
    #         srs = "TWD97"
    #     if self.cadastreDia.comboBox_4.currentIndex()==1:
    #         srs = "WGS84"
    #     filePath = rootPath + 'cadastreService.csv'
    #     urlPathfile = open(filePath, 'r')
    #     csvCursor = csv.reader(urlPathfile)
    #     urlPathList = []
    #     for row in csvCursor:
    #         urlPathList.append(row)
    #     url = urlPathList[0][1] + 'LandQuerySecXY.php?x=' + self.cadastreDia.lineEdit_2.text() + "&y=" + self.cadastreDia.lineEdit_3.text() + "&srs=" + srs
    #     response = urlopen(url)
    #     html = response.read()
    #     j = json.loads(html)
    #     unit = j['RESPONSE'][0]['LAND'][0]['UNIT']
    #     sec = j['RESPONSE'][0]['LAND'][0]['SEC']
    #     no = j['RESPONSE'][0]['LAND'][0]['NO']
    #     self.cadastreDia.comboBox_5.clear()
    #     self.cadastreDia.comboBox_5.insertItem(0, no)
    #     uri = urlPathList[0][1] + 'landWFS3.php?LD=' + unit + '&SCNO=' + sec + '&PO=' + no
    #     response = urlopen(uri)
    #     html = response.read()        
    #     if str(html).find('COP') != -1:
    #         QMessageBox.information(self.iface.mainWindow(), "錯誤", "查無此地號地籍圖")
    #     else:
    #         url_1 =  urlPathList[0][1] + 'LandDescription.php?unit=' + unit + '&sec=' + sec + '&no=' + no
    #         response_1 = urlopen(url_1)
    #         html_1 = response_1.read()
    #         if str(html_1).find('COP') != -1:
    #             pass
    #         else:
    #             j_1 = json.loads(html_1)
    #             county_r = j_1['RESPONSE'][0]['RALID']['AA45']
    #             town_r = j_1['RESPONSE'][0]['RALID']['AA46']
    #             unit_r = j_1['RESPONSE'][0]['UNIT']
    #             sec_r = j_1['RESPONSE'][0]['SEC']
    #             no_r = j_1['RESPONSE'][0]['NO']
    #             townID_r = county_r+town_r
    #             townToCadastreUrl = 'http://maps.nlsc.gov.tw/T09/pro/setSection.jsp?city=' + county_r + '&area=' + townID_r
    #             response = urlopen(townToCadastreUrl)
    #             xmlDoc = xml.dom.minidom.parse(response)
    #             root = xmlDoc.documentElement
    #             nameList = root.getElementsByTagName('name')
    #             idList = root.getElementsByTagName('id')
    #             nameNameList=[]
    #             ididList=[]
    #             for i in range(0, len(root.getElementsByTagName('name')), 1):
    #                 ididList.append(idList[i].childNodes[0].data)
    #                 nameNameList.append(nameList[i].childNodes[0].data)
    #             nameBase = unit_r + sec_r + nameNameList[ididList.index(sec_r)]
    #             WFSLayerName = nameBase + '-' +  no_r
    #             response = urlopen(uri)
    #             html = response.read()
    #             urllib.request.urlretrieve(uri,rootPath+'temp/temp.xml')
    #             xmluri = rootPath+'temp/temp.xml'
    #             self.iface.addVectorLayer(xmluri, '', "ogr")                
    #             # self.iface.activeLayer().setLayerName('WFSLayerName')
    #             self.iface.activeLayer().setName(WFSLayerName)
    #             shpName = "%s%s%s%s"%(rootPath, 'temp/', WFSLayerName, '.shp')                
    #             _writer = QgsVectorFileWriter.writeAsVectorFormat(self.iface.activeLayer(), shpName, "utf-8", self.iface.activeLayer().crs(), "ESRI Shapefile")
    #             QgsProject.instance().removeMapLayer(self.iface.activeLayer().id())                
    #             self.iface.addVectorLayer(shpName, WFSLayerName, "ogr")
    #             # layer = QgsVectorLayer(shpName, WFSLayerName, "ogr")                              
    #             pr = self.iface.activeLayer().dataProvider()
    #             features = self.iface.activeLayer().getFeatures() #returns QgsFeature object
    #             for feature in features:
    #                 geom = feature.geometry()
    #             pr.addAttributes( [ QgsField("Name", QVariant.String), QgsField("No", QVariant.String) ] )
    #             self.iface.activeLayer().updateFields()
    #             with edit(self.iface.activeLayer()):
    #                 for feat in self.iface.activeLayer().getFeatures():
    #                     self.iface.activeLayer().deleteFeature(feat.id())
    #             pt = QgsFeature()
    #             pt.setGeometry(geom)
    #             attr = []
    #             attr.append('1')
    #             attr.append(nameBase)
    #             attr.append(no)
    #             pt.setAttributes(attr)
    #             pr.addFeatures([pt])
    #             self.iface.activeLayer().updateExtents()
    #             self.canvas.setExtent(self.iface.activeLayer().extent())
    #             msg = WFSLayerName + '載入完成'
    #             self.iface.mainWindow().statusBar().showMessage(msg)
    #             self.cadastreDia.tabWidget.setCurrentIndex(2)
    #             if j_1['RESPONSE'][0]['RALID']!=NULL:
    #                 AA05 = j_1['RESPONSE'][0]['RALID']['AA05']
    #                 AA05_str = AA05[0:3] + '年' + AA05[3:5] + '月' + AA05[5:7] + '日'
    #                 AA06 = j_1['RESPONSE'][0]['RALID']['AA06']
    #                 url_reason_1 =  urlPathList[0][1] + 'QueryReason.php?UNIT=' + unit
    #                 response_reason_1 = urlopen(url_reason_1)
    #                 html_reason_1 = response_reason_1.read()
    #                 j_reason_1 = json.loads(html_reason_1)
    #                 reason_1_dict = {}
    #                 reason_1_keys = range(len(j_reason_1['RESPONSE'][0]['DATA']))
    #                 for i in reason_1_keys:
    #                     reason_1_dict[i] = j_reason_1['RESPONSE'][0]['DATA'][i]['CODE']
    #                 reason_1_dict_invert = {v: k for k, v in reason_1_dict.items()}
    #                 AA06_str = j_reason_1['RESPONSE'][0]['DATA'][reason_1_dict_invert.get(AA06)]['NAME']
    #                 AA10 = j_1['RESPONSE'][0]['RALID']['AA10']
    #                 AA11 = j_1['RESPONSE'][0]['RALID']['AA11']
    #                 url_useZone_1 =  urlPathList[0][1] + 'QueryZone.php'
    #                 response_useZone_1 = urlopen(url_useZone_1)
    #                 html_useZone_1 = response_useZone_1.read()
    #                 j_useZone_1 = json.loads(html_useZone_1)
    #                 useZone_1_dict = {}
    #                 useZone_1_keys = range(len(j_useZone_1['RESPONSE']))
    #                 for i in useZone_1_keys:
    #                     useZone_1_dict[i] = j_useZone_1['RESPONSE'][i]['CODE']
    #                 useZone_1_dict_invert = {v: k for k, v in useZone_1_dict.items()}
    #                 if useZone_1_dict_invert.get(AA11)!=None:
    #                     AA11_str = j_useZone_1['RESPONSE'][useZone_1_dict_invert.get(AA11)]['NAME']
    #                 else:
    #                     AA11_str = ''
    #                 AA12 = j_1['RESPONSE'][0]['RALID']['AA12']
    #                 AA16 = j_1['RESPONSE'][0]['RALID']['AA16']
    #                 AA17 = j_1['RESPONSE'][0]['RALID']['AA17']
    #                 AA45 = j_1['RESPONSE'][0]['RALID']['AA45']
    #                 AA45_str = ''
    #                 url_city_1 =  urlPathList[0][1] + 'QueryCity.php'
    #                 response_city_1 = urlopen(url_city_1)
    #                 html_city_1 = response_city_1.read()
    #                 j_city_1 = json.loads(html_city_1)
    #                 city_1_dict = {}
    #                 city_1_keys = range(len(j_city_1['RESPONSE']))
    #                 for i in city_1_keys:
    #                     city_1_dict[i] = j_city_1['RESPONSE'][i]['CODE']
    #                 city_1_dict_invert = {v: k for k, v in city_1_dict.items()}
    #                 if city_1_dict_invert.get(AA45)!=None:
    #                     AA45_str = j_city_1['RESPONSE'][city_1_dict_invert.get(AA45)]['NAME']
    #                 AA46 = j_1['RESPONSE'][0]['RALID']['AA46']
    #                 url_town_1 =  urlPathList[0][1] + 'QueryTown.php?city=' + AA45
    #                 response_town_1 = urlopen(url_town_1)
    #                 html_town_1 = response_town_1.read()
    #                 j_town_1 = json.loads(html_town_1)
    #                 town_1_dict = {}
    #                 AA46_str = ''
    #                 town_1_keys = range(len(j_town_1['RESPONSE'][0]['TOWN']))
    #                 for i in town_1_keys:
    #                     town_1_dict[i] = j_town_1['RESPONSE'][0]['TOWN'][i]['CODE']
    #                 town_1_dict_invert = {v: k for k, v in town_1_dict.items()}
    #                 if town_1_dict_invert.get(AA46)!=None:
    #                     AA46_str = j_town_1['RESPONSE'][0]['TOWN'][town_1_dict_invert.get(AA46)]['NAME']
    #                 AA23 = j_1['RESPONSE'][0]['RALID']['AA23']
    #                 BUILDINGCOUNT = j_1['RESPONSE'][0]['RALID']['BUILDINGCOUNT']
    #                 url_1_1 =  urlPathList[0][1] + 'QueryReason.php?UNIT=' + unit
    #                 self.cadastreDia.tableWidget_2.setItem(0,  0, QTableWidgetItem(nameBase))
    #                 self.cadastreDia.tableWidget_2.setItem(0,  1, QTableWidgetItem(no))
    #                 self.cadastreDia.tableWidget_2.setItem(0,  2, QTableWidgetItem(AA05_str))
    #                 self.cadastreDia.tableWidget_2.setItem(0,  3, QTableWidgetItem(AA06_str))
    #                 self.cadastreDia.tableWidget_2.setItem(0,  4, QTableWidgetItem(AA10))
    #                 self.cadastreDia.tableWidget_2.setItem(0,  5, QTableWidgetItem(AA11_str))
    #                 self.cadastreDia.tableWidget_2.setItem(0,  6, QTableWidgetItem(AA12))
    #                 self.cadastreDia.tableWidget_2.setItem(0,  7, QTableWidgetItem(AA16))
    #                 self.cadastreDia.tableWidget_2.setItem(0,  8, QTableWidgetItem(AA17))
    #                 self.cadastreDia.tableWidget_2.setItem(0,  9, QTableWidgetItem(AA45_str))
    #                 self.cadastreDia.tableWidget_2.setItem(0, 10, QTableWidgetItem(AA46_str))
    #                 self.cadastreDia.tableWidget_2.setItem(0, 11, QTableWidgetItem(AA23))
    #                 self.cadastreDia.tableWidget_2.setItem(0, 12, QTableWidgetItem(BUILDINGCOUNT))
    #                 self.cadastreDia.tableWidget_2.resizeColumnsToContents()
    #         self.cadastreDia.tableWidget.setItem(0, 0, QTableWidgetItem(self.cadastreDia.comboBox_3.currentText()))
    #         self.cadastreDia.tableWidget.setItem(0, 1, QTableWidgetItem(no))
    #         url_2 =  urlPathList[0][1] + 'LandOwnership.php?UNIT=' + unit + '&SEC=' + sec + '&NO=' + no + '&OFFSET=1&LIMIT=10'
    #         response_2 = urlopen(url_2)
    #         html_2 = response_2.read()
    #         if str(html_2).find('COP') != -1:
    #             pass
    #         else:
    #             j_2 = json.loads(html_2)
    #             if j_2['RETURNROWS']!=0:
    #                 j_2_count = len(j_2['RESPONSE'])
    #                 rowPosition = self.cadastreDia.tableWidget.rowCount()
    #                 self.cadastreDia.tableWidget.setColumnCount(j_2_count)
    #                 for i in range(0, j_2_count, 1):
    #                     if j_2['RESPONSE']!=NULL:
    #                         if len(j_2['RESPONSE'][i]['RBLOW'])!=0:
    #                             BB05 = j_2['RESPONSE'][i]['RBLOW'][0]['BB05']
    #                             BB05_str = BB05[0:3] + '年' + BB05[3:5] + '月' + BB05[5:7] + '日'
    #                             BB06 = j_2['RESPONSE'][i]['RBLOW'][0]['BB06']
    #                             url_reason_2 =  urlPathList[0][1] + 'QueryReason.php?UNIT=' + unit
    #                             response_reason_2 = urlopen(url_reason_2)
    #                             html_reason_2 = response_reason_2.read()
    #                             j_reason_2 = json.loads(html_reason_2)
    #                             reason_2_dict = {}
    #                             reason_2_keys = range(len(j_reason_2['RESPONSE'][0]['DATA']))
    #                             for p in reason_2_keys:
    #                                 reason_2_dict[p] = j_reason_2['RESPONSE'][0]['DATA'][p]['CODE']
    #                             reason_2_dict_invert = {v: k for k, v in reason_2_dict.items()}
    #                             BB06_str = j_reason_2['RESPONSE'][0]['DATA'][reason_2_dict_invert.get(BB06)]['NAME']
    #                             BB07 = j_2['RESPONSE'][i]['RBLOW'][0]['BB07']
    #                             BB07_str = BB07[0:3] + '年' + BB07[3:5] + '月' + BB07[5:7] + '日'
    #                             url_rights_2 =  urlPathList[0][1] + 'QueryRights.php'
    #                             response_rights_2 = urlopen(url_rights_2)
    #                             html_rights_2 = response_rights_2.read()
    #                             j_rights_2 = json.loads(html_rights_2)
    #                             BB15_1 = j_2['RESPONSE'][i]['RBLOW'][0]['BB15_1']
    #                             rights_2_dict = {}
    #                             rights_2_keys = range(len(j_rights_2['RESPONSE']))
    #                             for m in rights_2_keys:
    #                                 rights_2_dict[m] = j_rights_2['RESPONSE'][m]['CODE']
    #                             rights_2_dict_invert = {v: k for k, v in rights_2_dict.items()}
    #                             if rights_2_dict_invert.get(BB15_1)!=None:
    #                                 BB15_1_str = j_rights_2['RESPONSE'][rights_2_dict_invert.get(BB15_1)]['NAME']
    #                             else:
    #                                 BB15_1_str=''
    #                             BB15_2 = j_2['RESPONSE'][i]['RBLOW'][0]['BB15_2']
    #                             BB15_3 = j_2['RESPONSE'][i]['RBLOW'][0]['BB15_3']
    #                             BB03 = j_2['RESPONSE'][i]['RBLOW'][0]['BB03']
    #                             if BB03 !=NULL:
    #                                 BB03_str = BB03[0:3] + '年' + BB03[3:5] + '月' + BB03[5:7] + '日'
    #                             else:
    #                                 BB03_str = BB03
    #                             BB04_1 = j_2['RESPONSE'][i]['RBLOW'][0]['BB04_1']
    #                             BB04_2 = j_2['RESPONSE'][i]['RBLOW'][0]['BB04_2']
    #                             BB21 = j_2['RESPONSE'][i]['RBLOW'][0]['BB21']
    #                             self.cadastreDia.tableWidget.setItem( 0, i, QTableWidgetItem(nameBase))
    #                             self.cadastreDia.tableWidget.setItem( 1, i, QTableWidgetItem(no))
    #                             self.cadastreDia.tableWidget.setItem( 2, i, QTableWidgetItem(BB05_str))
    #                             self.cadastreDia.tableWidget.setItem( 3, i, QTableWidgetItem(BB06_str))
    #                             self.cadastreDia.tableWidget.setItem( 4, i, QTableWidgetItem(BB07_str))
    #                             self.cadastreDia.tableWidget.setItem( 5, i, QTableWidgetItem(BB15_1_str))
    #                             self.cadastreDia.tableWidget.setItem( 6, i, QTableWidgetItem(BB15_2))
    #                             self.cadastreDia.tableWidget.setItem( 7, i, QTableWidgetItem(BB15_3))
    #                             self.cadastreDia.tableWidget.setItem( 8, i, QTableWidgetItem(BB03))
    #                             self.cadastreDia.tableWidget.setItem( 9, i, QTableWidgetItem(BB04_1))
    #                             self.cadastreDia.tableWidget.setItem(10, i, QTableWidgetItem(BB04_2))
    #                             self.cadastreDia.tableWidget.setItem(11, i, QTableWidgetItem(BB04_2))
    #                     else:
    #                         self.cadastreDia.tableWidget.setColumnCount(1)
    #                 self.cadastreDia.tableWidget.resizeColumnsToContents()
    #         self.cadastreDia.tableWidget_3.setItem(0, 0, QTableWidgetItem(self.cadastreDia.comboBox_3.currentText()))
    #         self.cadastreDia.tableWidget_3.setItem(0, 1, QTableWidgetItem(no))
    #         url_3 = urlPathList[0][1] + 'LandOtherRights.php?UNIT=' + unit + '&SEC=' + sec + '&NO=' + no + '&OFFSET=1&LIMIT=10'
    #         response_3 = urlopen(url_3)
    #         html_3 = response_3.read()
    #         if str(html_3).find('COP') != -1:
    #             pass
    #         else:
    #             j_3 = json.loads(html_3)
    #             if j_3['RETURNROWS']!=0:
    #                 j_3_count = len(j_3['RESPONSE'])
    #                 rowPosition = self.cadastreDia.tableWidget_3.rowCount()
    #                 self.cadastreDia.tableWidget_3.setColumnCount(j_3_count)
    #                 for i in range(0, j_3_count, 1):
    #                     if j_3['RESPONSE']!=NULL:
    #                         if len(j_3['RESPONSE'][i]['RCLOR'])!=0:
    #                             CC01 = j_3['RESPONSE'][i]['RCLOR'][0]['CC01']
    #                             CC03 = j_3['RESPONSE'][i]['RCLOR'][0]['CC03']
    #                             CC04_1 = j_3['RESPONSE'][i]['RCLOR'][0]['CC04_1']
    #                             CC04_2 = j_3['RESPONSE'][i]['RCLOR'][0]['CC04_2']
    #                             CC05 = j_3['RESPONSE'][i]['RCLOR'][0]['CC05']
    #                             CC05_str = CC05[0:3] + '年' + CC05[3:5] + '月' + CC05[5:7] + '日'
    #                             CC06 = j_3['RESPONSE'][i]['RCLOR'][0]['CC06']
    #                             url_reason_3 =  urlPathList[0][1] + 'QueryReason.php?UNIT=' + unit
    #                             response_reason_3 = urlopen(url_reason_3)
    #                             html_reason_3 = response_reason_3.read()
    #                             j_reason_3 = json.loads(html_reason_3)
    #                             reason_3_dict = {}
    #                             reason_3_keys = range(len(j_reason_3['RESPONSE'][0]['DATA']))
    #                             for ii in reason_3_keys:
    #                                 reason_3_dict[ii] = j_reason_3['RESPONSE'][0]['DATA'][ii]['CODE']
    #                             reason_3_dict_invert = {v: k for k, v in reason_3_dict.items()}
    #                             if rights_2_dict_invert.get(CC06)!=None:
    #                                 CC06_str = j_reason_3['RESPONSE'][0]['DATA'][reason_3_dict_invert.get(CC06)]['NAME']
    #                             else:
    #                                 CC06_str=''
    #                             CC15_1 = j_3['RESPONSE'][i]['RCLOR'][0]['CC15_1']
    #                             url_rights_3 =  urlPathList[0][1] + 'QueryRights.php'
    #                             response_rights_3 = urlopen(url_rights_3)
    #                             html_rights_3 = response_rights_3.read()
    #                             j_rights_3 = json.loads(html_rights_3)
    #                             rights_3_dict = {}
    #                             rights_3_keys = range(len(j_rights_3['RESPONSE']))
    #                             for n in rights_3_keys:
    #                                 rights_3_dict[n] = j_rights_3['RESPONSE'][n]['CODE']
    #                             rights_3_dict_invert = {v: k for k, v in rights_3_dict.items()}
    #                             if rights_3_dict_invert.get(CC15_1)!=None:
    #                                 CC15_1_str = j_rights_3['RESPONSE'][rights_3_dict_invert.get(CC15_1)]['NAME']
    #                             else:
    #                                 CC15_1_str=''
    #                             CC15_2 = j_3['RESPONSE'][i]['RCLOR'][0]['CC15_2']
    #                             CC15_3 = j_3['RESPONSE'][i]['RCLOR'][0]['CC15_3']
    #                             CC15_4 = j_3['RESPONSE'][i]['RCLOR'][0]['CC15_4']
    #                             CC16 = j_3['RESPONSE'][i]['RCLOR'][0]['CC16']
    #                             CC18_1 = j_3['RESPONSE'][i]['RCLOR'][0]['CC18_1']
    #                             url_LoanRight_3 =  urlPathList[0][1] + 'QueryLoanRightsRange.php'
    #                             response_LoanRight_3 = urlopen(url_LoanRight_3)
    #                             html_LoanRight_3 = response_LoanRight_3.read()
    #                             j_LoanRight_3 = json.loads(html_LoanRight_3)
    #                             LoanRight_3_dict = {}
    #                             LoanRight_3_keys = range(len(j_LoanRight_3['RESPONSE']))
    #                             for m in LoanRight_3_keys:
    #                                 LoanRight_3_dict[m] = j_LoanRight_3['RESPONSE'][m]['CODE']
    #                             LoanRight_3_dict_invert = {v: k for k, v in LoanRight_3_dict.items()}
    #                             if LoanRight_3_dict_invert.get(CC18_1)!=None:
    #                                 CC18_1_str = j_LoanRight_3['RESPONSE'][LoanRight_3_dict_invert.get(CC18_1)]['NAME']
    #                             else:
    #                                 CC18_1_str=''
    #                             CC18_2 = j_3['RESPONSE'][i]['RCLOR'][0]['CC18_2']
    #                             CC18_3 = j_3['RESPONSE'][i]['RCLOR'][0]['CC18_3']
    #                             CC27 = j_3['RESPONSE'][i]['RCLOR'][0]['CC27']
    #                             url_rightstype_3 =  urlPathList[0][1] + 'QueryRightsAndTypes.php'
    #                             response_rightstype_3 = urlopen(url_rightstype_3)
    #                             html_rightstype_3 = response_rightstype_3.read()
    #                             j_rightstype_3 = json.loads(html_rightstype_3)
    #                             rightstype_3_dict = {}
    #                             rightstype_3_keys = range(len(j_rightstype_3['RESPONSE']))
    #                             for o in rightstype_3_keys:
    #                                 rightstype_3_dict[o] = j_rightstype_3['RESPONSE'][o]['CODE']
    #                             rightstype_3_dict_invert = {v: k for k, v in rightstype_3_dict.items()}
    #                             if rightstype_3_dict_invert.get(CC27)!=None:
    #                                 CC27_str = j_rightstype_3['RESPONSE'][rightstype_3_dict_invert.get(CC27)]['NAME']
    #                             else:
    #                                 CC27_str=''
    #                             CC28_1 = j_3['RESPONSE'][i]['RCLOR'][0]['CC28_1']
    #                             url_goaltype_3 =  urlPathList[0][1] + 'QueryRightsAndTypes.php'
    #                             response_goaltype_3 = urlopen(url_goaltype_3)
    #                             html_goaltype_3 = response_goaltype_3.read()
    #                             j_goaltype_3 = json.loads(html_goaltype_3)
    #                             goaltype_3_dict = {}
    #                             goaltype_3_keys = range(len(j_goaltype_3['RESPONSE']))
    #                             for p in goaltype_3_keys:
    #                                 goaltype_3_dict[p] = j_goaltype_3['RESPONSE'][p]['CODE']
    #                             goaltype_3_dict_invert = {v: k for k, v in goaltype_3_dict.items()}
    #                             if goaltype_3_dict_invert.get(CC28_1)!=None:
    #                                 CC28_1_str = j_goaltype_3['RESPONSE'][goaltype_3_dict_invert.get(CC28_1)]['NAME']
    #                             else:
    #                                 CC28_1_str=''
    #                             self.cadastreDia.tableWidget_3.setItem(0,  i, QTableWidgetItem(nameBase))
    #                             self.cadastreDia.tableWidget_3.setItem(1,  i, QTableWidgetItem(no))
    #                             self.cadastreDia.tableWidget_3.setItem(2,  i, QTableWidgetItem(CC01))
    #                             self.cadastreDia.tableWidget_3.setItem(3,  i, QTableWidgetItem(CC03))
    #                             self.cadastreDia.tableWidget_3.setItem(4,  i, QTableWidgetItem(CC04_1))
    #                             self.cadastreDia.tableWidget_3.setItem(5,  i, QTableWidgetItem(CC04_2))
    #                             self.cadastreDia.tableWidget_3.setItem(6,  i, QTableWidgetItem(CC05_str))
    #                             self.cadastreDia.tableWidget_3.setItem(7,  i, QTableWidgetItem(CC06_str))
    #                             self.cadastreDia.tableWidget_3.setItem(8,  i, QTableWidgetItem(CC15_1_str))
    #                             self.cadastreDia.tableWidget_3.setItem(9,  i, QTableWidgetItem(CC15_2))
    #                             self.cadastreDia.tableWidget_3.setItem(10, i, QTableWidgetItem(CC15_3))
    #                             self.cadastreDia.tableWidget_3.setItem(11, i, QTableWidgetItem(CC15_4))
    #                             self.cadastreDia.tableWidget_3.setItem(12, i, QTableWidgetItem(CC16))
    #                             self.cadastreDia.tableWidget_3.setItem(13, i, QTableWidgetItem(CC18_1_str))
    #                             self.cadastreDia.tableWidget_3.setItem(14, i, QTableWidgetItem(CC18_2))
    #                             self.cadastreDia.tableWidget_3.setItem(15, i, QTableWidgetItem(CC18_3))
    #                             self.cadastreDia.tableWidget_3.setItem(16, i, QTableWidgetItem(CC27_str))
    #                             self.cadastreDia.tableWidget_3.setItem(17, i, QTableWidgetItem(CC28_1_str))
    #                     else:
    #                         self.cadastreDia.tableWidget_3.setColumnCount(1)
    #                 self.cadastreDia.tableWidget_3.resizeColumnsToContents()
    #             self.cadastreDia.tableWidget_4.setItem(0, 0, QTableWidgetItem(self.cadastreDia.comboBox_3.currentText()))
    #             self.cadastreDia.tableWidget_4.setItem(0, 1, QTableWidgetItem(no))
    #             url_4 =  urlPathList[0][1] + 'BuildingDescription.php?unit=' + unit + '&sec=' + sec + '&no=' + no
    #             response_4 = urlopen(url_4)
    #             html_4 = response_4.read()
    #             if str(html_4).find('COP') != -1:
    #                 pass
    #             else:
    #                 j_4 = json.loads(html_4)
    #                 if j_4['RESPONSE'][0]['RDBID']!=NULL:
    #                     DD05 = j_4['RESPONSE'][0]['RDBID']['DD05']
    #                     self.cadastreDia.tableWidget_4.setItem(0,  0, QTableWidgetItem(nameBase))
    #                     self.cadastreDia.tableWidget_4.setItem(0,  1, QTableWidgetItem(no))
    #                     self.cadastreDia.tableWidget_4.setItem(0,  2, QTableWidgetItem(DD05))
    #                     self.cadastreDia.tableWidget_4.resizeColumnsToContents()

    #     self.cadastre_reset()
    #     self.cadastreDia.tabWidget.setCurrentIndex(2)

    # 輸入XY座標載入地籍圖(教學用)
    def loadWFS_XY_Position(self):
        filePath = rootPath + '\\temp\\landtest2.shp'
        self.iface.addVectorLayer(filePath, "", "ogr")

    # #載入地籍圖 圖層(內網用)
    # def loadMultiCadastre(self):
    #     filePath = rootPath + 'cadastreService.csv'
    #     urlPathfile = open(filePath, 'r')
    #     csvCursor = csv.reader(urlPathfile)
    #     urlPathList = []
    #     for row in csvCursor:
    #         urlPathList.append(row)
    #     unit = self.cadastreDia.comboBox_3.currentText()[0] + self.cadastreDia.comboBox_3.currentText()[1]
    #     sec  = self.cadastreDia.comboBox_3.currentText()[2] + self.cadastreDia.comboBox_3.currentText()[3] + self.cadastreDia.comboBox_3.currentText()[4] + self.cadastreDia.comboBox_3.currentText()[5]
    #     no = []
    #     for i in range(0, self.cadastreDia.listWidget_2.count(), 1):
    #         no.append(self.cadastreDia.listWidget_2.item(i).text())
    #     url_1 = urlPathList[0][1] + 'QueryByUnit.php?unit=' + unit
    #     response_1 = urlopen(url_1)
    #     html_1 = response_1.read()
    #     j_1 = json.loads(html_1)
    #     j_1_dict = {}
    #     j_1_keys = range(len(j_1['RESPONSE'][0]['SECTION']))
    #     for i in j_1_keys:
    #         j_1_dict[i] = j_1['RESPONSE'][0]['SECTION'][i]['SEC']
    #     j_1_dict_invert = {v: k for k, v in j_1_dict.items()}
    #     for i in range(0, len(no), 1):
    #         uri = urlPathList[0][1] + 'landWFS3.php?LD=' + unit + '&SCNO=' + sec + '&PO=' + no[i]
    #         nameBase = unit + sec + j_1['RESPONSE'][0]['SECTION'][j_1_dict_invert.get(sec)]['NAME']
    #         WFSLayerName = nameBase + '-' +  no[i]            
    #         response = urlopen(uri)                       
    #         html = response.read()
    #         urllib.request.urlretrieve(uri,rootPath+'temp/temp.xml')
    #         xmluri = rootPath+'temp/temp.xml'            
    #         self.iface.addVectorLayer(xmluri, '', "ogr")                        
    #         # self.iface.activeLayer().setLayerName(WFSLayerName)
    #         self.iface.activeLayer().setName(WFSLayerName)            
    #         shpName = "%s%s%s%s"%(rootPath, 'temp/', WFSLayerName, '.shp')
    #         _writer = QgsVectorFileWriter.writeAsVectorFormat(self.iface.activeLayer(), shpName, "utf-8", self.iface.activeLayer().crs(), "ESRI Shapefile")
    #         QgsProject.instance().removeMapLayer(self.iface.activeLayer().id())
            
    #         self.iface.addVectorLayer(shpName, WFSLayerName, "ogr")          
    #         pr = self.iface.activeLayer().dataProvider()
    #         features = self.iface.activeLayer().getFeatures() #returns QgsFeature object
    #         for feature in features:
    #             geom = feature.geometry()
    #         pr.addAttributes( [ QgsField("Name", QVariant.String), QgsField("No", QVariant.String) ] )
    #         self.iface.activeLayer().updateFields()
    #         with edit(self.iface.activeLayer()):
    #             for feat in self.iface.activeLayer().getFeatures():
    #                 self.iface.activeLayer().deleteFeature(feat.id())
    #         pt = QgsFeature()
    #         pt.setGeometry(geom)
    #         attr = []
    #         attr.append('1')
    #         attr.append(nameBase)
    #         attr.append(no[i])
    #         pt.setAttributes(attr)
    #         pr.addFeatures([pt])
    #         self.iface.activeLayer().updateExtents()

    #         self.canvas.zoomToFullExtent()
    #         msg = WFSLayerName + '載入完成'
    #         self.iface.mainWindow().statusBar().showMessage(msg)
    #     self.cadastrePosition(unit, sec, no[0])

    # 地籍圖載入圖層(教學用)
    def loadMultiCadastre(self):
        filePath = rootPath + '\\temp\\landtest.shp'
        self.iface.addVectorLayer(filePath, "", "ogr")
        # self.iface.addVectorLayer(r'C:\Users\vincentlu\Desktop\台北市\林務局轄管地籍圖107Jun_A臺北市.shp', "", "ogr")
        
        

    def updateCadastreInfo(self):
        unit = self.cadastreDia.comboBox_3.currentText()[0] + self.cadastreDia.comboBox_3.currentText()[1]
        sec  = self.cadastreDia.comboBox_3.currentText()[2] + self.cadastreDia.comboBox_3.currentText()[3] + self.cadastreDia.comboBox_3.currentText()[4] + self.cadastreDia.comboBox_3.currentText()[5]
        no   = self.cadastreDia.comboBox_5.currentText()
        self.cadastrePosition(unit, sec, no)

    def cadastrePosition(self, unit, sec, no):
        filePath = rootPath + 'cadastreService.csv'
        urlPathfile = open(filePath, 'r')
        csvCursor = csv.reader(urlPathfile)
        urlPathList = []
        for row in csvCursor:
            urlPathList.append(row)
        uri = urlPathList[0][1] + 'landWFS3.php?LD=' + unit + '&SCNO=' + sec + '&PO=' + no
        response = urlopen(uri)
        html = response.read()        
        if str(html).find('COP') != -1:
            pass
        else:
            url_1 =  urlPathList[0][1] + 'LandDescription.php?unit=' + unit + '&sec=' + sec + '&no=' + no
            response_1 = urlopen(url_1)
            html_1 = response_1.read()
            if str(html_1).find('COP') != -1:
                pass
            else:
                j_1 = json.loads(html_1)
                county_r = j_1['RESPONSE'][0]['RALID']['AA45']
                town_r = j_1['RESPONSE'][0]['RALID']['AA46']
                unit_r = j_1['RESPONSE'][0]['UNIT']
                sec_r = j_1['RESPONSE'][0]['SEC']
                no_r = j_1['RESPONSE'][0]['NO']
                townID_r = county_r+town_r
                townToCadastreUrl = 'http://maps.nlsc.gov.tw/T09/pro/setSection.jsp?city=' + county_r + '&area=' + townID_r
                response = urlopen(townToCadastreUrl)
                xmlDoc = xml.dom.minidom.parse(response)
                root = xmlDoc.documentElement
                nameList = root.getElementsByTagName('name')
                idList = root.getElementsByTagName('id')
                nameNameList=[]
                ididList=[]
                for i in range(0, len(root.getElementsByTagName('name')), 1):
                    ididList.append(idList[i].childNodes[0].data)
                    nameNameList.append(nameList[i].childNodes[0].data)
                nameBase = unit_r + sec_r + nameNameList[ididList.index(sec_r)]
                WFSLayerName = nameBase + '-' +  no_r
                response = urlopen(uri)
                html = response.read()
                if j_1['RESPONSE'][0]['RALID']!=NULL:
                    AA05 = j_1['RESPONSE'][0]['RALID']['AA05']
                    AA05_str = AA05[0:3] + '年' + AA05[3:5] + '月' + AA05[5:7] + '日'
                    AA06 = j_1['RESPONSE'][0]['RALID']['AA06']
                    url_reason_1 =  urlPathList[0][1] + 'QueryReason.php?UNIT=' + unit
                    response_reason_1 = urlopen(url_reason_1)
                    html_reason_1 = response_reason_1.read()
                    j_reason_1 = json.loads(html_reason_1)
                    reason_1_dict = {}
                    reason_1_keys = range(len(j_reason_1['RESPONSE'][0]['DATA']))
                    for i in reason_1_keys:
                        reason_1_dict[i] = j_reason_1['RESPONSE'][0]['DATA'][i]['CODE']
                    reason_1_dict_invert = {v: k for k, v in reason_1_dict.items()}
                    AA06_str = j_reason_1['RESPONSE'][0]['DATA'][reason_1_dict_invert.get(AA06)]['NAME']
                    AA10 = j_1['RESPONSE'][0]['RALID']['AA10']
                    AA11 = j_1['RESPONSE'][0]['RALID']['AA11']
                    url_useZone_1 =  urlPathList[0][1] + 'QueryZone.php'
                    response_useZone_1 = urlopen(url_useZone_1)
                    html_useZone_1 = response_useZone_1.read()
                    j_useZone_1 = json.loads(html_useZone_1)
                    useZone_1_dict = {}
                    useZone_1_keys = range(len(j_useZone_1['RESPONSE']))
                    for i in useZone_1_keys:
                        useZone_1_dict[i] = j_useZone_1['RESPONSE'][i]['CODE']
                    useZone_1_dict_invert = {v: k for k, v in useZone_1_dict.items()}
                    if useZone_1_dict_invert.get(AA11)!=None:
                        AA11_str = j_useZone_1['RESPONSE'][useZone_1_dict_invert.get(AA11)]['NAME']
                    else:
                        AA11_str = ''
                    AA12 = j_1['RESPONSE'][0]['RALID']['AA12']
                    AA16 = j_1['RESPONSE'][0]['RALID']['AA16']
                    AA17 = j_1['RESPONSE'][0]['RALID']['AA17']
                    AA45 = j_1['RESPONSE'][0]['RALID']['AA45']
                    AA45_str = ''
                    url_city_1 =  urlPathList[0][1] + 'QueryCity.php'
                    response_city_1 = urlopen(url_city_1)
                    html_city_1 = response_city_1.read()
                    j_city_1 = json.loads(html_city_1)
                    city_1_dict = {}
                    city_1_keys = range(len(j_city_1['RESPONSE']))
                    for i in city_1_keys:
                        city_1_dict[i] = j_city_1['RESPONSE'][i]['CODE']
                    city_1_dict_invert = {v: k for k, v in city_1_dict.items()}
                    if city_1_dict_invert.get(AA45)!=None:
                        AA45_str = j_city_1['RESPONSE'][city_1_dict_invert.get(AA45)]['NAME']
                    AA46 = j_1['RESPONSE'][0]['RALID']['AA46']
                    url_town_1 =  urlPathList[0][1] + 'QueryTown.php?city=' + AA45
                    response_town_1 = urlopen(url_town_1)
                    html_town_1 = response_town_1.read()
                    j_town_1 = json.loads(html_town_1)
                    town_1_dict = {}
                    AA46_str = ''
                    town_1_keys = range(len(j_town_1['RESPONSE'][0]['TOWN']))
                    for i in town_1_keys:
                        town_1_dict[i] = j_town_1['RESPONSE'][0]['TOWN'][i]['CODE']
                    town_1_dict_invert = {v: k for k, v in town_1_dict.items()}
                    if town_1_dict_invert.get(AA46)!=None:
                        AA46_str = j_town_1['RESPONSE'][0]['TOWN'][town_1_dict_invert.get(AA46)]['NAME']
                    AA23 = j_1['RESPONSE'][0]['RALID']['AA23']
                    BUILDINGCOUNT = j_1['RESPONSE'][0]['RALID']['BUILDINGCOUNT']
                    url_1_1 =  urlPathList[0][1] + 'QueryReason.php?UNIT=' + unit
                    self.cadastreDia.tableWidget_2.setItem(0,  0, QTableWidgetItem(nameBase))
                    self.cadastreDia.tableWidget_2.setItem(0,  1, QTableWidgetItem(no))
                    self.cadastreDia.tableWidget_2.setItem(0,  2, QTableWidgetItem(AA05_str))
                    self.cadastreDia.tableWidget_2.setItem(0,  3, QTableWidgetItem(AA06_str))
                    self.cadastreDia.tableWidget_2.setItem(0,  4, QTableWidgetItem(AA10))
                    self.cadastreDia.tableWidget_2.setItem(0,  5, QTableWidgetItem(AA11_str))
                    self.cadastreDia.tableWidget_2.setItem(0,  6, QTableWidgetItem(AA12))
                    self.cadastreDia.tableWidget_2.setItem(0,  7, QTableWidgetItem(AA16))
                    self.cadastreDia.tableWidget_2.setItem(0,  8, QTableWidgetItem(AA17))
                    self.cadastreDia.tableWidget_2.setItem(0,  9, QTableWidgetItem(AA45_str))
                    self.cadastreDia.tableWidget_2.setItem(0, 10, QTableWidgetItem(AA46_str))
                    self.cadastreDia.tableWidget_2.setItem(0, 11, QTableWidgetItem(AA23))
                    self.cadastreDia.tableWidget_2.setItem(0, 12, QTableWidgetItem(BUILDINGCOUNT))
                    self.cadastreDia.tableWidget_2.resizeColumnsToContents()

        self.cadastreDia.tableWidget.setItem(0, 0, QtWidgets.QTableWidgetItem(self.cadastreDia.comboBox_3.currentText()))
        self.cadastreDia.tableWidget.setItem(0, 1, QtWidgets.QTableWidgetItem(no))

        url_2 =  urlPathList[0][1] + 'LandOwnership.php?UNIT=' + unit + '&SEC=' + sec + '&NO=' + no + '&OFFSET=1&LIMIT=10'
        response_2 = urlopen(url_2)
        html_2 = response_2.read()
        if str(html_2).find('COP') != -1:
            pass
        else:
            j_2 = json.loads(html_2)
            if j_2['RETURNROWS']!=0:
                j_2_count = len(j_2['RESPONSE'])
                rowPosition = self.cadastreDia.tableWidget.rowCount()
                self.cadastreDia.tableWidget.setColumnCount(j_2_count)
                for i in range(0, j_2_count, 1):
                    if j_2['RESPONSE']!=NULL:
                        if len(j_2['RESPONSE'][i]['RBLOW'])!=0:
                            BB05 = j_2['RESPONSE'][i]['RBLOW'][0]['BB05']
                            BB05_str = BB05[0:3] + '年' + BB05[3:5] + '月' + BB05[5:7] + '日'
                            BB06 = j_2['RESPONSE'][i]['RBLOW'][0]['BB06']
                            url_reason_2 =  urlPathList[0][1] + 'QueryReason.php?UNIT=' + unit
                            response_reason_2 = urlopen(url_reason_2)
                            html_reason_2 = response_reason_2.read()
                            j_reason_2 = json.loads(html_reason_2)
                            reason_2_dict = {}
                            reason_2_keys = range(len(j_reason_2['RESPONSE'][0]['DATA']))
                            for p in reason_2_keys:
                                reason_2_dict[p] = j_reason_2['RESPONSE'][0]['DATA'][p]['CODE']
                            reason_2_dict_invert = {v: k for k, v in reason_2_dict.items()}
                            BB06_str = j_reason_2['RESPONSE'][0]['DATA'][reason_2_dict_invert.get(BB06)]['NAME']
                            BB07 = j_2['RESPONSE'][i]['RBLOW'][0]['BB07']
                            BB07_str = BB07[0:3] + '年' + BB07[3:5] + '月' + BB07[5:7] + '日'
                            url_rights_2 =  urlPathList[0][1] + 'QueryRights.php'
                            response_rights_2 = urlopen(url_rights_2)
                            html_rights_2 = response_rights_2.read()
                            j_rights_2 = json.loads(html_rights_2)
                            BB15_1 = j_2['RESPONSE'][i]['RBLOW'][0]['BB15_1']
                            rights_2_dict = {}
                            rights_2_keys = range(len(j_rights_2['RESPONSE']))
                            for m in rights_2_keys:
                                rights_2_dict[m] = j_rights_2['RESPONSE'][m]['CODE']
                            rights_2_dict_invert = {v: k for k, v in rights_2_dict.items()}
                            if rights_2_dict_invert.get(BB15_1)!=None:
                                BB15_1_str = j_rights_2['RESPONSE'][rights_2_dict_invert.get(BB15_1)]['NAME']
                            else:
                                BB15_1_str=''
                            BB15_2 = j_2['RESPONSE'][i]['RBLOW'][0]['BB15_2']
                            BB15_3 = j_2['RESPONSE'][i]['RBLOW'][0]['BB15_3']
                            BB03 = j_2['RESPONSE'][i]['RBLOW'][0]['BB03']
                            if BB03 !=NULL:
                                BB03_str = BB03[0:3] + '年' + BB03[3:5] + '月' + BB03[5:7] + '日'
                            else:
                                BB03_str = BB03
                            BB04_1 = j_2['RESPONSE'][i]['RBLOW'][0]['BB04_1']
                            BB04_2 = j_2['RESPONSE'][i]['RBLOW'][0]['BB04_2']
                            BB21 = j_2['RESPONSE'][i]['RBLOW'][0]['BB21']
                            self.cadastreDia.tableWidget.setItem( 0, i, QTableWidgetItem(nameBase))
                            self.cadastreDia.tableWidget.setItem( 1, i, QTableWidgetItem(no))
                            self.cadastreDia.tableWidget.setItem( 2, i, QTableWidgetItem(BB05_str))
                            self.cadastreDia.tableWidget.setItem( 3, i, QTableWidgetItem(BB06_str))
                            self.cadastreDia.tableWidget.setItem( 4, i, QTableWidgetItem(BB07_str))
                            self.cadastreDia.tableWidget.setItem( 5, i, QTableWidgetItem(BB15_1_str))
                            self.cadastreDia.tableWidget.setItem( 6, i, QTableWidgetItem(BB15_2))
                            self.cadastreDia.tableWidget.setItem( 7, i, QTableWidgetItem(BB15_3))
                            self.cadastreDia.tableWidget.setItem( 8, i, QTableWidgetItem(BB03))
                            self.cadastreDia.tableWidget.setItem( 9, i, QTableWidgetItem(BB04_1))
                            self.cadastreDia.tableWidget.setItem(10, i, QTableWidgetItem(BB04_2))
                            self.cadastreDia.tableWidget.setItem(11, i, QTableWidgetItem(BB04_2))
                    else:
                        self.cadastreDia.tableWidget.setColumnCount(1)

                self.cadastreDia.tableWidget.resizeColumnsToContents()
                
        self.cadastreDia.tableWidget_3.setItem(0, 0, QtWidgets.QTableWidgetItem(self.cadastreDia.comboBox_3.currentText()))
        self.cadastreDia.tableWidget_3.setItem(0, 1, QtWidgets.QTableWidgetItem(no))
        url_3 = urlPathList[0][1] + 'LandOtherRights.php?UNIT=' + unit + '&SEC=' + sec + '&NO=' + no + '&OFFSET=1&LIMIT=10'
        response_3 = urlopen(url_3)
        html_3 = response_3.read()
        if str(html_3).find('COP') != -1:
            pass
        else:
            j_3 = json.loads(html_3)
            if j_3['RETURNROWS']!=0:
                j_3_count = len(j_3['RESPONSE'])
                rowPosition = self.cadastreDia.tableWidget_3.rowCount()
                self.cadastreDia.tableWidget_3.setColumnCount(j_3_count)
                for i in range(0, j_3_count, 1):
                    if j_3['RESPONSE']!=NULL:
                        if len(j_3['RESPONSE'][i]['RCLOR'])!=0:
                            CC01 = j_3['RESPONSE'][i]['RCLOR'][0]['CC01']
                            CC03 = j_3['RESPONSE'][i]['RCLOR'][0]['CC03']
                            CC04_1 = j_3['RESPONSE'][i]['RCLOR'][0]['CC04_1']
                            CC04_2 = j_3['RESPONSE'][i]['RCLOR'][0]['CC04_2']
                            CC05 = j_3['RESPONSE'][i]['RCLOR'][0]['CC05']
                            CC05_str = CC05[0:3] + '年' + CC05[3:5] + '月' + CC05[5:7] + '日'
                            CC06 = j_3['RESPONSE'][i]['RCLOR'][0]['CC06']
                            url_reason_3 =  urlPathList[0][1] + 'QueryReason.php?UNIT=' + unit
                            response_reason_3 = urlopen(url_reason_3)
                            html_reason_3 = response_reason_3.read()
                            j_reason_3 = json.loads(html_reason_3)
                            reason_3_dict = {}
                            reason_3_keys = range(len(j_reason_3['RESPONSE'][0]['DATA']))
                            for ii in reason_3_keys:
                                reason_3_dict[ii] = j_reason_3['RESPONSE'][0]['DATA'][ii]['CODE']
                            reason_3_dict_invert = {v: k for k, v in reason_3_dict.items()}
                            if rights_2_dict_invert.get(CC06)!=None:
                                CC06_str = j_reason_3['RESPONSE'][0]['DATA'][reason_3_dict_invert.get(CC06)]['NAME']
                            else:
                                CC06_str=''
                            CC15_1 = j_3['RESPONSE'][i]['RCLOR'][0]['CC15_1']
                            url_rights_3 =  urlPathList[0][1] + 'QueryRights.php'
                            response_rights_3 = urlopen(url_rights_3)
                            html_rights_3 = response_rights_3.read()
                            j_rights_3 = json.loads(html_rights_3)
                            rights_3_dict = {}
                            rights_3_keys = range(len(j_rights_3['RESPONSE']))
                            for n in rights_3_keys:
                                rights_3_dict[n] = j_rights_3['RESPONSE'][n]['CODE']
                            rights_3_dict_invert = {v: k for k, v in rights_3_dict.items()}
                            if rights_3_dict_invert.get(CC15_1)!=None:
                                CC15_1_str = j_rights_3['RESPONSE'][rights_3_dict_invert.get(CC15_1)]['NAME']
                            else:
                                CC15_1_str=''
                            CC15_2 = j_3['RESPONSE'][i]['RCLOR'][0]['CC15_2']
                            CC15_3 = j_3['RESPONSE'][i]['RCLOR'][0]['CC15_3']
                            CC15_4 = j_3['RESPONSE'][i]['RCLOR'][0]['CC15_4']
                            CC16 = j_3['RESPONSE'][i]['RCLOR'][0]['CC16']
                            CC18_1 = j_3['RESPONSE'][i]['RCLOR'][0]['CC18_1']
                            url_LoanRight_3 =  urlPathList[0][1] + 'QueryLoanRightsRange.php'
                            response_LoanRight_3 = urlopen(url_LoanRight_3)
                            html_LoanRight_3 = response_LoanRight_3.read()
                            j_LoanRight_3 = json.loads(html_LoanRight_3)
                            LoanRight_3_dict = {}
                            LoanRight_3_keys = range(len(j_LoanRight_3['RESPONSE']))
                            for m in LoanRight_3_keys:
                                LoanRight_3_dict[m] = j_LoanRight_3['RESPONSE'][m]['CODE']
                            LoanRight_3_dict_invert = {v: k for k, v in LoanRight_3_dict.items()}
                            if LoanRight_3_dict_invert.get(CC18_1)!=None:
                                CC18_1_str = j_LoanRight_3['RESPONSE'][LoanRight_3_dict_invert.get(CC18_1)]['NAME']
                            else:
                                CC18_1_str=''
                            CC18_2 = j_3['RESPONSE'][i]['RCLOR'][0]['CC18_2']
                            CC18_3 = j_3['RESPONSE'][i]['RCLOR'][0]['CC18_3']
                            CC27 = j_3['RESPONSE'][i]['RCLOR'][0]['CC27']
                            url_rightstype_3 =  urlPathList[0][1] + 'QueryRightsAndTypes.php'
                            response_rightstype_3 = urlopen(url_rightstype_3)
                            html_rightstype_3 = response_rightstype_3.read()
                            j_rightstype_3 = json.loads(html_rightstype_3)
                            rightstype_3_dict = {}
                            rightstype_3_keys = range(len(j_rightstype_3['RESPONSE']))
                            for o in rightstype_3_keys:
                                rightstype_3_dict[o] = j_rightstype_3['RESPONSE'][o]['CODE']
                            rightstype_3_dict_invert = {v: k for k, v in rightstype_3_dict.items()}
                            if rightstype_3_dict_invert.get(CC27)!=None:
                                CC27_str = j_rightstype_3['RESPONSE'][rightstype_3_dict_invert.get(CC27)]['NAME']
                            else:
                                CC27_str=''
                            CC28_1 = j_3['RESPONSE'][i]['RCLOR'][0]['CC28_1']
                            url_goaltype_3 =  urlPathList[0][1] + 'QueryRightsAndTypes.php'
                            response_goaltype_3 = urlopen(url_goaltype_3)
                            html_goaltype_3 = response_goaltype_3.read()
                            j_goaltype_3 = json.loads(html_goaltype_3)
                            goaltype_3_dict = {}
                            goaltype_3_keys = range(len(j_goaltype_3['RESPONSE']))
                            for p in goaltype_3_keys:
                                goaltype_3_dict[p] = j_goaltype_3['RESPONSE'][p]['CODE']
                            goaltype_3_dict_invert = {v: k for k, v in goaltype_3_dict.items()}
                            if goaltype_3_dict_invert.get(CC28_1)!=None:
                                CC28_1_str = j_goaltype_3['RESPONSE'][goaltype_3_dict_invert.get(CC28_1)]['NAME']
                            else:
                                CC28_1_str=''
                            self.cadastreDia.tableWidget_3.setItem(0,  i, QTableWidgetItem(nameBase))
                            self.cadastreDia.tableWidget_3.setItem(1,  i, QTableWidgetItem(no))
                            self.cadastreDia.tableWidget_3.setItem(2,  i, QTableWidgetItem(CC01))
                            self.cadastreDia.tableWidget_3.setItem(3,  i, QTableWidgetItem(CC03))
                            self.cadastreDia.tableWidget_3.setItem(4,  i, QTableWidgetItem(CC04_1))
                            self.cadastreDia.tableWidget_3.setItem(5,  i, QTableWidgetItem(CC04_2))
                            self.cadastreDia.tableWidget_3.setItem(6,  i, QTableWidgetItem(CC05_str))
                            self.cadastreDia.tableWidget_3.setItem(7,  i, QTableWidgetItem(CC06_str))
                            self.cadastreDia.tableWidget_3.setItem(8,  i, QTableWidgetItem(CC15_1_str))
                            self.cadastreDia.tableWidget_3.setItem(9,  i, QTableWidgetItem(CC15_2))
                            self.cadastreDia.tableWidget_3.setItem(10, i, QTableWidgetItem(CC15_3))
                            self.cadastreDia.tableWidget_3.setItem(11, i, QTableWidgetItem(CC15_4))
                            self.cadastreDia.tableWidget_3.setItem(12, i, QTableWidgetItem(CC16))
                            self.cadastreDia.tableWidget_3.setItem(13, i, QTableWidgetItem(CC18_1_str))
                            self.cadastreDia.tableWidget_3.setItem(14, i, QTableWidgetItem(CC18_2))
                            self.cadastreDia.tableWidget_3.setItem(15, i, QTableWidgetItem(CC18_3))
                            self.cadastreDia.tableWidget_3.setItem(16, i, QTableWidgetItem(CC27_str))
                            self.cadastreDia.tableWidget_3.setItem(17, i, QTableWidgetItem(CC28_1_str))
                    else:
                        self.cadastreDia.tableWidget_3.setColumnCount(1)


                self.cadastreDia.tableWidget_3.resizeColumnsToContents()

            self.cadastreDia.tableWidget_4.setItem(0, 0, QTableWidgetItem(self.cadastreDia.comboBox_3.currentText()))
            self.cadastreDia.tableWidget_4.setItem(0, 1, QTableWidgetItem(no))
            url_4 =  urlPathList[0][1] + 'BuildingDescription.php?unit=' + unit + '&sec=' + sec + '&no=' + no
            response_4 = urlopen(url_4)
            html_4 = response_4.read()
            if str(html_4).find('COP') != -1:
                pass
            else:
                j_4 = json.loads(html_4)
                if j_4['RESPONSE'][0]['RDBID']!=NULL:
                    DD05 = j_4['RESPONSE'][0]['RDBID']['DD05']
                    self.cadastreDia.tableWidget_4.setItem(0,  0, QTableWidgetItem(nameBase))
                    self.cadastreDia.tableWidget_4.setItem(0,  1, QTableWidgetItem(no))
                    self.cadastreDia.tableWidget_4.setItem(0,  2, QTableWidgetItem(DD05))
                    self.cadastreDia.tableWidget_4.resizeColumnsToContents()
        self.cadastreDia.tabWidget.setCurrentIndex(2)

    def changeQueryMode(self):
        if self.cadastreDia.checkBox.isChecked():
            self.cadastreDia.lineEdit_2.setEnabled(False)
            self.cadastreDia.lineEdit_3.setEnabled(False)
            self.pointEmitter = QgsMapToolEmitPoint(self.iface.mapCanvas())
            self.pointEmitter.canvasClicked.connect(self.clickNow_3)
            self.iface.mapCanvas().setMapTool( self.pointEmitter )
        else:
            self.cadastreDia.lineEdit_2.setEnabled(True)
            self.cadastreDia.lineEdit_3.setEnabled(True)
            self.iface.mapCanvas().unsetMapTool( self.pointEmitter )

    def clickNow_3(self, event):
        self.cadastreDia.lineEdit_2.setText(str(event.x()))
        self.cadastreDia.lineEdit_3.setText(str(event.y()))

    def cadastreItemClicked(self):
        self.cadastreDia.listWidget_2.addItem(self.cadastreDia.listWidget.currentItem().text())
        itemList = []

        for i in range(0, self.cadastreDia.listWidget_2.count(), 1):
            itemList.append(self.cadastreDia.listWidget_2.item(i).text())

        items = list(set(itemList))

        self.cadastreDia.listWidget_2.clear()
        self.cadastreDia.comboBox_5.clear()

        for i in range(0, len(items), 1):
            self.cadastreDia.listWidget_2.addItem(items[i])

        for i in range(0, self.cadastreDia.listWidget_2.count(), 1):
            self.cadastreDia.comboBox_5.insertItem(i, self.cadastreDia.listWidget_2.item(i).text())

    def cadastre_reset(self):
        self.cadastreDia.comboBox.setCurrentIndex(0)
        self.cadastreDia.comboBox_2.clear()
        self.cadastreDia.comboBox_3.clear()
        self.cadastreDia.listWidget.clear()
        self.cadastreDia.listWidget.clear()
        self.cadastreDia.checkBox.setChecked(0)
        self.cadastreDia.tabWidget.setCurrentIndex(0)
        self.cadastreDia.lineEdit_2.setEnabled(True)
        self.cadastreDia.lineEdit_3.setEnabled(True)
        self.cadastreDia.comboBox_5.clear()

    def resetCadastreDia(self):
        self.cadastre_reset()
        self.cadastreDia.tableWidget.clearContents()
        self.cadastreDia.tableWidget_2.clearContents()
        self.cadastreDia.tableWidget_3.clearContents()
        self.cadastreDia.tableWidget_4.clearContents()
    # End of Cadastre Dialog Function







###---------地籍圖查詢功能----------------###

    


#########################################


#---------------內部影像底圖功能--------------------##

    def load_25000(self):
        QMessageBox.information(self.iface.mainWindow(), "提示", "請保持1/25000圖框可見並請勿移除!!\n直接點選即可載入該圖框之經建版地形圖\n若中途使用其他地圖工具或圖框圖層已移除，\n請再點選一次「1/25000經建版地形圖」按鈕")    
        self.getImg.load_25000_img(self.dockwidget.lineEdit.text())

    def load_5000(self):
        QMessageBox.information(self.iface.mainWindow(), "提示", "請保持1/5000圖框可見並請勿移除!!\n直接點選即可載入該圖框之正射影像\n若中途使用其他地圖工具或圖框圖層已移除，\n請再點選一次「正射影像」按鈕")    
        self.getImg.load_5000_img(self.dockwidget.lineEdit.text())


    def wms_show(self):

        filePath = rootPath + 'filePath.csv'
        #QMessageBox.information(self.iface.mainWindow(), "X", filePath)
        filePathfile = open(filePath, 'r')
        csvCursor = csv.reader(filePathfile)
        filePathList = []
        for row in csvCursor:
            filePathList.append(row)

        filePathName = self.dockwidget.lineEdit.text() + filePathList[11][2]

        self.wmsDia.comboBox.clear()
        self.wmsDia.comboBox_2.clear()
        
        if os.path.isfile(filePathName) :    
            self.load_1_5000()            
            self.wmsDia.show()
        else:
            msg = "找不到\" " + filePathName + " \"圖層" + "\n請確認路徑" 
            QMessageBox.information(self.iface.mainWindow(), "錯誤", msg)

    
    def clickNow_2(self, event):
        layers = self.canvas.layers()
        filePath = rootPath + 'filePath.csv'
        #QMessageBox.information(self.iface.mainWindow(), "X", filePath)
        filePathfile = open(filePath, 'r')
        csvCursor = csv.reader(filePathfile)
        filePathList = []
        for row in csvCursor:
            filePathList.append(row)

        filePathName = self.dockwidget.lineEdit.text() + filePathList[11][2]

        if os.path.isfile(filePathName) :      
            #QMessageBox.information(self.iface.mainWindow(), "mes", filePathName)
            if len(QgsProject.instance().mapLayersByName(filePathList[11][1])) == 0:
                i=0
                self.iface.addVectorLayer(filePathName, "", "ogr")  

            for each_layer in layers:
                #if each_layer.source() == 'C:/data/frameData/1_5000圖幅接合圖.shp'.decode('utf-8'):
                if each_layer.source() == filePathName:
                    parish_layer = each_layer
                    break
        rect = QgsRectangle(event.x() - 0.000001,
                            event.y() - 0.000001,
                            event.x() + 0.000001,
                            event.y() + 0.000001)
        # rect = self.iface.mapCanvas().mapRenderer().mapToLayerCoordinates(parish_layer, rect)
        rect = self.iface.mapCanvas().mapSettings().mapToLayerCoordinates(parish_layer, rect)
        parish_layer.selectByRect(rect)
        selected_features = parish_layer.selectedFeatures()
        #QMessageBox.information(self.iface.mainWindow(), "X", str(selected_features))
        if (selected_features != []):
            #QMessageBox.information(self.iface.mainWindow(), "ID5000", str(selected_features[0]["ID5000"]))
            self.wmsDia.comboBox.clear()
            self.wmsDia.comboBox.insertItem(0, str(selected_features[0]["ID5000"]))

        else:
            msg = "找不到\" " + filePathName + " \"圖層" + "\n請確認路徑"
            QMessageBox.information(self.iface.mainWindow(), "錯誤", msg) 


    
    def load_1_5000(self):
        self.iface.mapCanvas().unsetMapTool( self.pointEmitter )

        filePath = rootPath + 'filePath.csv'
        #QMessageBox.information(self.iface.mainWindow(), "X", filePath)
        filePathfile = open(filePath, 'r')
        csvCursor = csv.reader(filePathfile)
        filePathList = []
        for row in csvCursor:
            filePathList.append(row)

        filePathName = self.dockwidget.lineEdit.text() + filePathList[11][2]

        if os.path.isfile(filePathName) :    
        #QMessageBox.information(self.iface.mainWindow(), "mes", filePathName)
            if len(QgsProject.instance().mapLayersByName(filePathList[11][1])) == 0:
                i=0
                self.iface.addVectorLayer(filePathName, "", "ogr")  

                global styleFilePath_5000    
                styleFilePath_5000 = rootPath + 'style/noFillBlueLine.qml'
                self.iface.activeLayer().loadNamedStyle(styleFilePath_5000)        

            #if len(QgsProject.instance().mapLayersByName('1_5000圖幅接合圖'.decode('utf-8'))) == 0:
            #self.iface.addVectorLayer('C:/data/frameData/1_5000圖幅接合圖.shp'.decode('utf-8'), "", "ogr")
            self.setSourceEncode()

            # legend = self.iface.legendInterface()            
            legend = [layer for layer in QgsProject.instance().mapLayers().values()]
            registry = QgsProject.instance()
            #self.positioningDia.comboBox_2.currentText() + '事業區林班圖'.decode('utf-8')

            target_layer = registry.mapLayersByName( filePathList[11][1])[0]
            #target_layer = registry.mapLayersByName( '第二輪檢訂事業區圖'.decode('utf-8') )[0]
            self.iface.setActiveLayer(target_layer)    
            # legend.setLayerVisible(target_layer, True)
            QgsProject.instance().layerTreeRoot().findLayer(target_layer).setItemVisibilityChecked(True) 

            self.pointEmitter = QgsMapToolEmitPoint(self.iface.mapCanvas())
            # QObject.connect( self.pointEmitter, SIGNAL("canvasClicked(const QgsPoint, Qt::MouseButton)"), self.clickNow_2)
            self.pointEmitter.canvasClicked.connect(self.clickNow_2)
            self.iface.mapCanvas().setMapTool( self.pointEmitter )     
            #self.start()    

        else:
            msg = "找不到\" " + filePathName + " \"圖層" + "\n請確認路徑"
            QMessageBox.information(self.iface.mainWindow(), "錯誤", msg) 

            #else:
            #msg = "找不到\" ".decode('utf-8') + filePathName_5000 + " \"圖層".decode('utf-8') + "\n請確認路徑".decode('utf-8') 
            #QMessageBox.information(self.iface.mainWindow(), "錯誤".decode('utf-8'), msg)  


    def wmsDia_comboBox_change(self):
        filePath = rootPath + 'filePath.csv'
        #QMessageBox.information(self.iface.mainWindow(), "X", filePath)
        filePathfile = open(filePath, 'r')
        csvCursor = csv.reader(filePathfile)
        filePathList = []
        for row in csvCursor:
            filePathList.append(row)

        registry = QgsProject.instance()
        #legend = self.iface.legendInterface()
        legend = [layer for layer in QgsProject.instance().mapLayers().values()]

        target_layer = registry.mapLayersByName( filePathList[11][1])[0]
        self.iface.setActiveLayer(target_layer)
        # legend.setLayerVisible(target_layer, True)
        QgsProject.instance().layerTreeRoot().findLayer(target_layer.id()).setItemVisibilityChecked(True)

        expr = QgsExpression( " \"{}\" ='{}' ".format( 'ID5000', self.wmsDia.comboBox.currentText()))    

        it = target_layer.getFeatures( QgsFeatureRequest( expr ) )
        ids = [i.id() for i in it]
        
        self.iface.activeLayer().removeSelection()
        target_layer.selectByIds( ids )
        #self.canvas.zoomToSelected()

    
    def getID5000(self):

        self.wmsDia.comboBox.clear()
        self.wmsDia.comboBox_2.clear()

        self.load_1_5000()

        crs = QgsCoordinateReferenceSystem(3826)
        # self.iface.mapCanvas().mapRenderer().setDestinationCrs(crs)
        self.iface.mapCanvas().mapSettings().setDestinationCrs(crs)
        

        # legend = self.iface.legendInterface()
        legend = [layer for layer in QgsProject.instance().mapLayers().values()]
        layers = self.canvas.layers()
        for each_layer in layers:
            # legend.setLayerVisible(each_layer, False)
            QgsProject.instance().layerTreeRoot().findLayer(each_layer).setItemVisibilityChecked(False)
        registry = QgsProject.instance()

         

        filePath = rootPath + 'filePath.csv'
        #QMessageBox.information(self.iface.mainWindow(), "X", filePath)
        filePathfile = open(filePath, 'r')
        csvCursor = csv.reader(filePathfile)
        filePathList = []
        for row in csvCursor:
            filePathList.append(row)

        #filePathName = self.mainDia.lineEdit.text() + filePathList[11][2].decode('utf-8')

        #target_layer = registry.mapLayersByName( '1_5000圖幅接合圖0931'.decode('utf-8') )[0]
        target_layer = registry.mapLayersByName( filePathList[11][1])[0]
        self.iface.setActiveLayer(target_layer)
        # legend.setLayerVisible(target_layer, True)
        QgsProject.instance().layerTreeRoot().findLayer(target_layer).setItemVisibilityChecked(True)
        #extent = target_layer.extent()
        #self.canvas.setExtent(extent)

        rect = self.canvas.extent()
        request = QgsFeatureRequest().setFilterRect(rect)
        it = target_layer.getFeatures( request )
        ids = [i.id() for i in it]
        
        self.iface.activeLayer().removeSelection()
        # target_layer.setSelectedFeatures( ids )
        target_layer.selectByIds( ids )
                
        # request = QgsFeatureRequest(QgsExpression(ids)).setFlags(QgsFeatureRequest.NoGeometry).setSubsetOfAttributes([])
        # selection = target_layer.getFeatures(request)

        i=0
        features = self.iface.activeLayer().selectedFeatures()
        # idx_1 = self.iface.activeLayer().fieldNameIndex('ID5000')
        idx_1= self.iface.activeLayer().fields().indexFromName('ID5000')
        

        self.wmsDia.comboBox.clear()
        for feat in features:
            attrs_1 = feat.attributes()[idx_1]
            self.wmsDia.comboBox.insertItem(i+1, str(attrs_1))
            i+=1    


    def getWMSList(self):

        filePath = rootPath + 'wmsAccount.csv'
        #QMessageBox.information(self.iface.mainWindow(), "X", filePath)
        filePathfile = open(filePath, 'r')
        csvCursor = csv.reader(filePathfile)
        accountList = []
        for row in csvCursor:
            accountList.append(row)

        username = accountList[0][1]
        password = accountList[1][1]
        url = "http://owms.afasi.gov.tw/asofb/" + self.wmsDia.comboBox.currentText() + "/wms?request=getcapabilities"
        #QMessageBox.information(self.iface.mainWindow(), "mes", url)
        request = urllib.request.Request(url)
        # base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
        base64string = base64.encodestring(('%s:%s' % (username,password)).encode()).decode().replace('\n', '')
        request.add_header("Authorization", "Basic %s" % base64string)
        response = urllib.request.urlopen(request)

        #response = urllib2.urlopen('http://wms.afasi.gov.tw/asofb/wms?request=getcapabilities')  
        xmlDoc = xml.dom.minidom.parse(response)
        root = xmlDoc.documentElement
        layerList =  root.getElementsByTagName('Layer')
        #QMessageBox.information(self.iface.mainWindow(), "mes", layerList[0].childNodes[0].data)
        wmtsTitleList = []
        #wmtsIdentifierList = []
        #wmtsFormatList = []
    
        for layer in layerList:
            owsTitleList = layer.getElementsByTagName('Name')
            if layer.getAttribute("queryable") == '1':
                wmtsTitleList.append(owsTitleList[0].childNodes[0].data)
            #owsIdentifier = layer.getElementsByTagName('ows:Identifier')
            #imgformatList = layer.getElementsByTagName('Format')

      
        #wmtsIdentifierList.append(owsIdentifier[0].childNodes[0].data)
        #wmtsFormatList.append(imgformatList[0].childNodes[0].data)    
        #QMessageBox.information(self.iface.mainWindow(), "mes", wmtsTitleList[3])
        self.wmsDia.comboBox_2.clear()
        for i in range(0, len(wmtsTitleList), 1):
            self.wmsDia.comboBox_2.insertItem(i, wmtsTitleList[i])


    def addWMS(self):
        
        if self.wmsDia.radioButton.isChecked():
            url = 'http://owms.afasi.gov.tw/asofb/'
        if self.wmsDia.radioButton_2.isChecked():
            url = 'http://10.51.231.101/asofb/owms/'

        filePath = rootPath + 'wmsAccount.csv'
        #QMessageBox.information(self.iface.mainWindow(), "X", filePath)
        filePathfile = open(filePath, 'r')
        csvCursor = csv.reader(filePathfile)
        accountList = []
        for row in csvCursor:
            accountList.append(row)

        username = accountList[0][1]
        password = accountList[1][1]
        #username = "sinica1gov"
        #password = "gov1sinica104AP"

        urlWithParams = 'contextualWMSLegend=0&crs=EPSG:3826&dpiMode=7&featureCount=10&format=image/png&styles=&url=' + url + self.wmsDia.comboBox.currentText() + '/wms?&username=' + username + '&layers=' + self.wmsDia.comboBox_2.currentText() + '&password=' + password
        #QMessageBox.information(self.iface.mainWindow(), "X", urlWithParams)    
        #urlWithParams = self.WMTSDia.tableWidget_4.item(self.WMTSDia.tableWidget_4.currentRow(), 2).text()
        rlayer = QgsRasterLayer(urlWithParams, self.wmsDia.comboBox_2.currentText(), 'wms')
        QgsProject.instance().addMapLayer(rlayer) 

        root = QgsProject.instance().layerTreeRoot()

        filePath = rootPath + 'filePath.csv'
        filePathfile = open(filePath, 'r')
        csvCursor = csv.reader(filePathfile)

        global filePathList_5000
        filePathList_5000 = []
        for row in csvCursor:
            filePathList_5000.append(row)

        global defaultDir_5000
        defaultDir_5000 = self.dockwidget.lineEdit.text()
        global filePathName_5000
        filePathName_5000 = defaultDir_5000 + filePathList_5000[11][2]


        layers = self.canvas.layers()  
        for each_layer in layers:
            if each_layer.source() == filePathName_5000:        
                parish_layer = each_layer
                break

        myalayer = root.findLayer(parish_layer.id())
        myClone = myalayer.clone()
        parent = myalayer.parent()
        parent.insertChildNode(0, myClone)
        parent.removeChildNode(myalayer)


#########################################




#######CSV to Shapefile功能##########

    def csv2shp_show(self):    
        self.csv2shpDia.show()
    
    def getCSVName(self):
        csvFileName = QFileDialog.getOpenFileName(None, u"請選擇CSV檔案", self.dockwidget.lineEdit.text(), "CSV files (*.csv)")
        self.csv2shpDia.lineEdit.clear()
        self.csv2shpDia.lineEdit.insert(csvFileName[0])

    def getSHPName(self):
        shpFileName = QFileDialog.getSaveFileName(None, u"圖層另存為", self.dockwidget.lineEdit.text(), "SHP files (*.shp)")
        self.csv2shpDia.lineEdit_2.clear()
        self.csv2shpDia.lineEdit_2.insert(shpFileName[0])

    def csv2shp(self):
        ########################################################
        #                                                      #
        # CSV file to shapefile                                #
        #                                                      #
        # 1. read csv file                                     #
        # 2. decide coordinate                                 #
        # 3. decide point, line or polygon                     #
        #   3-1 point   : fill all attr                        #
        #   3-2 line    : fill part attr                       #    
        #   3-3 polygon : fill part attr                       #        
        #                                                      #
        ########################################################
    
        #1
        file = open(self.csv2shpDia.lineEdit.text(), 'r')
        csvCursor = csv.reader(file)
        personDF = []
        for row in csvCursor:
            personDF.append(row)


        #2
        global crs_
        global crs

        if self.csv2shpDia.comboBox.currentIndex()==0 : #twd97  
            crs_ = "Point?crs=epsg:3826"
            crs = QgsCoordinateReferenceSystem("epsg:3826")
        if self.csv2shpDia.comboBox.currentIndex()==1 : #wgs84
            crs_ = "Point?crs=epsg:4326"
            crs = QgsCoordinateReferenceSystem("epsg:4326")


        #3-1 
        if self.csv2shpDia.radioButton.isChecked():

            fileName = self.csv2shpDia.lineEdit.text() + '_points'
            layer =  QgsVectorLayer(crs_,  fileName, "memory")
            layer.setCrs(crs)
            pr = layer.dataProvider() 

            # fix first 2 field name: X, Y
            pr.addAttributes( [ QgsField(personDF[0][0], QVariant.Double),
                                QgsField(personDF[0][1], QVariant.Double) ] )

            # decide other field name
            for i in range(len(personDF[0])-2):
                res = pr.addAttributes([QgsField(personDF[0][i+2], QVariant.String)])      

            layer.updateFields()

            pt = QgsFeature()

            for i in range(len(personDF)-1): #point
                point = QgsPointXY(float(personDF[i+1][0]), float(personDF[i+1][1]))
                pt.setGeometry(QgsGeometry.fromPointXY(point))

                # fill all attr
                attr = []
                attr.append(str(personDF[i+1][0]))
                attr.append(str(personDF[i+1][1]))            

                for j in range(len(personDF[0])-2):
                    attr.append(str(personDF[i+1][j+2]))

                pt.setAttributes(attr)

                pr.addFeatures([pt])
                # update extent of the layer
                layer.updateExtents()


            _writer = QgsVectorFileWriter.writeAsVectorFormat(layer,self.csv2shpDia.lineEdit_2.text(), "utf-8", crs, "ESRI Shapefile")

            if self.csv2shpDia.lineEdit_2.text() =='':
                outfile = "輸出至暫存記憶體"
            else:
                outfile = "輸出檔案:" + self.csv2shpDia.lineEdit_2.text()

            QMessageBox.information(self.iface.mainWindow(), u"轉換完成", outfile )
            QgsProject.instance().addMapLayers([layer])


            #3-2
        elif self.csv2shpDia.radioButton_2.isChecked(): #line
            
            if self.csv2shpDia.comboBox.currentIndex()==0 : #twd97
                crs_ = "LineString?crs=epsg:3826"
                crs = QgsCoordinateReferenceSystem(3826)
            if self.csv2shpDia.comboBox.currentIndex()==1 : #wgs84
                crs_ = "LineString?crs=epsg:4326"
                crs = QgsCoordinateReferenceSystem(4326)
                
            fileName = self.csv2shpDia.lineEdit.text() + '_line'
            layer =  QgsVectorLayer(crs_,  fileName, "memory")
            layer.setCrs(crs)
            pr = layer.dataProvider() 

            # add field: Part
            pr.addAttributes( [ QgsField(personDF[0][2], QVariant.String) ] )

            # decide other field name
            #for i in range(len(personDF[0])-2):
                #res = pr.addAttributes([QgsField(personDF[0][i+2], QVariant.String)])      

            layer.updateFields()
            line = QgsFeature()

            # decide how many part
            partList = []
            for i in range(len(personDF)-1): 
                partList.append(personDF[i+1][2])

            myset = list(set(partList))

            # put different part point into pointList[][]
            pointList = []
            for i in range(len(myset)):
                pointList.append([])

                for j in range(len(personDF)-1): 
                    if personDF[j+1][2] == myset[i]:
                        pointList[i].append(QgsPointXY(float(personDF[j+1][0]), float(personDF[j+1][1])))

            for i in range(len(myset)):
                line.setGeometry(QgsGeometry.fromPolylineXY(pointList[i]))
                # fill all attr
                attr = []
                attr.append(str(myset[i]))
                line.setAttributes(attr)

                pr.addFeatures([line])
                # update extent of the layer
                layer.updateExtents()


            _writer = QgsVectorFileWriter.writeAsVectorFormat(layer,self.csv2shpDia.lineEdit_2.text(),"utf-8",crs,"ESRI Shapefile")
            # _writer = QgsVectorFileWriter.writeAsVectorFormat(self.iface.activeLayer(), self.gpx2shpDia.lineEdit_2.text(), "utf-8", crs, "ESRI Shapefile")

            if self.csv2shpDia.lineEdit_2.text() =='':
                outfile = "輸出至暫存記憶體"
            else:
                outfile = "輸出檔案:" + self.csv2shpDia.lineEdit_2.text()

            QMessageBox.information(self.iface.mainWindow(), u"轉換完成", outfile )
            QgsProject.instance().addMapLayers([layer])




    #3-3
        elif self.csv2shpDia.radioButton_3.isChecked(): #polygon
        # decide crs
            if self.csv2shpDia.comboBox.currentIndex()==0 : #twd97
                crs_ = "Polygon?crs=epsg:3826"
                crs = QgsCoordinateReferenceSystem(3826)
            if self.csv2shpDia.comboBox.currentIndex()==1 : #wgs84
                crs_ = "Polygon?crs=epsg:4326"
                crs = QgsCoordinateReferenceSystem(4326)

            fileName = self.csv2shpDia.lineEdit.text() + '_polygon'
            layer =  QgsVectorLayer(crs_,  fileName, "memory")
            layer.setCrs(crs)
            pr = layer.dataProvider() 

            # add field: Part
            pr.addAttributes( [ QgsField(personDF[0][2], QVariant.String) ] )

            # decide other field name
            #for i in range(len(personDF[0])-2):
                #res = pr.addAttributes([QgsField(personDF[0][i+2], QVariant.String)])      

            layer.updateFields()
            polygon = QgsFeature()

            # decide how many part
            partList = []
            for i in range(len(personDF)-1): 
                partList.append(personDF[i+1][2])

            myset = list(set(partList))

            # put different part point into pointList[][]
            pointList = []
            for i in range(len(myset)):
                pointList.append([])

                for j in range(len(personDF)-1): 
                    if personDF[j+1][2] == myset[i]:
                        pointList[i].append(QgsPointXY(float(personDF[j+1][0]), float(personDF[j+1][1])))

            for i in range(len(myset)):
                polygon.setGeometry(QgsGeometry.fromPolygonXY([pointList[i]]))
                # fill all attr
                attr = []
                attr.append(str(myset[i]))
                polygon.setAttributes(attr)

                pr.addFeatures([polygon])
                # update extent of the layer
                layer.updateExtents()

            _writer = QgsVectorFileWriter.writeAsVectorFormat(layer,self.csv2shpDia.lineEdit_2.text(),"utf-8",crs,"ESRI Shapefile")
        
            if self.csv2shpDia.lineEdit_2.text() =='':
                outfile = "輸出至暫存記憶體"
            else:
                outfile = "輸出檔案:" + self.csv2shpDia.lineEdit_2.text()

            QMessageBox.information(self.iface.mainWindow(), u"轉換完成", outfile )
            QgsProject.instance().addMapLayers([layer])

###################################################################

    def setSourceEncode(self):
        pass

#######GPX To Shapefile功能###############

    def gpx2shp_show(self):
        self.gpx2shpDia.show()

    def getGPXName(self):
        gpxFileName = QFileDialog.getOpenFileName(None, u"請選擇GPX檔案", self.dockwidget.lineEdit.text(), "GPX files (*.gpx)")
        self.gpx2shpDia.lineEdit.clear()
        self.gpx2shpDia.lineEdit.insert(gpxFileName[0])

 

    def getGPX2SHPName(self):
        shpFileName = QFileDialog.getSaveFileName(None, u"圖層另存為", self.dockwidget.lineEdit.text(), "SHP files (*.shp)")
        self.gpx2shpDia.lineEdit_2.clear()
        self.gpx2shpDia.lineEdit_2.insert(shpFileName[0])

    def gpx2shp(self):

        global layerPath
        global layeridName
              
        if self.gpx2shpDia.radioButton_3.isChecked(): #track_point
            layerPath = self.gpx2shpDia.lineEdit.text() + '|layerid=4'
            layeridName='track_point'    
        elif self.gpx2shpDia.radioButton_5.isChecked(): #track
            layerPath = self.gpx2shpDia.lineEdit.text() + '|layerid=2'
            layeridName='track'      

        layerName =  self.gpx2shpDia.lineEdit.text()+layeridName
        self.iface.addVectorLayer(layerPath, layerName, "ogr")

        extent = self.iface.activeLayer().extent()
        self.canvas.setExtent(extent)    


        # decide crs

        if self.gpx2shpDia.comboBox.currentIndex()==1 : #twd97
        #crs = "point?crs=epsg:3826"
            crs=QgsCoordinateReferenceSystem("epsg:3826")
        if self.gpx2shpDia.comboBox.currentIndex()==0 : #wgs84
        #crs = "point?crs=epsg:4326"    
            crs=QgsCoordinateReferenceSystem("epsg:4326")
    
        _writer = QgsVectorFileWriter.writeAsVectorFormat(self.iface.activeLayer(), self.gpx2shpDia.lineEdit_2.text(), "utf-8", crs, "ESRI Shapefile")

        outfile = "輸出檔案:" + self.gpx2shpDia.lineEdit_2.text()
        QMessageBox.information(self.iface.mainWindow(), u"轉換完成", outfile )
        
        QgsProject.instance().removeMapLayers( [self.iface.activeLayer().id()] )
        layer=QgsVectorLayer(self.gpx2shpDia.lineEdit_2.text() , self.gpx2shpDia.lineEdit_2.text(), "ogr")
        QgsProject.instance().addMapLayers([layer])

####################################################################################################
    
########匯出Shapefile 功能####################

    def exportSHP_show(self):
        #legend = self.iface.legendInterface()
        self.exportSHPDia.checkBox.setChecked(True)

        names = []
        #for layer in QgsProject.instance().mapLayers().values():
        for layer in self.iface.mapCanvas().layers():
            
            #QMessageBox.information(self.iface.mainWindow(), "layer.name()", layer.name())
            if layer.type() == QgsMapLayer.VectorLayer:
                names.append(layer.name())

        self.exportSHPDia.listWidget.clear()
        for i in range(len(names)):
            self.exportSHPDia.listWidget.addItem(names[i])
        self.exportSHPDia.show()

    def exportSHP(self):
        # decide crs
        if self.exportSHPDia.comboBox.currentIndex()==0 : #twd97
            #crs = "point?crs=epsg:3826"
            crs=QgsCoordinateReferenceSystem("epsg:3826")
        if self.exportSHPDia.comboBox.currentIndex()==1 : #wgs84
            #crs = "point?crs=epsg:4326"    
            crs=QgsCoordinateReferenceSystem("epsg:4326")

        #self.iface.addVectorLayer(self.gpx2shpDia.lineEdit.text()+"?type=track_points", self.gpx2shpDia.lineEdit.text(), "gpx")
        #self.iface.addVectorLayer("C:/Users/rchss_/Desktop/dataOperation_v0.9/GPX/mGPX_20151216021510.gpx|layerid=4", self.gpx2shpDia.lineEdit.text(), "gpx")


        #QgsProject.instance().addMapLayers([layer])
        registry = QgsProject.instance()
        target_layer = registry.mapLayersByName( self.exportSHPDia.listWidget.currentItem().text() )[0]
        self.iface.setActiveLayer(target_layer)      
        #QMessageBox.information(self.iface.mainWindow(), u"轉換完成", self.exportSHPDia.listWidget.currentItem().text() )
        shpFileName = QFileDialog.getSaveFileName(None, u"圖層另存為", self.dockwidget.lineEdit.text(), "SHP files (*.shp)")            

        if self.exportSHPDia.checkBox.isChecked():
            _writer = QgsVectorFileWriter.writeAsVectorFormat(self.iface.activeLayer(), shpFileName[0], "utf", crs, "ESRI Shapefile", True)
        else:
            _writer = QgsVectorFileWriter.writeAsVectorFormat(self.iface.activeLayer(), shpFileName[0], "utf", crs, "ESRI Shapefile")

        outfile = "輸出檔案:" + shpFileName[0]
        QMessageBox.information(self.iface.mainWindow(), u"匯出完成", outfile )
        layer = QgsVectorLayer(shpFileName[0] , shpFileName[0], "ogr")
        QgsProject.instance().addMapLayers([layer])

    def desideDataPath(self):
        dataPath = QFileDialog.getExistingDirectory(None, u"請選擇資料路徑", "", QFileDialog.ShowDirsOnly)
        if dataPath != "":
            self.dockwidget.lineEdit.clear()

            if dataPath[len(dataPath)-1] != "\\":
                dataPath = dataPath + "\\"
            #QMessageBox.information(self.iface.mainWindow(), "X", dataPath[len(dataPath)-1])
            self.dockwidget.lineEdit.insert(dataPath)
        
        self.writeDefaultPath()

######################################################################################


########外部地圖服功能############################

    def openWMTSDia(self):
        
        #for i in range(self.WMTSDia.tableWidget_3.rowCount()-1, -1, -1):
        #self.WMTSDia.tableWidget_3.removeRow(i)
        self.WMTSDia.comboBox_2.clear()
        filePath = rootPath + 'DefaultWMTS_Url.csv'
        WMTSURLListfile = open(filePath, 'r')
        #WMTSURLListfile = open('C:/data/DefaultWMTS_Url.csv', 'r')
        csvCursor = csv.reader(WMTSURLListfile)
        WMTSURLList = []
        for row in csvCursor:
            WMTSURLList.append(row)

        for i in range(len(WMTSURLList)):
            try:                         
                self.WMTSDia.comboBox_2.insertItem(i, WMTSURLList[i][0])
            except:
                continue
            #self.WMTSDia.tableWidget_3.insertRow( self.WMTSDia.tableWidget_3.rowCount() )
            #self.WMTSDia.tableWidget_3.setItem(self.WMTSDia.tableWidget_3.rowCount()-1, 0, QtGui.QTableWidgetItem(WMTSList[i][0].decode('utf-8')))
            #self.WMTSDia.tableWidget_3.setItem(self.WMTSDia.tableWidget_3.rowCount()-1, 1, QtGui.QTableWidgetItem(WMTSList[i][1].decode('utf-8')))
            #self.WMTSDia.tableWidget_3.setItem(self.WMTSDia.tableWidget_3.rowCount()-1, 2, QtGui.QTableWidgetItem(WMTSList[i][2].decode('utf-8')))

        for i in range(self.WMTSDia.tableWidget_4.rowCount()-1, -1, -1):
            self.WMTSDia.tableWidget_4.removeRow(i)
        filePath = rootPath + 'DefaultWMTS_Layer.csv'
        WMTSDefaultListFile = open(filePath, 'r')
        #WMTSDefaultListFile = open('C:/data/DefaultWMTS_Layer.csv', 'r')
        csvCursor = csv.reader(WMTSDefaultListFile)
        WMTSDefaultList = []
        for row in csvCursor:
            WMTSDefaultList.append(row)

        for i in range(len(WMTSDefaultList)):
            try:
                self.WMTSDia.tableWidget_4.insertRow( self.WMTSDia.tableWidget_4.rowCount() )
                self.WMTSDia.tableWidget_4.setItem(self.WMTSDia.tableWidget_4.rowCount()-1, 0, QTableWidgetItem(WMTSDefaultList[i][0]))
                self.WMTSDia.tableWidget_4.setItem(self.WMTSDia.tableWidget_4.rowCount()-1, 1, QTableWidgetItem(WMTSDefaultList[i][1]))
                self.WMTSDia.tableWidget_4.setItem(self.WMTSDia.tableWidget_4.rowCount()-1, 2, QTableWidgetItem(WMTSDefaultList[i][2]))
            except:
                continue
        self.WMTSDia.show()

    def addWMTSto(self):
        i=0
        filePath = rootPath + 'DefaultWMTS_Url.csv' 
        WMTSURLListfile = open(filePath, 'r')   
        #WMTSURLListfile = open('C:/data/DefaultWMTS_Url.csv', 'r')
        csvCursor = csv.reader(WMTSURLListfile)
        WMTSURLList = []
        for row in csvCursor:
            WMTSURLList.append(row)
        newUrl = [self.addWMTSDia.lineEdit_4.text(), self.addWMTSDia.lineEdit_5.text()]
        WMTSURLList.append(newUrl)
        WMTSURLListfile.close()

        self.addWMTSDia.close()
        self.addWMTSDia.lineEdit_4.clear()
        self.addWMTSDia.lineEdit_5.clear()

        self.WMTSDia.comboBox_2.clear()
        for i in range(len(WMTSURLList)):
            try:
                self.WMTSDia.comboBox_2.insertItem(i, WMTSURLList[i][0])
            except:
                continue
        
        #filePath_2 = rootPath + 'DefaultWMTS_Url.csv' 
        file = open(filePath, 'w', newline='')
        w = csv.writer(file)
        w.writerows(WMTSURLList)
        file.close()
    
    def showaddWMTSDia(self):
        self.addWMTSDia.show()

    def rmService(self):

        i=0
        filePath = rootPath + 'DefaultWMTS_Url.csv' 
        WMTSURLListfile = open(filePath, 'r')
        #WMTSURLListfile = open('C:/data/DefaultWMTS_Url.csv', 'r')
        csvCursor = csv.reader(WMTSURLListfile)
        WMTSURLList = []
        for row in csvCursor:
        #QMessageBox.information(self.iface.mainWindow(), "mes".decode('utf-8'), str(self.WMTSDia.comboBox_2.currentIndex()))
            if i != self.WMTSDia.comboBox_2.currentIndex():
                WMTSURLList.append(row)
                #QMessageBox.information(self.iface.mainWindow(), "mes".decode('utf-8'), str(i))
            i+=1
        WMTSURLListfile.close()

        self.WMTSDia.comboBox_2.clear()
        for i in range(len(WMTSURLList)):
            try:
                self.WMTSDia.comboBox_2.insertItem(i, WMTSURLList[i][0])
            except:
                continue

        file = open(filePath, 'w', newline='')
        #file = open('C:/data/DefaultWMTS_Url.csv', 'w')
        w = csv.writer(file)
        w.writerows(WMTSURLList)
        file.close()  
   

    def WMTScls(self):
        self.WMTSDia.comboBox.clear()
    
    def loadWMTS_2(self):
        if self.WMTSDia.tableWidget_4.currentRow() != -1:
            #urlWithParams = 'contextualWMSLegend=0&crs=EPSG:3857&dpiMode=7&featureCount=10&format=image/jpeg&layers=JM20K_1904&styles=default&tileMatrixSet=GoogleMapsCompatible&url=http://gis.sinica.edu.tw/tileserver/wmts'
            urlWithParams = self.WMTSDia.tableWidget_4.item(self.WMTSDia.tableWidget_4.currentRow(), 2).text()
            rlayer = QgsRasterLayer(urlWithParams, self.WMTSDia.tableWidget_4.item(self.WMTSDia.tableWidget_4.currentRow(), 1).text(), 'wms')
            QgsProject.instance().addMapLayer(rlayer)
            # QgsProject.instance().addMapLayer(rlayer) 

    def getWMTSList(self):
        #QMessageBox.information(self.iface.mainWindow(), "mes".decode('utf-8'), self.WMTSDia.lineEdit_4.text())
        
        self.WMTSDia.comboBox.clear()
        i=0
        filePath = rootPath + 'DefaultWMTS_Url.csv'
        WMTSURLListfile = open(filePath, 'r')
        #WMTSURLListfile = open('C:/data/DefaultWMTS_Url.csv', 'r')
        csvCursor = csv.reader(WMTSURLListfile)
        WMTSURLList = []
        for row in csvCursor:
            WMTSURLList.append(row)

        #for i in range(len(WMTSURLList)):
        #self.WMTSDia.comboBox_2.insertItem(i, WMTSURLList[i][0].decode('utf-8'))
        
        response = urllib.request.urlopen(WMTSURLList[self.WMTSDia.comboBox_2.currentIndex()][1])        
        xmlDoc = xml.dom.minidom.parse(response)
        root = xmlDoc.documentElement
        layerList =  root.getElementsByTagName('Layer')

        
        #QMessageBox.information(self.iface.mainWindow(), "mes", layerList[0].childNodes[0].data)
        #for content in contentList:
        #layerList   = contentList.getElementsByTagName('Layer')
        #QMessageBox.information(self.iface.mainWindow(), "mes", "111")
        #self.WMTSDia.comboBox.insertItem(i, owsTitilList[i].childNodes[0].data)
        for layer in layerList:
            try:
                owsTitleList = layer.getElementsByTagName('ows:Title')
                #owsIdentifier = layer.getElementsByTagName('ows:Identifier')
                #imgformatList = layer.getElementsByTagName('Format')
                self.WMTSDia.comboBox.insertItem(i, owsTitleList[0].childNodes[0].data) 
                i+=1
            except:
                continue

    
    def addToList(self):
        #QMessageBox.information(self.iface.mainWindow(), "mes".decode('utf-8'), str(self.WMTSDia.comboBox.currentIndex()))
        filePath = rootPath + 'DefaultWMTS_Url.csv'
        WMTSURLListfile = open(filePath, 'r')
        #WMTSURLListfile = open('C:/data/DefaultWMTS_Url.csv', 'r')
        csvCursor = csv.reader(WMTSURLListfile)
        WMTSURLList = []
        for row in csvCursor:
            WMTSURLList.append(row)

        response = urllib.request.urlopen(WMTSURLList[self.WMTSDia.comboBox_2.currentIndex()][1])
        xmlDoc = xml.dom.minidom.parse(response)
        root = xmlDoc.documentElement
        layerList =  root.getElementsByTagName('Layer')

        wmtsTitleList = []
        wmtsIdentifierList = []
        wmtsFormatList = []

        for layer in layerList:
            owsTitleList = layer.getElementsByTagName('ows:Title')
            owsIdentifier = layer.getElementsByTagName('ows:Identifier')
            imgformatList = layer.getElementsByTagName('Format')

            wmtsTitleList.append(owsTitleList[0].childNodes[0].data)
            wmtsIdentifierList.append(owsIdentifier[0].childNodes[0].data)
            wmtsFormatList.append(imgformatList[0].childNodes[0].data)
            #self.WMTSDia.comboBox.insertItem(i, owsTitleList[0].childNodes[0].data) 
            #i+=1

        self.WMTSDia.tableWidget_4.insertRow( self.WMTSDia.tableWidget_4.rowCount() )
        self.WMTSDia.tableWidget_4.setItem(self.WMTSDia.tableWidget_4.rowCount()-1, 1, QTableWidgetItem(wmtsTitleList[self.WMTSDia.comboBox.currentIndex()]))
        self.WMTSDia.tableWidget_4.setItem(self.WMTSDia.tableWidget_4.rowCount()-1, 0, QTableWidgetItem(wmtsIdentifierList[self.WMTSDia.comboBox.currentIndex()]))
        wmtsUrl = 'contextualWMSLegend=0&crs=EPSG:3857&dpiMode=7&featureCount=10&format=' + wmtsFormatList[self.WMTSDia.comboBox.currentIndex()] + '&layers=' + wmtsIdentifierList[self.WMTSDia.comboBox.currentIndex()] + '&styles=default&tileMatrixSet=GoogleMapsCompatible&url=' + WMTSURLList[self.WMTSDia.comboBox_2.currentIndex()][1]
        #sm = '111' +WMTSURLList[self.WMTSDia.comboBox_2.currentIndex()][1]
        #QMessageBox.information(self.iface.mainWindow(), "mes".decode('utf-8'), sm)
        self.WMTSDia.tableWidget_4.setItem(self.WMTSDia.tableWidget_4.rowCount()-1, 2, QTableWidgetItem(wmtsUrl))
    
    def rmItem(self):
        self.WMTSDia.tableWidget_4.removeRow(self.WMTSDia.tableWidget_4.currentRow())
    
    def saveToWMTSList(self):
        favoriteWMTSList = []
        for i in range(0, self.WMTSDia.tableWidget_4.rowCount(), 1):
            favoriteWMTSList.append([])
            str=self.WMTSDia.tableWidget_4.item(i, 0).text()
            favoriteWMTSList[i].append(str)
            str=self.WMTSDia.tableWidget_4.item(i, 1).text()
            favoriteWMTSList[i].append(str)
            str=self.WMTSDia.tableWidget_4.item(i, 2).text()
            favoriteWMTSList[i].append(str)

        filePath = rootPath + 'DefaultWMTS_Layer.csv'
        file = open(filePath, 'w', newline='')        
        w = csv.writer(file)
        w.writerows(favoriteWMTSList)
        file.close()

        self.WMTSDia.comboBox_2.setCurrentIndex(0)
        self.WMTSDia.comboBox.clear()

###########################################


####開啟主題圖功能####

    def openQGS(self):
        qgsFileName = QFileDialog.getOpenFileName(None, u"請選擇專案檔", self.dockwidget.lineEdit.text(), "qgs files (*.qgs)")
        project = QgsProject.instance() 
        project.read(qgsFileName[0])

###########################################
    

    


#####照片GPX軌跡定位######

    def photogpx_show(self):
        self.photogpxDia.lineEdit_3.clear()
        self.photogpxDia.lineEdit.clear()
        self.photogpxDia.spinBox.setValue(0)
        self.photogpxDia.spinBox_2.setValue(0)
        self.photogpxDia.spinBox_3.setValue(0)
        self.photogpxDia.spinBox_4.setValue(0)
        self.photogpxDia.lineEdit_2.clear() 
        self.photogpxDia.show()

    def getPhotoNamePX(self):
        photoFileName = QFileDialog.getOpenFileName(None, u"請選擇照片檔案", self.dockwidget.lineEdit.text(), "jpeg files (*.jpeg),(*.jpg)")
        self.photogpxDia.lineEdit_3.clear()
        self.photogpxDia.lineEdit_3.insert(photoFileName[0])

    def getGPXNamePX(self):
        gpxFileName = QFileDialog.getOpenFileName(None, u"請選擇GPX檔案", self.dockwidget.lineEdit.text(), "GPX files (*.gpx)")
        self.photogpxDia.lineEdit.clear()
        self.photogpxDia.lineEdit.insert(gpxFileName[0])
 

    def getSHPNamePX(self):
        shpFileName = QFileDialog.getSaveFileName(None, u"圖層另存為", self.dockwidget.lineEdit.text(), "SHP files (*.shp)")
        self.photogpxDia.lineEdit_2.clear()
        self.photogpxDia.lineEdit_2.insert(shpFileName[0])
    

    def inputphotogpx(self):

        self.exifread_module = False
        self.pil_module = False

        if CHECK_MODULE == '' and self.showMessageHide:
            self.showMessage('Python Modules', 'Please install python module "exifread" or "PIL".' , 'Warning')

        ##匯入照片EXIF
        if CHECK_MODULE == 'exifread' and not self.pil_module:
            self.exifread_module = True
            f = open(self.photogpxDia.lineEdit_3.text(), 'rb')
            tags = exifread.process_file(f)
            photoname = os.path.basename(self.photogpxDia.lineEdit_3.text())
            phototime = datetime.strptime(str(tags['Image DateTime']),'%Y:%m:%d %H:%M:%S')
            phototime2 = tags['Image DateTime']
            imgpath = self.photogpxDia.lineEdit_3.text()
            name = os.path.basename(imgpath)

            if 'GPS GPSAltitude' in tags:
                altitude = float(tags["GPS GPSAltitude"].values[0].num) / float(
                    tags["GPS GPSAltitude"].values[0].den)
            else:
                altitude = ''
            uuid_ = str(uuid.uuid4())

            try:
                dt1, dt2 = tags["EXIF DateTimeOriginal"].values.split()
                date = dt1.replace(':', '/')
                time_ = dt2
                timestamp = dt1.replace(':', '-') + 'T' + time_
            except:
                try:
                    date = tags["GPS GPSDate"].values.replace(':', '/')
                    tt = [str(i) for i in tags["GPS GPSTimeStamp"].values]
                    time_ = "{:0>2}:{:0>2}:{:0>2}".format(tt[0], tt[1], tt[2])
                    timestamp = tags["GPS GPSDate"].values.replace(':', '-') + 'T' + time_
                except:
                    date = ''
                    time_ = ''
                    timestamp = ''

            if 'GPS GPSImgDirection' in tags:
                azimuth = float(tags["GPS GPSImgDirection"].values[0].num) / float(
                    tags["GPS GPSImgDirection"].values[0].den)
            else:
                azimuth = ''

            if 'GPS GPSImgDirectionRef' in tags:
                north = str(tags["GPS GPSImgDirectionRef"].values)
            else:
                north = ''

            if 'Image Make' in tags:
                maker = tags['Image Make']
            else:
                maker = ''

            if 'Image Model' in tags:
                model = tags['Image Model']
            else:
                model = ''

            if 'Image ImageDescription' in tags:
                title = tags['Image ImageDescription']
            else:
                title = ''

            if 'EXIF UserComment' in tags:
                user_comm = tags['EXIF UserComment'].printable
            else:
                user_comm = ''


        if CHECK_MODULE == 'PIL' and not self.exifread_module:
            self.pil_module = True
            img = Image.open(self.photogpxDia.lineEdit_3.text())
            exif = img._getexif()
            #print(exif)
            tags = {}
            for tag, value in exif.items():
                decoded = ExifTags.TAGS.get(tag, tag) #exif.items()傳回的tag只是編號, 利用ExifTags.TAGS.get()來取得tag名稱
                tags[decoded] = value
                #print("%s -> %s" % (decoded, value))        
            photoname = os.path.basename(self.photogpxDia.lineEdit_3.text())
            phototime = datetime.strptime(tags["DateTimeDigitized"],'%Y:%m:%d %H:%M:%S')
            phototime2 = tags["DateTimeDigitized"]

            a = {}
            info = Image.open(imgpath)
            info = info._getexif()

            # if info == None:
            #     continue

            for tag, value in info.items():
                if TAGS.get(tag, tag) == 'GPSInfo' or TAGS.get(tag, tag) == 'DateTime' or TAGS.get(tag,
                                                                                                           tag) == 'DateTimeOriginal':
                    a[TAGS.get(tag, tag)] = value

            # if a == {}:
            #     continue


            if a['GPSInfo'] != {}:
                # if 1 and 2 and 3 and 4 in a['GPSInfo']:
                #     lat = [float(x) / float(y) for x, y in a['GPSInfo'][2]]
                #     latref = a['GPSInfo'][1]
                #     lon = [float(x) / float(y) for x, y in a['GPSInfo'][4]]
                #     lonref = a['GPSInfo'][3]

                #     lat = lat[0] + lat[1] / 60 + lat[2] / 3600
                #     lon = lon[0] + lon[1] / 60 + lon[2] / 3600

                #     if latref == 'S':
                #         lat = -lat
                #     if lonref == 'W':
                #         lon = -lon
                # else:
                #     continue

                uuid_ = str(uuid.uuid4())
                if 'DateTime' or 'DateTimeOriginal' in a:
                    if 'DateTime' in a:
                        dt1, dt2 = a['DateTime'].split()
                    if 'DateTimeOriginal' in a:
                        dt1, dt2 = a['DateTimeOriginal'].split()
                    date = dt1.replace(':', '/')
                    time_ = dt2
                    timestamp = dt1.replace(':', '-') + 'T' + time_

                if 6 in a['GPSInfo']:
                    if len(a['GPSInfo'][6]) > 1:
                        mAltitude = float(a['GPSInfo'][6][0])
                        mAltitudeDec = float(a['GPSInfo'][6][1])
                        altitude = mAltitude / mAltitudeDec
                else:
                    altitude = ''

                if 16 and 17 in a['GPSInfo']:
                    north = str(a['GPSInfo'][16])
                    azimuth = float(a['GPSInfo'][17][0]) / float(a['GPSInfo'][17][1])
                else:
                    north = ''
                    azimuth = ''

                maker = ''
                model = ''
                user_comm = ''
                title = ''

        
        if self.photogpxDia.radioButton_9.isChecked():
            phototime + timedelta(days=int(self.photogpxDia.spinBox.text()),hours=int(self.photogpxDia.spinBox_2.text()),minutes=int(self.photogpxDia.spinBox_3.text()),seconds=int(self.photogpxDia.spinBox_4.text()))
        if self.photogpxDia.radioButton_8.isChecked():
            phototime - timedelta(days=int(self.photogpxDia.spinBox.text()),hours=int(self.photogpxDia.spinBox_2.text()),minutes=int(self.photogpxDia.spinBox_3.text()),seconds=int(self.photogpxDia.spinBox_4.text()))

        #擷取GPX XML檔內的座標點為資料
        photoPath = self.photogpxDia.lineEdit.text()
        dom = xmini.parse(photoPath)

        gpxlist=[]
        for i in dom.getElementsByTagName("trkpt"):            
            _getL=i.getAttribute("lat")
            _getLo=i.getAttribute("lon")
            _getEle=i.getElementsByTagName("ele").item(0).childNodes.item(0).nodeValue
            _gett=i.getElementsByTagName("time").item(0).childNodes.item(0).nodeValue            
            gpxlist.append({"Lat":_getL,"Lon":_getLo,"elev":_getEle,"time":_gett,"timelag":0,"type":0})

        for x in range(0,len(gpxlist)):
            gpxtime = datetime.strptime(gpxlist[x]["time"], '%Y-%m-%dT%H:%M:%S%fZ')
            gpxlist[x]["time"] = gpxtime

        timelaglist=[]
        for x in range(0,len(gpxlist)):
            timelag = phototime - gpxlist[x]["time"]
            gpxlist[x]["timelag"] = timelag
            timelaglist.append(timelag)
        
        photogpxlist=[]
        for x in range(0,len(gpxlist)):
            if gpxlist[x]["timelag"] == min(timelaglist):                
                photogpxlist.append(gpxlist[x])



        geoPhotos = []

        # geo_info = {"type": "Feature",
        #                             "properties": {'ID': 'temp01', 'Name': photoname, 'DateTime': str(phototime),
        #                                         'Lon': photogpxlist[0]['Lon'],
        #                                         'Lat': photogpxlist[0]['Lat'], 'Path': self.photogpxDia.lineEdit_3.text(),
        #                                           },
        #                             "geometry": {"coordinates": [float(photogpxlist[0]['Lon']),float(photogpxlist[0]['Lat'])], "type": "Point"}}
        


        geo_info = {"type": "Feature",
                            "properties": {'ID': uuid_, 'Name': name, 'Date': date, 'Time': time_,
                                           'Lon': photogpxlist[0]['Lon'],
                                           'Lat': photogpxlist[0]['Lat'], 'Altitude': altitude, 'North': north,
                                           'Azimuth': azimuth,
                                           'Camera Maker': str(maker), 'Camera Model': str(model), 'Title': str(title),
                                           'Comment': user_comm,'Path': imgpath, 'RelPath': imgpath,
                                           'Timestamp': timestamp},
                            "geometry": {"coordinates": [float(photogpxlist[0]['Lon']),float(photogpxlist[0]['Lat'])], "type": "Point"}}

        geoPhotos.append(geo_info)
        
        self.creatgeojson(photoname,geoPhotos)
        # self.creatXML(photogpxlist,GPXtempPath)
        # self.gpx2shpPX()
        QMessageBox.information(self.iface.mainWindow(), str(phototime), str(phototime))
    #資料匯出產生geojson文件
    def creatgeojson(self,photoname,geoPhotos):

        if self.photogpxDia.comboBox.currentIndex()==1 : #twd97        
            crs = "urn:ogc:def:crs:EPSG::3826"
        if self.photogpxDia.comboBox.currentIndex()==0 : #wgs84           
            crs = "crs:OGC:1.3:CRS84"

        geojson = {"type": "FeatureCollection",
                   "name": photoname,
                   "crs": {"type": "Feature", "properties": {"name": crs}},
                   "features": geoPhotos}
        
        geofile = open(geojsonPath, 'w')
        json.dump(geojson, geofile)
        geofile.close()

        self.gpx2shpPX()

    # ##資料匯出產生XML文件
    # def creatXML(self,gpxlist,savePath):
    #     #在暫存中創建檔案
    #     doc = xmini.Document() 
    #     #建立根結點GPX
    #     root = doc.createElement('gpx') 
    #     #設置截點屬性
    #     root.setAttribute('creator', 'FCU_GIS') 
    #     root.setAttribute('version', '1.0') 
    #     #將截點增加到檔案中
    #     doc.appendChild(root) 
       
    #     nodeTrk = doc.createElement('trk')
    #     nodeName = doc.createElement('name')
    #     nodeName.appendChild(doc.createTextNode('reviseGPX'))
    #     nodetrkseg = doc.createElement('trkseg')

    #     for i in range(0,len(gpxlist)) :
    #         nodetrkpt = doc.createElement('trkpt')
    #         nodetrkpt.setAttribute('lat',gpxlist[i]["Lat"])
    #         nodetrkpt.setAttribute('lon',gpxlist[i]["Lon"])
    #         nodeEle = doc.createElement('ele')
    #         #给叶子节点name设置一个文本节点，用于显示文本内容
    #         nodeEle.appendChild(doc.createTextNode(gpxlist[i]["elev"]))

    #         nodeTime = doc.createElement("time")
    #         nodeTime.appendChild(doc.createTextNode(str(gpxlist[i]["time"])))

    #         nodePath = doc.createElement("Path")
    #         nodePath.appendChild(doc.createTextNode(self.photogpxDia.lineEdit_3.text()))
            

    #         #将各叶子节点添加到父节点Manager中，
    #         #最后将Manager添加到根节点Managers中
    #         nodetrkpt.appendChild(nodeEle)
    #         nodetrkpt.appendChild(nodeTime)
    #         nodetrkpt.appendChild(nodePath)
    #         nodetrkseg.appendChild(nodetrkpt)      
            
        
        
    #     nodeTrk.appendChild(nodeName)
    #     nodeTrk.appendChild(nodetrkseg)
    #     root.appendChild(nodeTrk)

    #     #寫入檔案
    #     fp = open(savePath, 'w')
    #     doc.writexml(fp, indent='\t', addindent='\t', newl='\n', encoding="utf-8")

           
    def gpx2shpPX(self):

        global layerPath
        global layeridName             
        
        # layerPath = GPXtempPath + '|layerid=4'
        # layeridName='track_point' 

        # layerName =  GPXtempPath+layeridName

        
        # self.iface.addVectorLayer(layerPath, layerName, "ogr")

        self.iface.addVectorLayer(geojsonPath, geojsonPath, "ogr")
        

        extent = self.iface.activeLayer().extent()
        self.canvas.setExtent(extent)    


        # decide crs

        if self.photogpxDia.comboBox.currentIndex()==1 : #twd97
        #crs = "point?crs=epsg:3826"
            crs=QgsCoordinateReferenceSystem("epsg:3826")
        if self.photogpxDia.comboBox.currentIndex()==0 : #wgs84
        #crs = "point?crs=epsg:4326"    
            crs=QgsCoordinateReferenceSystem("epsg:4326")
    
        _writer = QgsVectorFileWriter.writeAsVectorFormat(self.iface.activeLayer(), self.photogpxDia.lineEdit_2.text(), "utf-8", crs, "ESRI Shapefile")

        outfile = "輸出檔案:" + self.photogpxDia.lineEdit_2.text()
        QMessageBox.information(self.iface.mainWindow(), u"轉換完成", outfile )
        
        QgsProject.instance().removeMapLayers( [self.iface.activeLayer().id()] )
        layer=QgsVectorLayer(self.photogpxDia.lineEdit_2.text() , self.photogpxDia.lineEdit_2.text(), "ogr")
        QgsProject.instance().addMapLayers([layer])

        # Layer = self.iface.activeLayer()    
        # Layer.dataProvider().addAttributes([QgsField('Path', QVariant.String)])
        # Layer.updateFields()

########################################


####GPX飄移點修正#########

    #GPX飄移點處理初始參數###
    def Gpxrevise_show(self):        
            self.GpxreviseDia.imp.clear()        
            self.GpxreviseDia.lineEdit_3.clear()
            self.GpxreviseDia.lineEdit_4.clear()
            self.GpxreviseDia.lineEdit_5.clear()
            self.GpxreviseDia.lineEdit_6.clear()
            self.GpxreviseDia.lineEdit_7.clear()
            self.GpxreviseDia.show()


#選取GPX檔案
    def getGPXNameGX(self):
        gpxFileName = QFileDialog.getOpenFileName(None, u"請選擇GPX檔案", self.dockwidget.lineEdit.text(), "GPX files (*.gpx)")
        self.GpxreviseDia.lineEdit_3.clear()
        self.GpxreviseDia.lineEdit_3.insert(gpxFileName[0])

    #選取GPX輸出路徑
    def saveGPX(self):
        savegpxFileName = QFileDialog.getSaveFileName(None, u"另存新檔", self.dockwidget.lineEdit.text(), "GPX files (*.gpx)")
        self.GpxreviseDia.lineEdit_7.clear()
        self.GpxreviseDia.lineEdit_7.insert(savegpxFileName[0])

    ##資料匯出產生XML文件
    def GXcreatXML(self,gpxlist):
        #在暫存中創建檔案
        doc = xmini.Document() 
        #建立根結點GPX
        root = doc.createElement('gpx') 
        #設置截點屬性
        root.setAttribute('creator', 'FCU_GIS') 
        root.setAttribute('version', '1.0') 
        #將截點增加到檔案中
        doc.appendChild(root) 
       
        nodeTrk = doc.createElement('trk')
        nodeName = doc.createElement('name')
        nodeName.appendChild(doc.createTextNode('reviseGPX'))
        nodetrkseg = doc.createElement('trkseg')

        for i in range(0,len(gpxlist)) :
            nodetrkpt = doc.createElement('trkpt')
            nodetrkpt.setAttribute('lat',gpxlist[i]["Lat"])
            nodetrkpt.setAttribute('lon',gpxlist[i]["Lon"])
            nodeEle = doc.createElement('ele')
            #给叶子节点name设置一个文本节点，用于显示文本内容
            nodeEle.appendChild(doc.createTextNode(gpxlist[i]["elev"]))

            nodeTime = doc.createElement("time")
            nodeTime.appendChild(doc.createTextNode(gpxlist[i]["time"]))
            

            #将各叶子节点添加到父节点Manager中，
            #最后将Manager添加到根节点Managers中
            nodetrkpt.appendChild(nodeEle)
            nodetrkpt.appendChild(nodeTime)
            nodetrkseg.appendChild(nodetrkpt)      
            
        
        
        nodeTrk.appendChild(nodeName)
        nodeTrk.appendChild(nodetrkseg)
        root.appendChild(nodeTrk)

        #寫入檔案
        fp = open(self.GpxreviseDia.lineEdit_7.text(), 'w')
        doc.writexml(fp, indent='\t', addindent='\t', newl='\n', encoding="utf-8")
    
    #檢測飄移點
    def processGPX(self):        
        if self.GpxreviseDia.lineEdit_3.text() == '':
            QMessageBox.information(self.iface.mainWindow(), '請選取GPX檔', 'GPX檔不能空白，請選取GPX檔')   

            
        #擷取GPX XML檔內的座標點為資料
        dom = xmini.parse(self.GpxreviseDia.lineEdit_3.text())

        gpxlist=[]        
        
        try:
            for i in dom.getElementsByTagName("trkpt"):                        
                _getL=i.getAttribute("lat")
                _getLo=i.getAttribute("lon")
                _getEle=i.getElementsByTagName("ele").item(0).childNodes.item(0).nodeValue
                _gett=i.getElementsByTagName("time").item(0).childNodes.item(0).nodeValue            
                gpxlist.append({"Lat":_getL,"Lon":_getLo,"elev":_getEle,"time":_gett,"rate":0,"type":0}) 
                
        except:
            QMessageBox.information(self.iface.mainWindow(),'GPX檔案格式錯誤', 'GPX檔案格式不支援' + self.GpxreviseDia.lineEdit_3.text())
            
        
            

        
        #計算GPX座標距離總和
        distance = []
        for x in range(0,len(gpxlist)):
        
            if x + 1 < len(gpxlist):     

                R = 6373.0
                lat1 = radians(float(gpxlist[x]["Lat"]))
                lon1 = radians(float(gpxlist[x]["Lon"]))
                lat2 = radians(float(gpxlist[x + 1]["Lat"]))
                lon2 = radians(float(gpxlist[x + 1]["Lon"]))      

                dlon = lon2 - lon1
                dlat = lat2 - lat1

                a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
                c = 2 * atan2(sqrt(a), sqrt(1 - a))

                remote = R * c
                #print("Distance: " + str(distance) + "km")   

                distance.append(remote)

            else:
                break
        
        sum_distance = sum(distance)

        #時間格式轉換與計算點位時間差
        timelist = []
        for x in range(0,len(gpxlist)): 
            timelist.append(datetime.strptime(gpxlist[x]["time"], '%Y-%m-%dT%H:%M:%S%fZ'))


        timelag=[]
        for x in range(0,len(timelist)):
            if x + 1 < len(timelist):
                timelag.append((timelist[x+1]-timelist[x]).total_seconds()/60/60)
            else:
                break

        sum_timelag = sum(timelag)

        #計算點位的速率
        np.seterr(divide='ignore', invalid='ignore')

        ratelist = np.divide(np.array(distance),np.array(timelag))

        for x in range(0,len(ratelist)):
            if ratelist[x] != 0 :
                gpxlist[x]["rate"] = ratelist[x]
            else:
                gpxlist[x]["rate"] = 0
        
        self.gpxList = gpxlist

        #QMessageBox.information(self.iface.mainWindow(), u"系統測試中", outfile )
        #顯示總距離
        self.GpxreviseDia.lineEdit_4.clear()
        self.GpxreviseDia.lineEdit_4.insert(str(round(sum_distance,3)))

        #顯示總時間
        self.GpxreviseDia.lineEdit_5.clear()
        self.GpxreviseDia.lineEdit_5.insert(str(round(sum_timelag,3)))

        #顯示與計算平均速率
        self.GpxreviseDia.lineEdit_6.clear()
        self.GpxreviseDia.lineEdit_6.insert(str(round(sum_distance / sum_timelag,3)))
        
        #顯示default刪除平均速率
        self.GpxreviseDia.imp.clear()
        self.GpxreviseDia.imp.insert(str(round((sum_distance / sum_timelag)*2,3)))

    
    #刪除飄移點並輸出檔案
    def removeGPX(self):
        gpxlist = self.gpxList        

        removeNUM = self.GpxreviseDia.imp.text()

        out_gpxlist = []

        for x in range(0,len(gpxlist)):
            if gpxlist[x]["rate"] < float(removeNUM) :
                out_gpxlist.append(gpxlist[x])            

        NUM = len(out_gpxlist)

        self.GXcreatXML(out_gpxlist)

        QMessageBox.information(self.iface.mainWindow(), self.GpxreviseDia.lineEdit_7.text(), u"已刪除飄移點"+ str(NUM) +"點，並另存新檔路徑為" + self.GpxreviseDia.lineEdit_7.text())



########################################


###照片EXIF定位###

    

    def ImportPhotos_show(self):
        self.ImportPhotosDia.imp.clear()        
        self.ImportPhotosDia.out.clear()
        self.ImportPhotosDia.load_style_path.clear()  
        self.ImportPhotosDia.show()
    
    def close(self):
        self.ImportPhotosDia.close()

    def mouseClick(self):
        try:
            self.iface.setActiveLayer(self.canvas.layers()[0])
        except:
            pass
        self.canvas.setMapTool(self.toolMouseClick)
        self.clickPhotos.setChecked(True)

    def toolButtonOut(self):
        typefiles = 'ESRI Shapefile (*.shp *.SHP);; GeoJSON (*.geojson *.GEOJSON);; GeoPackage (*.gpkg *.GPKG);; Comma Separated Value (*.csv *.CSV);; Keyhole Markup Language (*.kml *.KML);; Mapinfo TAB (*.tab *.TAB)'
        if platform.system() == 'Linux':
            try:
                self.outputPath, self.extension = QFileDialog.getSaveFileNameAndFilter(None, 'Save File', os.path.join(
                    os.path.join(os.path.expanduser('~')),
                    'Desktop'), typefiles)
            except:
                self.outputPath = QFileDialog.getSaveFileName(None, 'Save File', os.path.join(
                    os.path.join(os.path.expanduser('~')),
                    'Desktop'), typefiles) #hack line
        else:
            self.outputPath = QFileDialog.getSaveFileName(None, 'Save File', os.path.join(
                os.path.join(os.path.expanduser('~')),
                'Desktop'), typefiles)

        self.extension_type = self.outputPath[1]
        self.outputPath = self.outputPath[0]
        if self.extension_type:
            self.extension2 = self.extension_switch2[self.extension_type]

        self.ImportPhotosDia.out.setText(self.outputPath)

    def toolButtonImport(self):
        self.directoryPhotos = QFileDialog.getExistingDirectory(None, 'Select a folder:',
                                                                os.path.join(os.path.join(os.path.expanduser('~')),
                                                                             'Desktop'), QFileDialog.ShowDirsOnly)
        self.selected_folder = self.directoryPhotos[:]; p = '/'
        if '/' in self.selected_folder:
            self.selected_folder = self.selected_folder.split('/')[-1]; p = '/'
        if '\\' in self.selected_folder:
            self.selected_folder = self.selected_folder.split('\\')[-1]; p = '\\'
        if '//' in self.selected_folder:
            self.selected_folder = self.selected_folder.split('//')[-1]; p = '//'
        self.selected_folder = './' + self.selected_folder + p

        self.ImportPhotosDia.imp.setText(self.directoryPhotos)

    def loadstyle(self):
        self.load_style = QFileDialog.getOpenFileName(None, "Load style",
                                               os.path.join(os.path.join(os.path.expanduser('~')), 'Desktop'),
                                               "(*.qml)")
        if self.load_style[0] == "":
            return
        else:
            self.load_style = self.load_style[0]

        self.ImportPhotosDia.load_style_path.setText(self.load_style)

    def selectDir(self):
        title = 'Warning'
        msg = 'Please select a directory photos.'
        self.showMessage(title, msg, 'Warning')
        return True

    def selectOutp(self):
        title = 'Warning'
        msg = 'Please define output file location.'
        self.showMessage(title, msg, 'Warning')
        return True

    def noImageFound(self):
        title = 'Warning'
        msg = 'No image path found.'
        self.showMessage(title, msg, 'Warning')
        return True

    def ok(self):
        if self.ImportPhotosDia.imp.text() == '':
            if self.selectDir():
                return
        if not os.path.isdir(self.ImportPhotosDia.imp.text()):
            if self.selectDir():
                return
        if self.ImportPhotosDia.out.text() == '':
            if self.selectOutp():
                return
        if not os.path.isabs(self.ImportPhotosDia.out.text()):
            if self.selectOutp():
                return

        self.outputPath = self.ImportPhotosDia.out.text()
        self.directoryPhotos = self.ImportPhotosDia.imp.text()

        if self.ImportPhotosDia.input_load_style.text() == '':
            self.load_style = os.path.join(self.plugin_dir, "photos.qml")
        else:
            self.load_style = self.ImportPhotosDia.load_style_path.text()

        if self.load_style != '':
            if not os.path.exists(self.load_style):
                title = 'Warning'
                msg = 'No style path found.'
                self.showMessage(title, msg, 'Warning')
                return

        showMessageHide = True
        self.import_photos(self.directoryPhotos, self.outputPath, self.load_style, showMessageHide)

    def import_photos(self, directoryPhotos, outputPath, load_style, showMessageHide=True):

        if load_style == '':
            self.load_style = os.path.join(self.plugin_dir, "photos.qml")
        else:
            self.load_style = load_style
        self.showMessageHide = showMessageHide
        self.outputPath = outputPath
        self.directoryPhotos = directoryPhotos

        if platform.system() == 'Linux':
            self.lphoto = os.path.basename(self.outputPath)
            try:
                self.extension = '.'+self.extension.split()[-1][2:-1].lower()
            except:
                self.extension = '.shp' #hack line, temporary
        else:
            _ , self.extension = os.path.splitext(self.outputPath)
            basename = os.path.basename(self.outputPath)
            self.lphoto = basename[:-len(self.extension)]

        self.outDirectoryPhotosGeoJSON = os.path.join(self.plugin_dir, 'tmp.geojson')

        self.ImportPhotosDia.ok.setEnabled(False)
        self.ImportPhotosDia.closebutton.setEnabled(False)
        self.ImportPhotosDia.toolButtonImport.setEnabled(False)
        self.ImportPhotosDia.toolButtonOut.setEnabled(False)
        self.ImportPhotosDia.input_load_style.setEnabled(False)

        # get paths of photos
        extens = ['jpg', 'jpeg', 'JPG', 'JPEG']
        self.photos = []
        self.photos_names = []
        for root, dirs, files in os.walk(self.directoryPhotos):
            for name in files:
                if name.lower().endswith(tuple(extens)):
                    self.photos.append(os.path.join(root, name))
                    self.photos_names.append(name)

        self.initphotos = len(self.photos)

        if self.initphotos == 0 and self.showMessageHide:
            title = 'Warning'
            msg = 'No photos.'
            self.showMessage(title, msg, 'Warning')
            self.ImportPhotosDia.ok.setEnabled(True)
            self.ImportPhotosDia.closebutton.setEnabled(True)
            self.ImportPhotosDia.toolButtonImport.setEnabled(True)
            self.ImportPhotosDia.toolButtonOut.setEnabled(True)
            self.ImportPhotosDia.input_load_style.setEnabled(True)
            self.clickPhotos.setChecked(True)
            return

        self.canvas.setMapTool(self.toolMouseClick)

        self.truePhotosCount = 0

        self.Qpr_inst = QgsProject.instance()
        if platform.system()=='Darwin':
            self.layernamePhotos.append(self.lphoto+' OGRGeoJSON Point')
        else:
            self.layernamePhotos.append(self.lphoto)

        if platform.system() == 'Linux':
            self.outputPath = self.outputPath + self.extension
            self.extension = self.extension_switch[self.extension]
        else:
            self.extension = self.extension_switch[self.extension.lower()]

        self.exifread_module = False
        self.pil_module = False

        if CHECK_MODULE == '' and self.showMessageHide:
            self.showMessage('Python Modules', 'Please install python module "exifread" or "PIL".' , 'Warning')

        #self.import_photos_task('', '')
        self.call_import_photos()
        self.ImportPhotosDia.close()

    def refresh(self):  # Deselect features
        mc = self.canvas
        for layer in mc.layers():
            if layer.type() == layer.VectorLayer:
                layer.removeSelection()
        mc.refresh()

    def showMessage(self, title, msg, icon):
        if icon == 'Warning':
            icon = QMessageBox.Warning
        elif icon == 'Information':
            icon = QMessageBox.Information

        msgBox = QMessageBox()
        msgBox.setIcon(icon)
        msgBox.setWindowTitle(title)
        msgBox.setText(msg)
        msgBox.setWindowFlags(Qt.CustomizeWindowHint | Qt.WindowStaysOnTopHint | Qt.WindowCloseButtonHint)
        msgBox.exec_()

    def completed(self, exception, result=None):
        # decide crs

        if self.ImportPhotosDia.comboBox.currentIndex()==1 : #twd97
        #crs = "point?crs=epsg:3826"
            crs=QgsCoordinateReferenceSystem("epsg:3826")
        if self.ImportPhotosDia.comboBox.currentIndex()==0 : #wgs84
        #crs = "point?crs=epsg:4326"    
            crs=QgsCoordinateReferenceSystem("epsg:4326")

        geojson = {"type": "FeatureCollection",
                   "name": self.lphoto,
                   "crs": {"type": "name", "properties": {"name": "crs:OGC:1.3:CRS84"}},
                   "features": self.geoPhotos}

        geofile = open(self.outDirectoryPhotosGeoJSON, 'w')
        json.dump(geojson, geofile)
        geofile.close()
        del self.geoPhotos, geojson

        try:
            for layer in self.canvas.layers():
                if layer.publicSource() == self.outputPath:
                    self.Qpr_inst.instance().removeMapLayer(layer.id())
                    os.remove(self.outputPath)
        except:
            pass

        self.layerPhotos = QgsVectorLayer(self.outDirectoryPhotosGeoJSON, self.lphoto, "ogr")
        # QgsVectorFileWriter.writeAsVectorFormat(self.layerPhotos, self.outputPath, "utf-8",
        #                                             QgsCoordinateReferenceSystem(self.layerPhotos.crs().authid()),
        #                                             self.extension)
        QgsVectorFileWriter.writeAsVectorFormat(self.layerPhotos, self.outputPath, "utf-8", crs, self.extension)
        self.layerPhotos_final = QgsVectorLayer(self.outputPath, self.lphoto, "ogr")

        # clear temp.geojson file
        try:
            f = open(self.outDirectoryPhotosGeoJSON, 'r+')
            f.truncate(0)  # need '0' when using r+
        except:
            pass

        try:
            self.layerPhotos_final.loadNamedStyle(self.load_style)
        except:
            title = 'Warning'
            msg = 'No geo-tagged images were detected.'
            self.showMessage(title, msg, 'Warning')
            self.taskPhotos.destroyed()
            return

        self.layerPhotos_final.setReadOnly(False)
        self.layerPhotos_final.reload()
        self.layerPhotos_final.triggerRepaint()

        try:
            xmin = min(self.lon)
            ymin = min(self.lat)
            xmax = max(self.lon)
            ymax = max(self.lat)
            self.canvas.zoomToSelected(self.layerPhotos_final)
            self.canvas.setExtent(QgsRectangle(xmin, ymin, xmax, ymax))
        except:
            pass

        ###########################################
        self.ImportPhotosDia.ok.setEnabled(True)
        self.ImportPhotosDia.closebutton.setEnabled(True)
        self.ImportPhotosDia.toolButtonImport.setEnabled(True)
        self.ImportPhotosDia.toolButtonOut.setEnabled(True)
        self.ImportPhotosDia.input_load_style.setEnabled(True)
        self.clickPhotos.setChecked(True)

        noLocationPhotosCounter = self.initphotos - self.truePhotosCount
        if (self.truePhotosCount == noLocationPhotosCounter == 0 or self.truePhotosCount == 0 ) and self.showMessageHide:
            title = '照片定位'
            msg = '匯入完成.\n\n明細:\n  沒有增加新照片.'
            self.showMessage(title, msg, 'Information')
            self.taskPhotos.destroyed()
            return
        elif ((self.truePhotosCount == self.initphotos) or ((noLocationPhotosCounter + self.truePhotosCount) == self.initphotos) )and self.showMessageHide:
            title = '照片定位'
            msg = '匯入完成.\n\n明細:\n  ' + str(
                int(self.truePhotosCount)) + ' 照片已新增，沒有錯誤.\n  ' + str(
                int(noLocationPhotosCounter)) + ' 照片已略過 (因缺少座標位置).'
            self.showMessage(title, msg, 'Information')

        g = self.Qpr_inst.layerTreeRoot().insertGroup(0, self.lphoto)
        self.Qpr_inst.addMapLayer(self.layerPhotos_final, False)
        nn = QgsLayerTreeLayer(self.layerPhotos_final)
        g.insertChildNode(0, nn)

    def stopped(self, task):
        QgsMessageLog.logMessage(
            'Task "{name}" was canceled'.format(
                name=task.description()),
            'ImportPhotos', Qgis.Info)

    def import_photos_task(self, task, wait_time):
        self.geoPhotos = []
        self.lon = []
        self.lat = []
        for count, imgpath in enumerate(self.photos):
            try:
                name = os.path.basename(imgpath)
                RelPath = self.selected_folder + self.photos_names[count]
                if CHECK_MODULE == 'exifread' and not self.pil_module:
                    self.exifread_module = True
                    self.taskPhotos.setProgress(count/self.initphotos)
                    with open(imgpath, 'rb') as imgpathF:
                        tags = exifread.process_file(imgpathF, details=False)
                    if not tags.keys() & {"GPS GPSLongitude", "GPS GPSLatitude"}:
                        continue

                    lat, lon = self.get_exif_location(tags, "lonlat")
                    if 'GPS GPSAltitude' in tags:
                        altitude = float(tags["GPS GPSAltitude"].values[0].num) / float(
                            tags["GPS GPSAltitude"].values[0].den)
                    else:
                        altitude = ''
                    uuid_ = str(uuid.uuid4())

                    try:
                        dt1, dt2 = tags["EXIF DateTimeOriginal"].values.split()
                        date = dt1.replace(':', '/')
                        time_ = dt2
                        timestamp = dt1.replace(':', '-') + 'T' + time_
                    except:
                        try:
                            date = tags["GPS GPSDate"].values.replace(':', '/')
                            tt = [str(i) for i in tags["GPS GPSTimeStamp"].values]
                            time_ = "{:0>2}:{:0>2}:{:0>2}".format(tt[0], tt[1], tt[2])
                            timestamp = tags["GPS GPSDate"].values.replace(':', '-') + 'T' + time_
                        except:
                            date = ''
                            time_ = ''
                            timestamp = ''

                    if 'GPS GPSImgDirection' in tags:
                        azimuth = float(tags["GPS GPSImgDirection"].values[0].num) / float(
                            tags["GPS GPSImgDirection"].values[0].den)
                    else:
                        azimuth = ''

                    if 'GPS GPSImgDirectionRef' in tags:
                        north = str(tags["GPS GPSImgDirectionRef"].values)
                    else:
                        north = ''

                    if 'Image Make' in tags:
                        maker = tags['Image Make']
                    else:
                        maker = ''

                    if 'Image Model' in tags:
                        model = tags['Image Model']
                    else:
                        model = ''

                    if 'Image ImageDescription' in tags:
                        title = tags['Image ImageDescription']
                    else:
                        title = ''

                    if 'EXIF UserComment' in tags:
                        user_comm = tags['EXIF UserComment'].printable
                    else:
                        user_comm = ''

                if CHECK_MODULE == 'PIL' and not self.exifread_module:
                    self.pil_module = True
                    a = {}
                    info = Image.open(imgpath)
                    info = info._getexif()

                    if info == None:
                        continue

                    for tag, value in info.items():
                        if TAGS.get(tag, tag) == 'GPSInfo' or TAGS.get(tag, tag) == 'DateTime' or TAGS.get(tag,
                                                                                                           tag) == 'DateTimeOriginal':
                            a[TAGS.get(tag, tag)] = value

                    if a == {}:
                        continue

                    if a['GPSInfo'] != {}:
                        if 1 and 2 and 3 and 4 in a['GPSInfo']:
                            lat = [float(x) / float(y) for x, y in a['GPSInfo'][2]]
                            latref = a['GPSInfo'][1]
                            lon = [float(x) / float(y) for x, y in a['GPSInfo'][4]]
                            lonref = a['GPSInfo'][3]

                            lat = lat[0] + lat[1] / 60 + lat[2] / 3600
                            lon = lon[0] + lon[1] / 60 + lon[2] / 3600

                            if latref == 'S':
                                lat = -lat
                            if lonref == 'W':
                                lon = -lon
                        else:
                            continue

                        uuid_ = str(uuid.uuid4())
                        if 'DateTime' or 'DateTimeOriginal' in a:
                            if 'DateTime' in a:
                                dt1, dt2 = a['DateTime'].split()
                            if 'DateTimeOriginal' in a:
                                dt1, dt2 = a['DateTimeOriginal'].split()
                            date = dt1.replace(':', '/')
                            time_ = dt2
                            timestamp = dt1.replace(':', '-') + 'T' + time_

                        if 6 in a['GPSInfo']:
                            if len(a['GPSInfo'][6]) > 1:
                                mAltitude = float(a['GPSInfo'][6][0])
                                mAltitudeDec = float(a['GPSInfo'][6][1])
                                altitude = mAltitude / mAltitudeDec
                        else:
                            altitude = ''

                        if 16 and 17 in a['GPSInfo']:
                            north = str(a['GPSInfo'][16])
                            azimuth = float(a['GPSInfo'][17][0]) / float(a['GPSInfo'][17][1])
                        else:
                            north = ''
                            azimuth = ''

                        maker = ''
                        model = ''
                        user_comm = ''
                        title = ''
                self.lon.append(lon)
                self.lat.append(lat)
                self.truePhotosCount = self.truePhotosCount + 1

                geo_info = {"type": "Feature",
                            "properties": {'ID': uuid_, 'Name': name, 'Date': date, 'Time': time_,
                                           'Lon': lon,
                                           'Lat': lat, 'Altitude': altitude, 'North': north,
                                           'Azimuth': azimuth,
                                           'Camera Maker': str(maker), 'Camera Model': str(model), 'Title': str(title),
                                           'Comment': user_comm,'Path': imgpath, 'RelPath': RelPath,
                                           'Timestamp': timestamp},
                            "geometry": {"coordinates": [lon, lat], "type": "Point"}}
                self.geoPhotos.append(geo_info)

                if self.taskPhotos.isCanceled():
                    self.stopped(self.taskPhotos)
                    self.taskPhotos.destroyed()
                    return None
            except:
                pass
        return True

    def call_import_photos(self):
        self.taskPhotos = QgsTask.fromFunction(u'ImportPhotos', self.import_photos_task,
                                 on_finished=self.completed, wait_time=4)
        QgsApplication.taskManager().addTask(self.taskPhotos)

######################################################
# based on http://www.codegists.com/snippet/python/exif_gpspy_snakeye_python

    def _get_if_exist(self, data, key):
        if key in data:
            return data[key]

        return None


    def _convert_to_degress(self, value):
        """
        Helper function to convert the GPS coordinates stored in the EXIF to degress in float format

        :param value:
        :type value: exifread.utils.Ratio
        :rtype: float
        """
        d = float(value.values[0].num) / float(value.values[0].den)
        m = float(value.values[1].num) / float(value.values[1].den)
        s = float(value.values[2].num) / float(value.values[2].den)

        return d + (m / 60.0) + (s / 3600.0)


    def get_exif_location(self, exif_data, lonlat):
        """
        Returns the latitude and longitude, if available, from the provided exif_data (obtained through get_exif_data above)
        """

        if lonlat=='lonlat':
            lat = ''
            lon = ''
            gps_latitude = self._get_if_exist(exif_data, 'GPS GPSLatitude')
            gps_latitude_ref = self._get_if_exist(exif_data, 'GPS GPSLatitudeRef')
            gps_longitude = self._get_if_exist(exif_data, 'GPS GPSLongitude')
            gps_longitude_ref = self._get_if_exist(exif_data, 'GPS GPSLongitudeRef')

            if gps_latitude and gps_latitude_ref and gps_longitude and gps_longitude_ref:
                lat = self._convert_to_degress(gps_latitude)
                if gps_latitude_ref.values[0] != 'N':
                    lat = 0 - lat

                lon = self._convert_to_degress(gps_longitude)
                if gps_longitude_ref.values[0] != 'E':
                    lon = 0 - lon

            return lat, lon
    

    ###教學網站連結##########
    def helpDia_show(self):
        QMessageBox.about(self.iface.mainWindow(), "HELP", "<a href='http://qgislearn.forest.gov.tw'>點我看說明文件</a>")

    ## 預載資訊 #########
    def inforDia_show(self):   
        # filePath = rootPath + 'filePathEdit.csv'      
        filePath = rootPath + 'filePath.csv' 
        # filePathfile = open(filePath, 'r')
        filePathfile = open(filePath, 'r', newline='')   
        csvCursor = csv.reader(filePathfile)
        filePathList = []
        for row in csvCursor:
            filePathList.append(row)
        self.inforDia.comboBox.clear()
        for i in range(len(filePathList)):
            try:
                self.inforDia.comboBox.insertItem(i, filePathList[i][2])
                # self.inforDia.comboBox.insertItem(i, filePathList[i][1]+filePathList[i][2]+filePathList[i][3])
            except:
                continue
            

        filePath = rootPath + 'cadastreService.csv' 
        # filePathfile = open(filePath, 'r')
        filePathfile = open(filePath, 'r', newline='')   
        csvCursor = csv.reader(filePathfile)
        filePathList = []
        for row in csvCursor:
            filePathList.append(row)

        self.inforDia.lineEdit_3.setText(filePathList[0][1])

        filePath = rootPath + 'wmsAccount.csv' 
        # filePathfile = open(filePath, 'r') 
        filePathfile = open(filePath, 'r', newline='')  
        csvCursor = csv.reader(filePathfile)
        filePathList = []
        for row in csvCursor:
            filePathList.append(row)

        usrPw = filePathList[0][1] + ':' + filePathList[1][1]


        self.inforDia.lineEdit_4.setText(usrPw)

        self.inforDia.show()

    def reloadFilePath(self):
        # filePath = rootPath + 'filePathEdit.csv' 
        filePath = rootPath + 'filePath.csv' 
        # filePathfile = open(filePath, 'r')
        filePathfile = open(filePath, 'r', newline='')     
        csvCursor = csv.reader(filePathfile)
        filePathList = []
        for row in csvCursor:
            filePathList.append(row)

        self.inforDia.comboBox.clear()
        for i in range(len(filePathList)):
            try:
                self.inforDia.comboBox.insertItem(i, filePathList[i][2])
                # self.inforDia.comboBox.insertItem(i, filePathList[i][1]+filePathList[i][2]+filePathList[i][3])
            except:
                continue



    def edit_filePath(self):
        if self.inforDia.pushButton.isChecked() == True:
            self.inforDia.comboBox.setEditable(True)
            self.inforDia.pushButton_2.setEnabled(True)

        else:
            self.save_filePath()        
            self.inforDia.comboBox.setEditable(False)
            self.inforDia.pushButton_2.setEnabled(False)



    def edit_serverIP(self):
        if  self.inforDia.pushButton_6.isChecked() == True:
            self.inforDia.lineEdit_3.setEnabled(True)
            self.inforDia.pushButton_5.setEnabled(True)
        else:
            self.inforDia.lineEdit_3.setEnabled(False)
            self.inforDia.pushButton_5.setEnabled(False)
            self.save_serverIP()


    def edit_wmsAccount(self):
        if  self.inforDia.pushButton_8.isChecked() == True:
            self.inforDia.lineEdit_4.setEnabled(True)
            self.inforDia.pushButton_7.setEnabled(True)      
        else:
            self.inforDia.lineEdit_4.setEnabled(False)
            self.inforDia.pushButton_7.setEnabled(False) 
            self.save_wmsAccount()


    def save_filePath(self):

        reply = QMessageBox.question(self.iface.mainWindow(), '確定修改?', '任意修改以下資訊將可能造成程式無法運作!!\n確定要修改?', QMessageBox.Yes, QMessageBox.No)
        if reply == QMessageBox.Yes:

            filePath = rootPath + 'filePath.csv' 
            # filePathfile = open(filePath, 'r')
            filePathfile = open(filePath, 'r', newline='')   
            csvCursor = csv.reader(filePathfile)
            filePathListOld = []
            for row in csvCursor:
                filePathListOld.append(row)

            filePathList = []

            for i in range(self.inforDia.comboBox.count()):
                if i == self.inforDia.comboBox.currentIndex():
                    # newfilePath = [i, self.inforDia.comboBox.currentText()[self.inforDia.comboBox.currentText().find('\\')+1:len(self.inforDia.comboBox.currentText())-4], self.inforDia.comboBox.currentText(),filePathListOld[i][3],filePathListOld[i][4]]
                    newfilePath = [i, self.inforDia.comboBox.currentText()[self.inforDia.comboBox.currentText().find('\\')+1:self.inforDia.comboBox.currentText().find('.')], self.inforDia.comboBox.currentText(),filePathListOld[i][3],filePathListOld[i][4]]

                else:
                    # newfilePath = [i, self.inforDia.comboBox.itemText(i)[self.inforDia.comboBox.itemText(i).find('\\')+1:len(self.inforDia.comboBox.itemText(i))-4],self.inforDia.comboBox.itemText(i),filePathListOld[i][3],filePathListOld[i][4]]
                    newfilePath = [i, self.inforDia.comboBox.itemText(i)[self.inforDia.comboBox.itemText(i).find('\\')+1:self.inforDia.comboBox.itemText(i).find('.')],self.inforDia.comboBox.itemText(i),filePathListOld[i][3],filePathListOld[i][4]]  

                filePathList.append(newfilePath)      
                #QMessageBox.information(self.iface.mainWindow(), "X", self.inforDia.comboBox.itemText(i).encode('utf-8'))

            # filePath = rootPath + 'filePath.csv'
            #QMessageBox.information(self.iface.mainWindow(), "X", filePath)
            # file = open(filePath, 'w')
            file = open(filePath, 'w', newline='')
            w = csv.writer(file)
            w.writerows(filePathList)
            file.close()   

            self.reloadFilePath()

        else:
            pass       


    def save_serverIP(self):

        reply = QMessageBox.question(self.iface.mainWindow(), '確定修改?', '任意修改以下資訊將可能造成程式無法運作!!\n確定要修改?', QMessageBox.Yes, QMessageBox.No)
        if reply == QMessageBox.Yes:
            filePathList = []

            newfilePath = [0, self.inforDia.lineEdit_3.text()]
            filePathList.append(newfilePath)      
            #QMessageBox.information(self.iface.mainWindow(), "X", self.inforDia.comboBox.itemText(i).encode('utf-8'))

            #QMessageBox.information(self.iface.mainWindow(), "X", filePathList[1])
            filePath = rootPath + 'cadastreService.csv'
            #QMessageBox.information(self.iface.mainWindow(), "X", filePath)
            # file = open(filePath, 'w')
            file = open(filePath, 'w', newline='')
            w = csv.writer(file)
            w.writerows(filePathList)
            file.close() 

            self.inforDia.lineEdit_3.setEnabled(False)
            self.inforDia.pushButton_5.setEnabled(False)
            self.inforDia.pushButton_6.setChecked(False)

        else:
            pass       




    def save_wmsAccount(self):
        reply = QMessageBox.question(self.iface.mainWindow(), '確定修改?', '任意修改以下資訊將可能造成程式無法運作!!\n確定要修改?', QMessageBox.Yes, QMessageBox.No)

        if reply == QMessageBox.Yes:
            filePathList = []

            newfilePath = [0, self.inforDia.lineEdit_4.text()[0:self.inforDia.lineEdit_4.text().find(':')]]
            filePathList.append(newfilePath)      

            newfilePath = [1, self.inforDia.lineEdit_4.text()[self.inforDia.lineEdit_4.text().find(':')+1: len(self.inforDia.lineEdit_4.text())-1]]
            filePathList.append(newfilePath)          

            filePath = rootPath + 'wmsAccount.csv'

            # file = open(filePath, 'w')
            file = open(filePath, 'w', newline='')
            w = csv.writer(file)
            w.writerows(filePathList)
            file.close() 

            self.inforDia.lineEdit_4.setEnabled(False)
            self.inforDia.pushButton_7.setEnabled(False)
            self.inforDia.pushButton_8.setChecked(False)

        else:
            pass      

    def loadDefaultPath(self):
        filePath = rootPath + 'DefaultFilePath.csv' 
        filePathfile = open(filePath, 'r')   
        csvCursor = csv.reader(filePathfile)
        filePathList = []
        for row in csvCursor:
            filePathList.append(row)

        self.dockwidget.lineEdit.setText(filePathList[0][1])
  
    def writeDefaultPath(self):
        ########################################################
        #                                                      #
        # save Default Path when mainDia close                 #
        #                                                      #
        ########################################################

        
        newfilePath = [0, self.dockwidget.lineEdit.text()]
        filePathList = []
        filePathList.append(newfilePath)

        #QMessageBox.information(self.iface.mainWindow(), "X", filePathList[1])
        filePath = rootPath + 'DefaultFilePath.csv'
        #QMessageBox.information(self.iface.mainWindow(), "X", filePath)
        # file = open(filePath, 'w')
        file = open(filePath, 'w', newline='')
        w = csv.writer(file)
        w.writerows(filePathList)
        file.close()

    


#########################################    

    

    def run(self):
        """Run method that loads and starts the plugin"""

        if not self.pluginIsActive:
            self.pluginIsActive = True

            #print "** STARTING TFB_Tools3"

            # dockwidget may not exist if:
            #    first run of plugin
            #    removed on close (see self.onClosePlugin method)
            if self.dockwidget == None:
                # Create the dockwidget (after translation) and keep reference
                #Open 主要工具列 dockwidget
                self.dockwidget = TFB_Tools3DockWidget()
                self.dockwidget.pushButton.clicked.connect(self.load_25000)
                self.dockwidget.pushButton_2.clicked.connect(self.load_5000)
                self.dockwidget.pushButton_3.clicked.connect(self.wms_show)
                self.dockwidget.pushButton_4.clicked.connect(self.csv2shp_show)
                self.dockwidget.pushButton_5.clicked.connect(self.gpx2shp_show)
                self.dockwidget.pushButton_6.clicked.connect(self.exportSHP_show)                
                self.dockwidget.pushButton_7.clicked.connect(self.openQGS)
                self.dockwidget.pushButton_8.clicked.connect(self.openWMTSDia)
                self.dockwidget.pushButton_9.clicked.connect(self.desideDataPath)
                self.dockwidget.pushButton_10.clicked.connect(self.positioningDia_show)                
                self.dockwidget.pushButton_11.clicked.connect(self.cadastreDia_show)
                self.dockwidget.pushButton_12.clicked.connect(self.inforDia_show)
                self.dockwidget.pushButton_13.clicked.connect(self.helpDia_show)
                self.dockwidget.pushButton_14.clicked.connect(self.ImportPhotos_show)
                self.dockwidget.pushButton_15.clicked.connect(self.photogpx_show)
                self.dockwidget.pushButton_16.clicked.connect(self.Gpxrevise_show)
                self.dockwidget.pushButton_17.clicked.connect(self.mouseClick)
                self.loadDefaultPath()                
                #Close 主要工具列 dockwidget

                #Open 預載資訊 inforDia
                self.inforDia.pushButton.clicked.connect(self.edit_filePath)
                self.inforDia.pushButton_2.clicked.connect(self.save_filePath)
                self.inforDia.pushButton_5.clicked.connect(self.save_serverIP)
                self.inforDia.pushButton_6.clicked.connect(self.edit_serverIP)
                self.inforDia.pushButton_7.clicked.connect(self.save_wmsAccount)
                self.inforDia.pushButton_8.clicked.connect(self.edit_wmsAccount)
                #Close 預載資訊 inforDia


                # Open 快速定位 Positioning Dialog                
                self.positioningDia.rejected.connect(self.reconnection_positioningButton)
                self.positioningDia.comboBox_19.activated[int].connect(self.switchPositioningDia)
                self.positioningDia.comboBox_18.activated[int].connect(self.zoomTo_comboBox_18)
                self.positioningDia.comboBox_18.popupAboutToBeShown.connect(self.addlayer_comboBox_18)
                self.positioningDia.comboBox_17.activated[int].connect(self.zoomTo_comboBox_17)
                self.positioningDia.comboBox_17.popupAboutToBeShown.connect(self.addlayer_comboBox_17)
                self.positioningDia.comboBox_16.activated[int].connect(self.zoomTo_comboBox_16)
                self.positioningDia.comboBox_16.popupAboutToBeShown.connect(self.addlayer_comboBox_16)
                self.positioningDia.comboBox_15.activated[int].connect(self.zoomTo_comboBox_15)
                self.positioningDia.comboBox_15.popupAboutToBeShown.connect(self.addlayer_comboBox_15)
                self.positioningDia.comboBox_14.activated[int].connect(self.zoomTo_comboBox_14)
                self.positioningDia.comboBox_14.popupAboutToBeShown.connect(self.addlayer_comboBox_14)
                self.positioningDia.comboBox_13.activated[int].connect(self.zoomTo_comboBox_13)
                self.positioningDia.comboBox_13.popupAboutToBeShown.connect(self.addlayer_comboBox_13)
                self.positioningDia.comboBox_4.activated[int].connect(self.zoomTo_comboBox_4)
                self.positioningDia.comboBox_4.popupAboutToBeShown.connect(self.addlayer_comboBox_4)
                self.positioningDia.comboBox_20.activated[int].connect(self.zoomTo_comboBox_20)
                self.positioningDia.comboBox_20.popupAboutToBeShown.connect(self.addlayer_comboBox_20)
                self.positioningDia.pushButton_2.clicked.connect(self.queryNo)
                self.positioningDia.comboBox_2.activated[int].connect(self.ComboBox_2_change)
                self.positioningDia.comboBox_3.activated[int].connect(self.ComboBox_3_change)
                self.positioningDia.comboBox_5.activated[int].connect(self.ComboBox_5_change)
                self.positioningDia.comboBox_6.activated[int].connect(self.ComboBox_6_change)
                self.positioningDia.comboBox_7.activated[int].connect(self.ComboBox_7_change)
                self.positioningDia.comboBox_8.activated[int].connect(self.ComboBox_8_change)
                self.positioningDia.comboBox_9.activated[int].connect(self.ComboBox_9_change)
                self.positioningDia.comboBox_10.activated[int].connect(self.ComboBox_10_change)
                self.positioningDia.comboBox_11.activated[int].connect(self.ComboBox_11_change)
                self.positioningDia.comboBox_12.activated[int].connect(self.ComboBox_12_change)
                self.positioningDia.comboBox.activated[int].connect(self.ComboBox_change)
                # End of Open 快速定位 Positioning Dialog

                # Open 載入地籍圖Cadastre Dialog                
                self.cadastreDia.comboBox.activated[int].connect(self.countyToTown)
                self.cadastreDia.comboBox_2.activated[int].connect(self.townToCadastre)
                self.cadastreDia.comboBox_3.activated[int].connect(self.cadastreToNo)
                self.cadastreDia.comboBox_4.activated[int].connect(self.changeCRS)
                self.cadastreDia.comboBox_5.activated[int].connect(self.updateCadastreInfo)
                self.cadastreDia.pushButton.clicked.connect(self.loadWFS)
                self.cadastreDia.pushButton_2.clicked.connect(self.copyForm)
                self.cadastreDia.pushButton_3.clicked.connect(self.loadWFS_XY_Position)
                self.cadastreDia.pushButton_4.clicked.connect(self.loadMultiCadastre)
                self.cadastreDia.pushButton_5.clicked.connect(self.addCadastreItem)
                self.cadastreDia.checkBox.clicked.connect(self.changeQueryMode)
                self.cadastreDia.listWidget.itemClicked.connect(self.cadastreItemClicked)
                self.cadastreDia.listWidget_2.itemClicked.connect(self.cadastreItemDel)
                self.cadastreDia.rejected.connect(self.resetCadastreDia)
                
                # End of Open Cadastre Dialog


                self.positioningDia.comboBox_19.activated[int].connect(self.switchPositioningDia)

                #Open CSV to SHP
                self.csv2shpDia.toolButton.clicked.connect(self.getCSVName)
                self.csv2shpDia.toolButton_2.clicked.connect(self.getSHPName)
                self.csv2shpDia.pushButton.clicked.connect(self.csv2shp)
                #Close CSV to SHP

                #Open GPX to SHP
                self.gpx2shpDia.toolButton.clicked.connect(self.getGPXName)
                self.gpx2shpDia.toolButton_2.clicked.connect(self.getGPX2SHPName)
                self.gpx2shpDia.pushButton.clicked.connect(self.gpx2shp)
                #Close GPX to SHP

                #Open 匯出SHP
                self.exportSHPDia.pushButton.clicked.connect(self.exportSHP)
                #Close 匯出SHP

                #Open 農行所各版正射影像
                self.wmsDia.pushButton.clicked.connect(self.addWMS)
                self.wmsDia.pushButton_2.clicked.connect(self.getID5000)
                self.wmsDia.pushButton_3.clicked.connect(self.getWMSList)
                self.wmsDia.comboBox.activated[int].connect(self.wmsDia_comboBox_change)
                #Close 農行所各版正射影像

                #Open 外部地圖服務
                self.WMTSDia.pushButton_2.clicked.connect(self.getWMTSList)
                self.WMTSDia.pushButton_3.clicked.connect(self.addToList)
                self.WMTSDia.pushButton_4.clicked.connect(self.loadWMTS_2)
                self.WMTSDia.pushButton_6.clicked.connect(self.rmItem)
                self.WMTSDia.pushButton_7.clicked.connect(self.showaddWMTSDia)                
                self.WMTSDia.pushButton_8.clicked.connect(self.rmService)
                self.WMTSDia.rejected.connect(self.saveToWMTSList)
                #Close 外部地圖服務

                #Open 照片EXIF定位
                self.ImportPhotosDia.ok.clicked.connect(self.ok)
                self.ImportPhotosDia.closebutton.clicked.connect(self.close)
                self.ImportPhotosDia.toolButtonImport.clicked.connect(self.toolButtonImport)
                self.ImportPhotosDia.toolButtonOut.clicked.connect(self.toolButtonOut)
                self.ImportPhotosDia.input_load_style.clicked.connect(self.loadstyle)
                #Close 照片EXIF定位

                #Open 照片GPS軌跡定位
                self.photogpxDia.toolButton.clicked.connect(self.getGPXNamePX)
                self.photogpxDia.toolButton_2.clicked.connect(self.getSHPNamePX)
                self.photogpxDia.toolButton_3.clicked.connect(self.getPhotoNamePX)
                self.photogpxDia.pushButton.clicked.connect(self.inputphotogpx)
                #Close 照片GPS軌跡定位

                #Open GPX飄移點處理
                self.GpxreviseDia.pushButton.clicked.connect(self.getGPXNameGX)
                self.GpxreviseDia.pushButton_4.clicked.connect(self.saveGPX)
                self.GpxreviseDia.pushButton_3.clicked.connect(self.processGPX)
                self.GpxreviseDia.pushButton_2.clicked.connect(self.removeGPX)
                #Close GPX飄移點處理

                self.addWMTSDia.pushButton.clicked.connect(self.addWMTSto)

            # connect to provide cleanup on closing of dockwidget
            self.dockwidget.closingPlugin.connect(self.onClosePlugin)

            # show the dockwidget
            # TODO: fix to allow choice of dock location
            self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dockwidget)
            self.dockwidget.show()
