#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import sys
import log
import utils
import json
import arcpy
from zbmx.zbmx import ModelBuider
# from fzjbnt.fzjbnt import FzJbnt
from fzxz.fzxz import Fzxz
from fzxz.fzxzmap import FzxzMap
from hgxfx.hgxfx import Hgxfx
from ztt.ztt import Ztt
from ctfx.ctfx import Ctfx
from clipFeature.clipFeature import ClipFeature
from xmydsyx.xmydsyx import Xmydsyx

import importlib, sys

importlib.reload(sys)


def run(fun, data):
    try:
        switch = {
            'ModelBuider': modelBuider,
            'Fzxz': fzXzfx,
            'FzxzMap': fzxzMap,
            # 'FzJbnt': fzJbnt,
            'Hgxfx': hgxfx,
            'Ztt': ztt,
            'Ctfx': ctfx,
            'Xmydsyx': xmydsyx,
            'ClipFeature': clipFeature,
        }
        switch.get(fun, default())(data)
    except arcpy.ExecuteError:
        print("####ERROR####" + arcpy.GetMessages())
        log.error(arcpy.GetMessages())
    except:
        msg = str(sys.exc_info()).decode('string-escape')
        print("####ERROR####" + msg)
        log.error(msg)


# 默认情况下执行的函数
def default():
    print('No such case')


# 模型构建
def modelBuider(data):
    # root = os.path.dirname(os.path.abspath(__file__))
    # jsonData = os.path.join(root,"zbmx/data.json")
    # with open(jsonData, 'r')as fp:
    #    data = json.load(fp)
    mp = ModelBuider(data)
    mp.run()


# 辅助选址
def fzXzfx(data):
    mp = Fzxz(data["bsm"])
    mp.run()


# 辅助选址出图
def fzxzMap(data):
    mp = FzxzMap()
    mp.run()


# 合规性分析
def hgxfx(data):
    mp = Hgxfx(data["bsm"])
    mp.run()


# 冲突分析
def ctfx(data):
    mp = Ctfx(data["bsm"])
    mp.run()


# 数据裁剪
def clipFeature(data):
    mp = ClipFeature()
    mp.run()


# 项目用地适宜性分析
def xmydsyx(data):
    mp = Xmydsyx(data["bsm"])
    mp.run()


# 专题图
def ztt(data):
    mp = Ztt(data)
    mp.run()


# 辅助基本农田划定
# def fzJbnt(data):
#     root = os.path.dirname(os.path.abspath(__file__))
#     jsonData = os.path.join(root, "fzjbnt/data.json")
#     with open(jsonData, 'r') as fp:
#         data = json.load(fp)
#
#     mp = FzJbnt(data)
#     mp.run()


if __name__ == "__main__":
    try:
        log.info("---------------------------------------------------------")
        fun = sys.argv[1]
        log.info(fun)
        if len(sys.argv) == 3:
            jsonData = utils.b64Decode(sys.argv[2])
            log.info(jsonData)
            print(jsonData)
            run(fun, json.loads(jsonData))
        elif len(sys.argv) == 2:
            run(fun, None)
    except arcpy.ExecuteError:
        print("####ERROR####" + arcpy.GetMessages())
        log.error(arcpy.GetMessages())
    except:
        msg = str(sys.exc_info()).decode('string-escape')
        print("####ERROR####" + msg)
        log.error(msg)
