# -*- coding: utf-8 -*-
import os
import arcpy
import uuid
from db.postgresql import Postgresql
import appconfig
from arcpy import env
import platform


class Ztt:
    def __init__(self, data):
        # self.db = Postgresql(appconfig.DB_CONN)
        self.bsm = data["bsm"]
        # self.mxd = data["mxd"]
        # self.jpg = data["jpg"]
        # self.bsm = "d6acdfa1ee494a44a7f131abf69334b9"
        self.db = Postgresql(appconfig.DB_CONN)
        self.task()
        self.mxd = self.task['MBWJ']
        self.jpg = self.task['OUTPUT']
        self.extent = self.task['EXTENT']
        # self.jpg = "D:\\GeoScene\\work\\aprx\\export.jpg"

    def task(self):
        '''加载数据-任务'''
        sql = 'SELECT A.BSM AS "BSM",A.NAME AS "ZBT",A.dtsm AS "FBT",A.zzdw AS "BZDW",A.zzsj AS "BZSJ",a.zttwjlj as "OUTPUT",a.filepath as "EXTENT",B.MBMC AS "MBMC",B.MBWJ AS "MBWJ"  FROM onemap.T_YZT_ZTTK A left JOIN onemap.T_YZT_ZTTMBK b ON A.MBBSM = b.BSM  WHERE A.BSM = \'{0}\''.format(
            self.bsm)
        tasks = self.db.query(sql)
        if len(tasks) == 0:
            self.fxlog(self.bsm, "error", "任务标识错误[{0}]".format(self.bsm))
            raise Exception("任务标识错误[{0}]".format(self.bsm))
        self.task = tasks[0]

    def get_layer_extent(self, layer):
        desc = arcpy.Describe(layer)
        if desc and desc.extent:
            return desc.extent
        return None

    # 获取系统默认下载路径
    def get_download_dir(self):
        if platform.system() == "Windows":
            return os.path.join(os.path.expanduser("~"), "Downloads")
        elif platform.system() == "Darwin":
            return os.path.join(os.path.expanduser("~"), "Downloads")
        elif platform.system() == "Linux":
            return os.path.join(os.path.expanduser("~"), "Downloads")
        else:
            return None

    def run(self):
        aprx = arcpy.mp.ArcGISProject(self.mxd)
        layout_doc = aprx.listLayouts()[0]
        for elm in layout_doc.listElements("TEXT_ELEMENT"):
            if elm.name == "zbt":
                elm.text = self.task['ZBT']
            elif elm.name == "fbt":
                elm.text = self.task['FBT']
            elif elm.name == "bzsj":
                elm.text = '制作时间：{0}'.format(self.task['BZSJ'])
            elif elm.name == "ztdw":
                elm.text = '制作单位：{0}'.format(self.task['BZDW'])

        mapframe = layout_doc.listElements("MAPFRAME_ELEMENT")[0]
        temp = self.get_download_dir()
        temp_layer = temp + "/extent.shp"
        arcpy.Delete_management(temp_layer)
        if '.shp' in self.extent:
            where = '1 = 1'
            arcpy.analysis.Select(self.extent, temp_layer, where)
        else:
            where = 'xzqdm = \'{0}\''.format(self.extent)
            env.workspace = appconfig.SDE["KJGH"]
            arcpy.analysis.Select("KJGH.XZQMERGE", temp_layer, where)
        temp_layer_extent = self.get_layer_extent(temp_layer)
        layer = mapframe.map.addDataFromPath(temp_layer)
        if layer.isFeatureLayer:
            sym = layer.symbology
            sym.renderer.symbol.color = {"RGB": [0, 0, 0, 0]}
            sym.renderer.symbol.outlineColor = {"RGB": [255, 0, 0, 100]}
            sym.renderer.symbol.outlineWidth = 3.0
            layer.symbology = sym
        mapframe.camera.setExtent(temp_layer_extent)
        layout_doc.exportToJPEG(self.jpg, resolution=300)
        arcpy.Delete_management(temp_layer)
        print("####OK####")
