# -*- coding: utf-8 -*-
import os
import arcpy
import uuid
import arcpy


class FzxzMap:
    def __init__(self):
        self.root = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "../mxds/fzxz"))
        self.aprx = os.path.join(self.root, r"FzxzMap.aprx")
        self.shp = os.path.join(self.root, r"fzxz.shp")

    # 获取图层的范围
    def get_layer_extent(self, layer):
        desc = arcpy.Describe(layer)
        if desc and desc.extent:
            return desc.extent
        return None

    def run(self):
        aprx = arcpy.mp.ArcGISProject(self.aprx)
        map_doc = aprx.listMaps()[0]
        layF = map_doc.listLayers('fzxzF')[0]
        layM = map_doc.listLayers('fzxzM')[0]
        jpgPath = ""

        cursor = arcpy.da.SearchCursor(self.shp, ['BSM', 'RWBSM'])
        for row in cursor:
            bsm = row[0]
            rwbsm = row[1]
            if jpgPath == "":
                jpgPath = os.path.join(self.root, "jpgs", str(rwbsm))
                if not os.path.exists(jpgPath):
                    os.makedirs(jpgPath)

            where = "BSM='{}'".format(str(bsm))
            # print(where)
            if layF.supports('DefinitionQuery'):
                dql = layF.listDefinitionQueries()
                # dql = []
                for dq in dql:
                    dq['isActive'] = False
                dql.append({'name': bsm, 'sql': where, 'isActive': True})
                layF.updateDefinitionQueries(dql)
            # aprx.save()
            # 全局
            fileF = os.path.join(jpgPath, '{0}_F.jpg'.format(bsm))
            if not os.path.exists(fileF):
                if layF:
                    local_extent = self.get_layer_extent(layF)
                    # print(local_extent)
                    map_doc.defaultCamera.setExtent(local_extent)
                # aprx.save()
                map_doc.defaultView.exportToJPEG(fileF, width=400, height=240, resolution=300)
            print(fileF.replace("Z:", "").replace("\\", "/"))
            # 局部
            fileM = os.path.join(jpgPath, '{0}_M.jpg'.format(bsm))
            if not os.path.exists(fileM):
                if layM:
                    temp_layer = r"in_memory\selected_layer" + bsm
                    arcpy.analysis.Select(layF, temp_layer, where)
                    # 获取临时选择图层的范围
                    temp_layer_extent = self.get_layer_extent(temp_layer)
                    map_doc.defaultCamera.setExtent(temp_layer_extent)
                # aprx.save()
                map_doc.defaultView.exportToJPEG(fileM, width=400, height=240, resolution=300)
            print(fileM.replace("Z:", "").replace("\\", "/"))

# map = FzxzMap()
# map.run()
