"""
@autor:Yue
@date::17:11
@file:exec.py
@project:autoInterface

"""
#from blueprints.testcases import t2,t1
import copy,datetime,os,json,sys,time,re


#import HTMLTestRunner,
from blueprints.BeautifulReport import BeautifulReport
aa=os.path.abspath(__file__)
sys.path.append(os.path.dirname(os.path.dirname(aa)))
#print(sys.path)
from blueprints.tools.rwKeyData import   rwKeyData
from blueprints.settings import config,qaConfig,qa2Config
from blueprints.tools.debugtalk import  fakeinfo
from blueprints.tools.dealDatabase import delDatabase
from blueprints.cases_mapping import project_mapping

def getinfo(section='baseinfo',k='environment'):
    rw=rwKeyData()#.readKeyData(section,k)# or 'qa'
    #print(env,config,config.get(env))
    if k=='environment':
        env=rw.readKeyData('baseinfo','environment')
        return config.get(env) or qaConfig
    return rw.readKeyData(section,k)


def runexec(config,scences,rf,description,clearflag=0):
    import unittest
    from blueprints.execcase import wcases, getcases, dealScene
    suit=unittest.TestSuite()
    bs=copy.deepcopy(scences)
    print('=='*10,scences)
    wcases(config, scences)
    getcases(config,suit, bs)
    #rf=deals.renameFile('txt')
    # with open(rf,"wb+") as f:
    #     runner = HTMLTestRunner.HTMLTestRunner(f,verbosity=2,description="测试报告")
    #     result=runner.run(suit)
    #     print("5========",runner.stopTime,runner.startTime)
    #     during=datetime.datetime.strptime(str(runner.stopTime)[:-3], '%Y-%m-%d %H:%M:%S.%f')-datetime.datetime.strptime(str(runner.startTime)[:-3], '%Y-%m-%d %H:%M:%S.%f')
    #     print("4===============>",during,during.microseconds)
    #     return result,during.seconds
    filename=rf.split(os.sep)[-1]
    filepath=rf.replace(filename,"")
    t=BeautifulReport(suit)

    #print("====",filename,filepath,rf)
    t.report(description=description,filename=filename,log_path=filepath)
    if clearflag:
        from blueprints.tools.deals import  clearUp
        clearUp('globalvar','cardno')
    return t.failure_count,t.success_count,t.begin_time,t.end_time


def getGlobalParam(config,k):
    ###k只能是usered，phone_no，environment
    rw=rwKeyData(config)
    param=rw.readKeyData('baseinfo',k)
    if k=='usered':
        if param=='qa':
            phone_no=sys.args[2]
        elif param=='jenkins':
            while True:
                phone_no = fakeinfo('phone')
                sql='select id from xyqb_user.user where phone_no='+phone_no
                existPhone=delDatabase(config,sql)
                #print("=====***"*20,existPhone,type(existPhone[0]),phone_no)
                if 0==existPhone[0]:
                    break
        else:
            phone_no = rw.readKeyData('baseinfo','phone_no')

        ####该行执行完成后，发现phone_no并没有写入到keydata文件中，故写phone放到main区中
        #rw.writeKeyData('baseinfo', 'phone_no',phone_no)
        #print("=====***"*20,rw.readKeyData('baseinfo', 'phone_no'),phone_no)
        return phone_no











if __name__ == '__main__':

    # ###合同测试用例
    #
    # casefile = [{'hetong': ['281.json', '282.json']}]
    otherfile = ['243.json', '244.json', '245.json', '246.json', '247.json', '248.json', \
                 '249.json', '250.json', '251.json', '252.json', '253.json', '254.json', \
                 '255.json', '256.json', '257.json', '258.json', '259.json', '260.json', \
                 '261.json', '262.json', '263.json', '264.json', '265.json', '266.json', \
                 '267.json', '268.json', '269.json', '270.json', '271.json', '272.json',
                 '283.json', '284.json', '299.json', '300.json', '301.json', '302.json', '319.json',
                 '320.json', '321.json', '322.json']
    #
    # totalfile = casefile[0].get("hetong") + otherfile
    # casefile[0]['hetong'] = totalfile

    ###资方测试用例

    # 分配资产计划
    cases_number = [358, 359, 360]

    # 登陆，完成授信和基本资料认证
    # cases_number = [323, 382, 383, 384, 385, 357, 361, 358, 359, 360]
    #cases_number = [323, 401, 400, 361]
    cases_number = [323, 382, 383, 384, 385, 361, 402, 403, 404, 405, 401]

    # 登陆，完成授信，提交审核
    # cases_number = [323, 382, 383, 384, 385, 357, 361, 358, 359, 360]
    # cases_number = [323, 357, 400, 361, 399]
    cases_number = [323, 399]

    # 登陆，提交审核，风控回调
    # cases_number=[323,399,358, 359, 360,362,365,366,367]
    # cases_number = [323, 357, 400, 361, 399, 367]
    cases_number = [367]

    ##登陆，绑卡，提现
    # cases_number=[323,368,371,372,374,375,376,377,378]
    # cases_number = [323, 357, 400, 361, 399, 367, 368, 371,372,374,375,376,378]
    cases_number = [323, 368, 371, 372, 374, 375, 376, 378]


    ##分配资产计划,登陆，完成基本资料认证,完成授信,提交审核，风控回调
    cases_number = [358, 359, 360,323, 382, 383, 384, 385,361, 402, 403, 404, 405, 401,399,407,367]

    ###提现
    cases_number = [323, 368, 371, 372, 374, 375, 376, 378]

    rw=rwKeyData()
    rw.deleteKeyData('circleData')
    ##当单订单时，则不做后续清理工作,修改测试报告描述
    description = 'zijin'
    description = 'account'

    productid=rw.readKeyData('baseinfo','productid')
    if description == '单订单' and productid == 1:
        clearflag = 0
    if description == '多订单' and productid == 4:
        clearflag = 1
    else:
        clearflag=0

    config=getinfo()



    ##根据name值，从cases_mapping文件找对应的key
    name='test'

    # name='passportapi'
    ###########################

    # name='account'
    ###############

    # name='sidecar'
    #'account' or 'configuration_center'or

    # 串流程


    # name='funding_plan'
    # name='case_fengkong'
    # name = 'case_fengkong_refuse'
    name='trade'
    # name = 'case_fangkuan'

    # ############


    projectname=project_mapping.get(name)
    casename=projectname.get('casename')
    testnumer=projectname.get('testnumer')
    platform=projectname.get('platform')
    reportpathname=projectname.get('reportname') or '其他'
    if not (projectname and casename and testnumer and platform ):
        raise  Exception('{} 不能为空，需要到【cases_mapping】中查看'.format(name))

    now=int(time.time())
    description=casename

    execjsonversion = eval(rw.readKeyData('channnel', 'execjsonversion'))
    execjsonversionpath =str(execjsonversion.get(casename,'allignore'))

    meta_cases_number=getinfo('testsuit',testnumer)
    rw.writeKeyData('testsuit','person_test_number',testnumer)

    from blueprints.tools.deals import  dealcasenumer
    casefile=dealcasenumer(meta_cases_number)

    tt=config.reportsfile+'/{platform}/{path}/'.format(platform=platform,path=os.path.join(reportpathname,execjsonversionpath))
    #tt = config.reportsfile + '/考拉/{path}/'.format(path=os.path.join(reportpathname, execjsonversionpath))
    #tt = config.reportsfile + '/KA/{path}/'.format(path=os.path.join(reportpathname, execjsonversionpath))

    f=tt+'{0}.html'.format(casename+str(now))

    if not os.path.exists(os.sep.join(f.split(os.sep)[0:-1])):
        os.makedirs(tt)

    name,firdir=f.split(os.sep)[-1],os.sep.join(f.split(os.sep)[0:-1])

    if not os.path.exists(firdir):
        os.makedirs(firdir)
        os.system('touch {0}'.format(f))
    t=runexec(config,casefile,f,description,clearflag)
    print("==================",t)
