#!/usr/bin/env python
# -*- coding:utf-8 -*-
from core.AnalysisReport import *
from controllers.nacos_py import *
import stat
import os
import logging
import tornado.web

import tornado.gen
import tornado.ioloop
import tornado.template
import tornado.httpserver
from tornado import iostream
import time
import threading
from tornado import web, gen, ioloop, template
from tornado.gen import coroutine, Future
from tornado.ioloop import IOLoop
from tornado.concurrent import run_on_executor
from concurrent.futures import ThreadPoolExecutor
from tornado.httpclient import AsyncHTTPClient
"""
    下载word版本批量报告
"""
class NpEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        else:
            return super(NpEncoder, self).default(obj)


class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, world")


class DownWordProgressMessageReturnReportHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("You created report file")

    def post(self, *args, **kwargs):
        # if self.reuqest.headers.get("Content-Type", "").startswith("application/json"):
        try:
            logging.error(self.request.body)
            receive_data=json.loads(self.request.body, encoding="utf-8")
            if isinstance(receive_data,str):
                receive_data=json.loads(receive_data)
            logging.error((type(receive_data), receive_data))

            print('接收到的json数据='+str(receive_data))
            PlatID = receive_data['PlatID']
            ProjID = ''                             #receive_data['ProjID']
            TempID = receive_data['TempID']
            NewFileName = str(receive_data['NewFileName']).strip()
            templateFileServerUrl = ""
            if receive_data.get('CasesCondition') is not None:
                CasesCondition = receive_data['CasesCondition']
            else:
                CasesCondition = None
            caseFilter = receive_data['caseFilter']
            fileGroup = receive_data['fileGroup']
            if receive_data.get('edition') is not None:
                edition = receive_data['edition']
            else:
                edition = ""
            if receive_data.get('TokenID') is not None:
                TokenID = receive_data['TokenID']
            else:
                TokenID = ""
            if receive_data.get('serverUrl') is not None:
                serverUrl = receive_data['serverUrl']
                mongodb_cfg, maxResponseCount,templateFileServerUrl = nacos_py(serverUrl)
            else:
                mongodb_cfg = "readInfo"
            if receive_data.get('updateFlag') is not None:
                updateFlag = receive_data.get('updateFlag')
            else:
                updateFlag = False

            filePathName = myReportMainJava(PlatID, ProjID, TempID, TokenID, mongodb_cfg, caseFilter, fileGroup,
                                            NewFileName, edition, updateFlag, templateFileServerUrl, CasesCondition)
            f = open(filePathName, 'rb')
            while True:
                b = f.read(8096)
                if not b:
                    break
                else:
                    self.write(b)
            self.flush()
            f.close()
            #os.remove(filePathName)
        except Exception as e:
            logging.error("%s"%str(e)+" "+str(self.request.remote_ip))
            resp=json.dumps({"code": "参数错误", "msg": str(e)})
            print(resp)
            self.write(resp)


class DownWordProgressMessageCancelReportHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("You created report file")

    def post(self, *args, **kwargs):
        # if self.reuqest.headers.get("Content-Type", "").startswith("application/json"):
        try:
            receive_data=json.loads(self.request.body, encoding="utf-8")
            if isinstance(receive_data,str):
                receive_data=json.loads(receive_data)
            print('接收到的json数据=' + str(receive_data))
            PlatID = receive_data['PlatID']
            ProjID = ''                             #receive_data['ProjID']
            TempID = receive_data['TempID']
            if str(os.path.abspath(os.curdir)).find("controllers") > 0:
                filePath = os.path.abspath(os.curdir).replace("controllers", "docx")
            else:
                filePath = os.path.join(os.path.abspath(os.curdir), "docx")
            reportPath = os.path.join(filePath, 'report')
            reportList = os.listdir(reportPath)
            for reportItem in reportList:
                f_path = os.path.join(reportPath, reportItem)
                if reportItem.find(TempID) > -1:
                    if os.path.isdir(f_path):
                        shutil.rmtree(f_path)
                    else:
                        os.remove(f_path)
            #os.remove(filePathName)
        except Exception as e:
            logging.error("%s"%str(e)+" "+str(self.request.remote_ip))
            resp=json.dumps({"code": "参数错误", "msg": str(e)})
            print(resp)
            self.write(resp)


class DownWordProgressMessageReportNameHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("You created report file")

    def post(self, *args, **kwargs):
        # if self.reuqest.headers.get("Content-Type", "").startswith("application/json"):
        try:
            receive_data=json.loads(self.request.body, encoding="utf-8")
            if isinstance(receive_data,str):
                receive_data=json.loads(receive_data)
            print('接收到的json数据=' + str(receive_data))
            PlatID = receive_data['PlatID']
            ProjID = ''                             #receive_data['ProjID']
            TempID = receive_data['TempID']
            if str(os.path.abspath(os.curdir)).find("controllers") > 0:
                filePath = os.path.abspath(os.curdir).replace("controllers", "docx")
            else:
                filePath = os.path.join(os.path.abspath(os.curdir), "docx")
            reportPath = os.path.join(filePath, 'report')
            print(reportPath)
            reportList = os.listdir(reportPath)
            reportName = '报告未生成'
            for reportItem in reportList:
                f_path = os.path.join(reportPath, reportItem)
                if reportItem.find(TempID) > -1 and os.path.isdir(f_path):
                    for f_pathItem in os.listdir(f_path):
                        if reportName == '报告未生成':
                            reportName = f_pathItem
                        else:
                            reportName += ';'
                            reportName += f_pathItem
            if reportName == '报告未生成':
                for reportItem in reportList:
                    if str(reportItem).find('.zip') > 0 and str(reportItem).find(TempID) > -1:
                        reportName = '报告已完成'
            self.write(reportName)
            self.finish()
            #os.remove(filePathName)
        except Exception as e:
            logging.error("%s"%str(e)+" "+str(self.request.remote_ip))
            resp=json.dumps({"code": "参数错误", "msg": str(e)})
            print(resp)
            self.write(resp)


class DownWordProgressMessageDownReportHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("You created report file")

    def post(self, *args, **kwargs):
        # if self.reuqest.headers.get("Content-Type", "").startswith("application/json"):
        try:
            receive_data=json.loads(self.request.body, encoding="utf-8")
            if isinstance(receive_data,str):
                receive_data=json.loads(receive_data)
            print('接收到的json数据=' + str(receive_data))
            PlatID = receive_data['PlatID']
            ProjID = ''                             #receive_data['ProjID']
            TempID = receive_data['TempID']
            if str(os.path.abspath(os.curdir)).find("controllers") > 0:
                filePath = os.path.abspath(os.curdir).replace("controllers", "docx")
            else:
                filePath = os.path.join(os.path.abspath(os.curdir), "docx")
            reportPath = os.path.join(filePath, 'report')
            reportList = os.listdir(reportPath)
            reportPath, reportTime = '', 0
            for reportItem in reportList:
                f_path = os.path.join(reportPath, reportItem)
                if os.path.isdir(f_path):
                    pass
                else:
                    if str(reportItem).find('.zip') > 0 and str(reportItem).find(TempID) > -1:
                        if int(str(reportItem)[24:44]) > reportTime:
                            reportPath = f_path
                            reportTime = int(str(reportItem)[24:44])
            f = open(reportPath, 'rb')
            while True:
                b = f.read(8096)
                if not b:
                    break
                else:
                    self.write(b)
            self.flush()
            f.close()
            os.remove(reportPath)
        except Exception as e:
            logging.error("%s"%str(e)+" "+str(self.request.remote_ip))
            resp=json.dumps({"code": "参数错误", "msg": str(e)})
            print(resp)
            self.write(resp)
