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

"""
#from blueprints.testcases import t2,t1
import copy,datetime,os,json,sys,time
aa=os.path.abspath(__file__)
sys.path.append(os.path.dirname(os.path.dirname(aa)))

#import HTMLTestRunner,

try:
    from blueprints.BeautifulReport import BeautifulReport
except Exception as e:

    from BeautifulReport import BeautifulReport


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


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)
    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,usered):
    ###k只能是usered，phone_no，environment
    rw=rwKeyData(config)
    param=usered#sys.argv[2] #rw.readKeyData('baseinfo',k)
    fid = rw.readKeyData('channnel', 'fundcorpid')
    if param:
        if param!='jenkins' :
            phone_no=sys.argv[3]
        else:
            while True:
                phone_no = fakeinfo('phone')

                while True:
                    if fid in ['770'] :
                        if phone_no[-1] in ['0','3','6','9']:
                            phone_no = phone_no
                            break
                        else:
                            phone_no = fakeinfo('phone')
                    else:
                        break


                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, 357, 400, 361, 399, 367, 368, 371, 372, 374, 375, 376, 378,

                    363, 364, 369, 358,370, 373, 386,387, 388,389,
                    390,391, 392, 389, 390, 393, 394, 395, 396, 397]


    ##分配资产计划,登陆，完成基本资料认证,完成授信,提交审核，风控回调
    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()
    ##删除circleData后，文件仍然存在
    rw.deleteKeyData('circleData')
    ##通过keydata获取运行环境
    env=sys.argv[1]
    config=config.get(env) or qaConfig
    rw.writeKeyData('baseinfo','environment',env)

    ##手工传使用者
    usered=sys.argv[2]
    phone_no=getGlobalParam(config,usered)

    rw.writeKeyData('baseinfo', 'phone_no', phone_no)
    print(phone_no,"=====++"*20)
    #
    # 1/0
    ##产品id全局，因为多订单和单订单要分开出报告
    productid=sys.argv[5] or 1
    fundcorpid=sys.argv[7] or 480
    rw.writeKeyData('channnel', 'fundcorpid', fundcorpid)
    rw.writeKeyData('baseinfo','productid',productid)

    ##当单订单时，则不做后续清理工作,修改测试报告描述
    description=sys.argv[6]
    clearflag=0
    relativepath = '主流程/'
    if description=='SingleOrder' and productid==1:
        clearflag=0
    if description=='MoreOrder' and productid==4:
        clearflag=1


    ##通过keydata获取运行场景
    testnumer=sys.argv[4] or 'cases_number1'
    meta_cases_number=getinfo('testsuit',testnumer)
    rw.writeKeyData('testsuit','person_test_number',testnumer)
    cases_number=json.loads(meta_cases_number)

    t = '.json,'.join([str(i) for i in cases_number]) + ".json"
    casefile = [{'passportapi': t.split(',')}]

    reportname=time.strftime("%Y%m%d%H%M%S")+'.html'
    print(reportname)

    if description=='SingleOrder':
        relativepath='主流程/'
    elif description=='MoreOrder':
        relativepath='多订单/'
    elif description=='hetong':
        relativepath='合同/'
    else:
        relativepath='其他类型/'

    f=config.reportsfile+'/测试yue/'+relativepath+reportname



    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)
