"""
@autor:Yue
@date::14:23
@file:deals.py
@project:autoInterface

"""
from  datetime import datetime
import time,os,pickle,jsonpath,re,sys
from blueprints.tools.dealDatabase import dealParamSql
from blueprints.tools.rwKeyData import rwKeyData
from blueprints.tools.dealDatabase import delDatabase
from blueprints.tools import debugtalk
from blueprints.settings import *
import requests,json,base64,hashlib,redis
def renameFile(houzui):
    rename=datetime.now()
    t = int(time.mktime(time.strptime(str(rename), "%Y-%m-%d %H:%M:%S.%f")))
    #tt,houzui=os.path.splitext(filename)
    #print(tt,houzui)
    return str(t)+"."+houzui

def separate_deallsql(sql, section='globalvar', k="logindata"):
    #将手机号存储在KeyData配置文件中，功能类似数据库的表
    colum = "username"
    recolum = "username"
    keydata=rwKeyData()
    revalue = keydata.readKeyData(section,k)


    revalue = keydata.readKeyData(section, k)
    #print("re=====",section,k,revalue)

    sql=dealParamSql(sql,colum,recolum,revalue)

    colum = 'phone_no'
    recolum = 'phone'
    revalue=keydata.readKeyData(section,k)

    sql = dealParamSql(sql, colum, recolum, revalue)

    colum = 'phone_no'
    recolum = 'logindata'
    revalue = keydata.readKeyData(section, k)
    sql = dealParamSql(sql, colum, recolum, revalue)

    return sql


def clearUp(section,k=None,end=None):
    rw=rwKeyData()
    options=rw.getOptions()
    if k:
        rw.deleteKeyData(section,k)

def dealcasenumer(case_number):
    final_case=[]
    case_number=json.loads(case_number.replace("'",'"'))
    #print(case_number)
    for i in case_number:
        #temp=json.loads(case_number[i])

        for k,v in i.items():
            t = '.json,'.join([str(i) for i in v]) + ".json"
            casefile = {'{0}'.format(k): t.split(',')}
            final_case.append(casefile)
    return final_case

def getenv():
    rw=rwKeyData()
    return rw.readKeyData('baseinfo','environment')

def getenvconfig():
    env=getenv()
    if config.get(env):
        return  config.get(env)
    else:
        raise Exception('未获取到全局配置')



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='13683241439'
        else:
            while True:
                phone_no = debugtalk.fakeinfo('phone')
                #print('随机生成的手机号：',phone_no)
                while True:
                    if fid in ['770'] :
                        if phone_no[-1] in ['0','3','6','9']:
                            phone_no = phone_no
                            break
                        else:
                            phone_no = debugtalk.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


def dealSign(casejson):
    security_code='security_code=6jby7jiy4tv3scaj8pw6sgyxips05afe'
    body=casejson.get('body')

    if body and isinstance(body,dict):
        if body.get('sign'):
            body=dict(sorted(body.items()))

            if len(str(body.get('sign')))>=0:
                temp=''
                for k,v in body.items():
                    if not k=='sign':
                        t=k+"="+str(v)+"&"
                        temp+=t
                temp=temp+security_code
                #print('temp=====', temp)
                casejson['body']['sign']=hashlib.md5(temp.encode()).hexdigest()
    #print(casejson)
    return casejson

def conn_redis():
    redis_url='opapi-redis1.quantgroups.com'
    redis_port=26379

    c=redis.Redis(redis_url,redis_port,db=0)
    t=c.pipeline()
    #print(t)
    #print(c.info())
    #print(t.keys('a*')[0])
    print([i for i in t.keys('job*')])





def aaa():
    a="{\'userId\': \'%s\', \'payOrderNo\': \'%s\', \'payStatus\': \'%s\', " \
      "\'businessFlowNo\': \'%s\', \'thirdPayOrderNo\': \'%s\', \'payMethod\': \'%s\'," \
      " \'payPlatform\': \'%s\', \'payAmount\': \'%s\', \'extData\': \'%s\', \'applyAt\': \'%s\', " \
      "\'completedAt\': \'%s\', \'canceledAt\': \'%s\', \'remark\': \'%s\', " \
      "\'loanApplicationHistoryId\': \'%s\', \'termNo\': \'%s\', \'repayType\': \'%s\'," \
      " \'actualRepayment\': \'%s\', \'overdueDays\': \'%s\', \'repaymentStatus\': \'%s\', " \
      "\'isHandle\': \'%s\', \'principal\': \'%s\', \'interest\': \'%s\', \'premium\': \'%s\', \'discount\': \'%s\', \'actualDiscount\': \'%s\', \'overdueServiceFee\': \'%s\', \'overdueInterest\': \'%s\', \'collectionRelief\': \'%s\', \'coupon\': \'%s\', \'actualCoupon\': \'%s\', \'actualCollectionRelief\': \'%s\', \'couponBusinessId\': \'%s\', \'actualOverdueServiceFee\': \'%s\', " \
      "\'actualServiceFee\': \'%s\', \'actualOverdueInterest\': \'%s\', \'actualInterest\': \'%s\'}"

    temp=jsonpath.jsonpath(json.loads(a),'$..properties')[0]
    ttemp={}

    for i in temp:
        ttemp.update(**{i:"%s"})
    print(ttemp.__str__())
    # t=a.replace("\\'","'")
    # print(t)







if __name__ == '__main__':

    # t=renameFile("aaa.py")
    # #t=os.path.getsize("cookie.txt")
    # rename=datetime.now()
    # print(rename,type(rename))
    # print(time.strptime(str(rename), "%Y-%m-%d %H:%M:%S.%f"))
    #t=test1()
    #print(t)

    tt=[]
    t='/Users/dm/Desktop/python_script/autoInterface/testCase/payment'

    for i in os.listdir(t):

        # ttt = os.system("grep -v 'qt_token' {0}".format(t + os.sep + i))
        # print(ttt, i)
        # if ttt==0:
            tt.append(int(i.replace('.json', '')))
        #print(ttt,i)
    print(sorted(tt),len(tt))
    b=['a','b','c','a']
    a={}
    for i in b:
        if a.get(i):
            print(b,a.get(i))
            a[i]+= + 1
            #a.setdefault(i, a.get(i) + 1)
        else:
            a.setdefault(i, 1)
    print(a)
    # a=[{'principal':'10000','interest':'0.23','termNo':6,'premium':'100','serviceFee':'50','deadline':'2021-01-01'}]
    #
    # t=dealSign({'a':1})
    #
    # # t=aaa()
    # # # t=getGlobalParam(test1Config,'jenkins')
    # print(t)

    #t=dealcasenumer("[{'a':[1,2,3]},{'b':[11,22]}]")
    #t=conn_redis()
    #print(t)


    t="applyNumber:AN000000142468362325409792," \
      "bankCode:PINGAN," \
      "bankCardNumber:6222986928006526," \
      "userId:71," \
      "reservePhoneNumber:13700001114"

    temp={}
    for i in t.split(','):
        print(i)
        temp.update(**{i.split(":")[0]:i.split(":")[-1]})
    print(temp)














