import tornado
from tornado import httpclient
import time
import json
from tornado.options import define, options
from tornado.web import Application, RequestHandler
from functools import partial
import pandas as pd
import json_tools
import urllib.parse
import requests
import numpy as np
from Data.Data_page import Data_Page
import types

define("df_res", default="")  # 定义
df_res=pd.DataFrame()
define("report_name", default="")  # 定义


class table(RequestHandler):
    def get(self):
        global df_res
        global report_name


        # report_name ='report_20190904110614.csv'
        # path = 'static/report/' + report_name
        # df_res = pd.read_csv(path, encoding='gbk')


        train_data = np.array(df_res)  # np.ndarray()
        train_list = train_data.tolist()  # list

        try:
            # num1 = self.get_argument('option1')
            current_page_num = self.get_argument('page')



        except Exception as e:
            current_page_num = 1
        # print(num1)
        # current_page_num=1

        page_info = Data_Page(current_page_num, train_list, '/table')
        page_list = page_info.create_page()
        user_list = page_info.per_page_content(train_list)


        self.render('../templates/case_table.html',user_list=user_list, page_list=page_list,report_name=report_name)


class Send_parm(RequestHandler):

    def post(self):
        global df_res
        global report_name

        report_name = self.get_argument('report_name')

        path = 'static/report/' + report_name
        df_res = pd.read_csv(path, encoding='gbk')
        #
        if not df_res.empty:
            df_ = list(zip(df_res['测试参数'].to_list(), df_res['开发参数'].to_list()))
        for i in range(0, len(df_)):
            for j in range(0, 2):
                a = AsyncResponseHandler(res_l=df_[i][j], index=i, type_=j)
                func = partial(a.get, self)
                func()

        else:
            # global df_res
            df_res = pd.read_csv(path, encoding='gbk')
            # train_data = np.array(df_res)  # np.ndarray()
            # train_list = train_data.tolist()  # list
            #
            # current_page_num=1
            #
            # page_info = Data_Page(current_page_num, train_list, '/table')
            # page_list = page_info.create_page()
            # user_list = page_info.per_page_content(train_list)

            self.redirect('/table')
            # self.render('../templates/case_table.html', user_list=user_list, page_list=page_list,
            #             report_name=report_name)

            # self.render('../templates/case_table.html', df=train_list, report_name=report_name)



class AsyncResponseHandler(tornado.web.RequestHandler):

    def __init__(self,res_l=None, index=0, type_=None, *args, **kwargs):


        res_l=str(res_l).replace("'", '"')
        self.res_l = json.loads(res_l)
        self.index = index
        self.type_ = type_


    @tornado.web.asynchronous
    @tornado.gen.coroutine
    def get(self,*args, **kwargs):
        headers = self.res_l['headers']
        url =self.res_l['url']
        method = self.res_l['Method']

        body=urllib.parse.urlencode(self.res_l['data'])

        self.http_client = tornado.httpclient.AsyncHTTPClient()

        resp = yield tornado.gen.Task(
                    self.http_client.fetch,
                    url,
                    method=method,
                    headers=headers,
                    body=body,
                    validate_cert=False)

        body_ = resp.body
        code_ = resp.code

        self._finished = 1
        if body_  ==  None:
            body_ = "{'msg':'调用接口失败','code':404}"
        else:
            body_ = str(body_, 'utf-8')
            body_=body_.replace('"',"'")
            if code_ != 200:
                body_= "{'msg':'{0}','code':{1}}".format(body_, code_)

        global df_res


        if self.type_ == 0:
            df_res.loc[self.index, '测试响应'] = body_
            if pd.isnull(df_res.loc[self.index,'开发响应']) == False :
                json_cmp(self.index)

        elif self.type_ == 1:
            df_res.loc[self.index, '开发响应'] = body_
            if pd.isnull(df_res.loc[self.index,'测试响应']) == False:
                json_cmp(self.index)
        self._finished = 1


def dict_get(dicts, objkey, default):
    tmp = dicts
    for k, v in tmp.items():
        if k == objkey:
            return v
        else:
            if isinstance(v, dict):
                ret = dict_get(v, objkey, default)
                if ret is not default:
                    return ret
    return default


def json_cmp(index):

    pd.set_option('display.max_columns', 1000)
    pd.set_option('display.width', 1000)
    pd.set_option('display.max_colwidth', 1000)

    global df_res
    str_test = str(df_res.loc[index, '测试响应']).replace("'", '"')
    str_dev = str(df_res.loc[index, '开发响应']).replace("'", '"')

    test = json.loads(str_test)
    dev = json.loads(str_dev)

    test_codes=test['code']
    dev_codes=dev['code']

    if test_codes == 200  and   dev_codes ==200:
        test_v=dict_get(test,'value', None)
        dev_v=dict_get(dev,'value', None)

        if test_v != None and  dev_v!=None:
            if test_v ==  dev_v:
                df_res.loc[index, '对比结果'] = 'Y'
            else:
                df_res.loc[index, '对比结果'] = '测试：{0}，开发：{1}'.format(test_v,dev_v)

        else:
            df_res.loc[index, '对比结果'] = '测试：{0}，开发：{1}'.format(test_v,dev_v)

    else:
        df_res.loc[index, '对比结果'] = '调用接口失败'

    if sum(df_res['对比结果'].isnull()) <= 0:

        global report_name
        path = 'static/report/' + report_name

        df_res.to_csv(path, index=False, header=True, encoding='gbk')
        print('end')

    else:
        pass


if __name__ == "__main__":
    import numpy as np
    import pandas as pd

    pd.set_option('display.max_columns', 1000)
    pd.set_option('display.width', 1000)
    pd.set_option('display.max_colwidth', 1000)

