# -*- coding: utf-8 -*-
import os
import sys
import json
import log
import appconfig
import arcpy
import utils
from arcpy import env
from db.postgresql import Postgresql

import importlib, sys

importlib.reload(sys)


class Ctfx:
    def __init__(self, data):
        self.bsm = data
        self.db = Postgresql(appconfig.DB_CONN)
        self.outputname = "CTFX" + data
        log.info(data)
        # 根据BSM获取任务信息
        self.task()
        # 临时工作空间
        self.root = os.path.dirname(os.path.abspath(__file__))
        path = os.path.join(self.root, "out")
        if not os.path.exists(path):
            os.makedirs(path)
        # 创建输出GDB，如果已存在则删除后新建
        self.outGdb = os.path.join(path, "{0}.gdb".format(data))
        arcpy.Delete_management(self.outGdb)
        arcpy.CreateFileGDB_management(path, "{0}.gdb".format(data))
        # 输出文件夹里面已经有内容的，就覆盖掉
        env.overwriteOutput = True
        # 设置工作空间
        env.workspace = appconfig.SDE["KJGH"]

    def task(self):
        # 根据BSM获取任务信息
        sql = f'select t.sjy "SJY",t.xzqdm "XZQDM",t.fxyz "FXYZ",t.rwzt "RWZT",t.fxtable "FXTABLE",t.fxyear "FXYEAR",yz.cxtj as "CXTJ",yz.name "YZNAME",sjy.name "SJYNAME" from onemap.t_fxpj_ctfx_main t left join onemap.t_fxpj_ctfx_yz yz on yz.id = t.fxyz ' \
              f'left join onemap.t_fxpj_ctfx_sjy sjy on sjy.tablename = t.sjy where t.id = \'{self.bsm}\''
        tasks = self.db.query(sql)
        if len(tasks) == 0:
            raise Exception("任务标识错误[{0}]".format(self.bsm))
        self.task = tasks[0]
        # 查询条件（SQL语句，二调三调用英文分号隔开，二调在前三调在后，以当前分析年份与2019年作比较）
        self.task["CXTJ"] = str(self.task["CXTJ"])
        if self.task["CXTJ"].find(";") > -1:
            if int(self.task["FXYEAR"]) > 2018:
                self.task["CXTJ"] = self.task["CXTJ"].split(";")[1]
            else:
                self.task["CXTJ"] = self.task["CXTJ"].split(";")[0]

    def run(self):
        try:
            # 记录任务开始时间
            self.rwkssj = utils.getNowTimeStr("%Y-%m-%d %H:%M:%S")
            # self.updateFxzt(self.bsm, "1", "")
            mjField = "TBMJ"
            # 1.根据查询条件获取分析数据源
            sjy = r"{0}\SJY".format(self.outGdb)
            if self.task["CXTJ"] != None and self.task["CXTJ"] != "":
                arcpy.Select_analysis(self.task["FXTABLE"], sjy, self.task["CXTJ"])
            else:
                arcpy.Select_analysis(self.task["FXTABLE"], sjy)
            arcpy.AddField_management(sjy, mjField, "DOUBLE")
            arcpy.CalculateField_management(sjy, mjField, "!shape.area@SQUAREMETERS!", "PYTHON_9.3")
            # 计算分析数据源总面积
            fxTotal = 0
            with arcpy.da.SearchCursor(sjy, ['TBMJ']) as cursor:
                for row in cursor:
                    fxTotal = fxTotal + row[0]
            self.fxTotal = fxTotal
            log.info(self.bsm + "根据查询条件获取分析数据源完成")

            # 2.裁剪数据源
            env.workspace = appconfig.getSDE("SDE")
            fxjg = r"{0}\{1}".format(self.outGdb, self.outputname)
            arcpy.Clip_analysis(sjy, self.task["SJY"], fxjg, 0)
            log.info(self.bsm + "裁剪分析数据源完成")

            # 3.计算面积
            log.info("面积")
            arcpy.AddField_management(fxjg, mjField, "DOUBLE")
            arcpy.CalculateField_management(fxjg, mjField, "!shape.area@SQUAREMETERS!", "PYTHON_9.3")
            # 计算分析结果总面积
            jgTotal = 0
            with arcpy.da.SearchCursor(fxjg, ['TBMJ']) as cursor:
                for row in cursor:
                    jgTotal = jgTotal + row[0]
            self.jgTotal = jgTotal
            # 4. 添加统计字段
            subXzqLeng = self.getSubXzqLength()
            staticsField = "STATICS"
            arcpy.AddField_management(fxjg, staticsField, "TEXT")
            arcpy.CalculateField_management(fxjg, staticsField, "!ZLDWDM![0:" + str(subXzqLeng) + "]", "PYTHON_9.3")
            # 5.根据行政区划统计信息
            xzqstatist = r"{0}\XZQSTCTIST".format(self.outGdb)
            arcpy.Statistics_analysis(fxjg, xzqstatist, [[mjField, "SUM"]], staticsField)
            # 遍历GDB统计表
            statistobj = {}
            with arcpy.da.SearchCursor(xzqstatist, [staticsField, "SUM_" + mjField]) as cursor:
                for row in cursor:
                    statistobj[row[0]] = row[1]
            log.info(json.dumps(statistobj))
            # 结果数据拷贝到sde数据库
            # sde = appconfig.SDE["SDE"]
            # env.workspace = sde
            # sdeTableName = "SDE." + self.outputname
            # try:
            #     arcpy.Delete_management(sdeTableName)
            # except arcpy.ExecuteError:
            #     log.error(arcpy.GetMessages())
            # except:
            #     msg = str(sys.exc_info()).decode('string-escape')
            #     log.error(msg)
            # arcpy.Copy_management(fxjg, sdeTableName)
            # 记录任务开始时间
            self.rwjssj = utils.getNowTimeStr("%Y-%m-%d %H:%M:%S")
            # 组装分析结果
            self.updateFxztAndStatist(self.bsm, "2", self.createFxjg(), json.dumps(statistobj))
            log.info("####OK####")
            print("####OK####")
        except arcpy.ExecuteError:
            print("####ERROR####" + arcpy.GetMessages())
            log.error(arcpy.GetMessages())
            self.updateFxzt(self.bsm, "3", arcpy.GetMessages())
        except:
            msg = str(sys.exc_info()).decode('string-escape')
            print("####ERROR####" + msg)
            log.error(msg)
            self.updateFxzt(self.bsm, "3", msg)

    # 获取行政区下属级别代码长度
    def getSubXzqLength(self):
        curlength = len(self.task["XZQDM"])
        if curlength == 4:
            curlength = 6
        elif curlength == 6:
            curlength = 9
        elif curlength == 9:
            curlength = 12
        return curlength

    # 组装分析结果
    def createFxjg(self):
        # fxjgstr = self.task["SJYNAME"] + "内约有" + self.task["YZNAME"] + self.areaTransform(self.jgTotal) + "，占分析范围内" + self.task["YZNAME"] + "总面积的" + self.proportion()
        fxjgstr = "{0}内约有{1}{2}，占分析范围内{1}总面积的{3}。"
        fxjgstr = fxjgstr.format(self.task["SJYNAME"], self.task["YZNAME"], self.areaTransform(
            self.jgTotal), self.proportion())
        return fxjgstr

    # 面积转换 平方米转万亩
    def areaTransform(self, area):
        res = area * 0.0015 / 10000
        return "" + "%.2f" % res + "万亩"

    # 面积转换 平方米转万亩
    def proportion(self):
        res = (self.jgTotal / self.fxTotal) * 100
        return "" + "%.2f" % res + "%"

    # 更新冲突分析任务状态
    def updateFxzt(self, bsm, fxzt, msg):
        # 记录任务结束时间
        self.rwjssj = utils.getNowTimeStr("%Y-%m-%d %H:%M:%S")
        sql = "update onemap.t_fxpj_ctfx_main t set rwzt = '{0}',rwkssj = to_date('{1}','yyyy-mm-dd hh24:mi:ss') , rwjssj = to_date('{2}','yyyy-mm-dd hh24:mi:ss') ,fxjg = '{3}',fxjgtable = '{4}',workspace = '{5}' where t.id = '{6}'"
        sql = sql.format(
            fxzt
            , self.rwkssj
            , self.rwjssj
            , msg
            , self.outputname
            , self.outGdb
            , bsm)
        self.db.insert(sql)

    # 更新冲突分析任务状态
    def updateFxztAndStatist(self, bsm, fxzt, msg, statist):
        # 记录任务结束时间
        self.rwjssj = utils.getNowTimeStr("%Y-%m-%d %H:%M:%S")
        sql = "update onemap.t_fxpj_ctfx_main t set rwzt = '{0}',rwkssj = to_date('{1}','yyyy-mm-dd hh24:mi:ss') , rwjssj = to_date('{2}','yyyy-mm-dd hh24:mi:ss') ,fxjg = '{3}',fxjgtable = '{4}',workspace = '{5}', statist = '{7}' where t.id = '{6}'"
        sql = sql.format(
            fxzt
            , self.rwkssj
            , self.rwjssj
            , msg
            , self.outputname
            , self.outGdb
            , bsm
            , statist)
        self.db.insert(sql)
