import pandas as pd
import numpy as np
import json
import json_tools
import time
from config.concat_sql import *

def date_treat(df, url, headers, method, codes):
    pd.set_option('display.max_columns', 1000)
    pd.set_option('display.width', 1000)
    pd.set_option('display.max_colwidth', 1000)

    # df=pd.DataFrame({'uuid':['12333','98766'],
    #                  'orderid':['hgufhu009','oiuuuy'],
    #                  'time':['2018-09-01','2019-09-09']
    #                 },
    #                 columns=['uuid','orderid','time'])
    #####数据处理调用

    method_ = {"Method": None}
    headers_ = {"headers": None}
    codes_={"codes":codes}

    headers_['headers']= headers
    method_['Method'] = method

    headers_.update(method_)

    name = int(time.strftime("%Y%m%d%H%M%S", time.localtime()))

    df_res = pd.DataFrame(columns=['caseID', '测试参数', '测试响应', '开发参数', '开发响应', '对比结果'])
    try:

        for i in range(0,len(df)):
            parm={}
            data_l = headers_
            data_={}
            for col in df.columns:
                if pd.isnull(df.loc[i, col]) == False:
                    data_.update({col:df.loc[i, col]})
                else:
                    pass
            else:
                data_.update(codes_)
                parm = {'data':data_,'url':'None'}

            data_l.update(parm)

            df_res.loc[i, 'caseID'] = i
            data_l['url']=url[0]
            df_res.loc[i, '测试参数'] = str(data_l)
            data_l['url'] =url[1]
            df_res.loc[i, '开发参数'] = str(data_l)
        else:
            report_name='report_'+str(name)+'.csv'
            path='static/report/'+report_name
            df_res.to_csv(path,index=False,header=True,encoding='gbk')
            return {'msg':'测试用例已生成，请下载report.csv文件，查看用例数据，确认无误后，点击运行','flag':1,'report_name':report_name}
    except Exception as e:
        print(str(e.args[1]))
        return {'msg':str(e.args[1]),'flag':0}

def file_date():

    df = pd.read_table(r"0725.txt")[1:5]
    df = df.reset_index(drop=True)
    print(df, "hahhhahah")
    # dropna使得滤除缺失数据更加得心应手。
    df = df.dropna(subset=['other_params'])
    df.fillna(False, inplace=True)

    df['business_type'] = df['business_type'].astype(int)
    df = df.loc[df.business_type == 0]

    def parse_json(x):
        feature = json.loads(x)
        return feature['codes']

    df['codes'] = pd.DataFrame(df['other_params'].apply(lambda x: parse_json(x)).tolist())
    del df['other_params']
    # print(df.to_clipboard())
    df = df.dropna(subset=["codes"])
    # time.sleep(199999)
    """进行数据解析从多个codes 解析完1个code"""
    # df = pd.read_csv(r"/Users/luzhaoyang/Desktop/测试.csv")[0:5]
    # print(df,"mingmingjiu")
    df["codes_list"] = df["codes"].apply(lambda x: len(str(x).split(',')))

    dict_df = []
    for index, row in df.iterrows():
        for k in (row.codes).split(','):
            # print(k)
            df_new = pd.DataFrame(row).T
            df_new["one_code"] = k
            dict_df.append(df_new)
    df = pd.concat(dict_df)
    print(df, 'nishuia ')
    df.fillna(False, inplace=True)
    df['business_type'] = df['business_type'].astype(int)
    df = df.loc[df.business_type == 0]


def sql_date(parm, database=None):

    error_s=''
    _sql = parm
    try:
        _df = pd.read_sql(_sql, con_tuomin_xyqb)
    except Exception as e:
        _df= pd.DataFrame()
        error_s= e.args[0]
        return _df, error_s
    return _df, error_s

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)
    df_res = pd.read_csv('./report.csv', encoding='gbk')

    # df=pd.DataFrame({'uuid':['12333','98766'],
    #                  'orderid':['hgufhu009','oiuuuy'],
    #                  'time':['2018-09-01','0000']
    #                 },
    #                 columns=['uuid','orderid','time'])

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

    # print(sum(data['calculate'].isnull()))