# -*- coding: utf-8 -*-
import os
import sys
import log
import arcpy
# import utils
import appconfig

# import arcpy
import arcpy.mp as mp
from db.postgresql import Postgresql

import importlib, sys

importlib.reload(sys)


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.task()

    def task(self):
        '''加载数据-任务'''
        sql = "select a.BSM as \"BSM\",a.XZQDM as \"XZQDM\",A.ZBT as \"ZBT\",A.FBT as \"FBT\",A.BZDW as \"BZDW\",A.BZSJ as \"BZSJ\",A.ZTSJ as \"ZTSJ\",A.ZTDW as \"ZTDW\",B.MBMC as \"MBMC\",B.MBWJ as \"MBWJ\" from onemap.T_YZT_ZTT a JOIN onemap.T_YZT_ZTTMB 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 run(self):
        mxd = mp.MapDocument(self.mxd)
        xzqdm = self.task['XZQDM']
        if xzqdm and xzqdm != '':
            df = mp.ListDataFrames(mxd)[0]
            # 市级行政区控制是否显示
            layersj = mp.ListLayers(mxd, '市级行政区', df)[0]
            layersj.visible = True
            if len(xzqdm) > 4:
                layersj.visible = False
            # 县级行政区获取范围
            layerxj = mp.ListLayers(mxd, '县级行政区', df)[0]
            query = "XZQDM like '{0}%'".format(str(xzqdm))
            layerxj.definitionQuery = query
            # 所有图层 必须都带有 SW_XZQH
            layers = mp.ListLayers(mxd)
            query1 = "SW_XZQH like '{0}%'".format(str(xzqdm))
            for layer in layers:
                if layer.name != '市级行政区' and layer.name != '县级行政区':
                    layer.definitionQuery = query1
            df.extent = layerxj.getExtent()

        for elm in mp.ListLayoutElements(mxd, "TEXT_ELEMENT"):
            if elm.name == "zbt":
                elm.text = self.task['ZBT']
            if elm.name == "fbt":
                elm.text = self.task['FBT']
            if elm.name == "bzdw":
                elm.text = self.task['BZDW']
            if elm.name == "bzrq":
                elm.text = self.task['BZSJ']
            if elm.name == "ztsj":
                elm.text = self.task['ZTSJ']
            if elm.name == "ztdw":
                elm.text = self.task['ZTDW']

        mp.ExportToJPEG(mxd, self.jpg, resolution=300)
        print("####OK####")
