"""
@autor:Yue
@date::09:36
@file:debugtalk.py
@project:autoInterface

"""
import  faker,datetime,time,random,requests
import base64,json,numpy_financial,jsonpath
from decimal import Decimal
from math import  fabs
from urllib.parse import  urlencode
from blueprints.tools import rwKeyData
from blueprints.tools import dealDatabase
from itertools import product
from blueprints.tools import deals
import urllib3
urllib3.disable_warnings()
def fakeinfo(k,flag=1):
    rw = rwKeyData.rwKeyData()
    f=faker.Faker(locale='zh_CN')
    if k=='username':
        return f.name()
    if k=='text':
        return ''.join(f.sentences())
    if k=='address':
        return f.street_name()+f.street_address()
    if k=='email':
        return f.email()
    if k=='phone':
        return f.phone_number()
    if k=='idno':
        while True:
            idno = f.ssn()
            #print("++++")
            fid=rw.readKeyData('channnel','fundcorpid')
            if fid in ['910']:
                year = idno[6:10]
                nowyear=datetime.datetime.today().year
                if nowyear-int(year)>=23 and nowyear-int(year)<=55:
                    return idno
            else:
                return idno
    if k=='ip':
        return f.ipv4()
    if k=='random':
        return ''.join(random.sample('zyxwvutsrqponmlkjihgfedcbaABCDEFJHIGKLMNOPQRSTUVWSYZ1234567890',8))

    if k.lower()=='cardNo'.lower():#or k.lower()=='cardNoProvider'.lower():
        while True:
            if rw.readKeyData('globalvar','cardno') and flag:
                return rw.readKeyData('globalvar','cardno')
            t=rw.readKeyData('baseinfo', 'bancode')
            #print(t,type(t))
            bc=json.loads(t.replace("'",'"'))
            k=[]
            for b in bc.keys():
                k.append(b)
            bankcode=random.choice(k)
            c=bc.get(bankcode)+f.credit_card_number()
            #print(c)
            if len(c)>=20:
                rw.writeKeyData('globalvar','cardNo'.lower(),c[0:19])
                rw.writeKeyData('globalvar', 'cardNoProvider'.lower(), bankcode)
                return c[0:19]


def xiaoshudian(m,n=2):
    tt = ''.join([str(0) for i in range(n)])
    f = Decimal('0.{tt}'.format(tt=tt))
    return fabs(Decimal(m).quantize(f))

def getBankInfo(k):
    rw=rwKeyData.rwKeyData()
    if k=='cardNo':
        if rw.readKeyData('globalvar', 'cardno'):
            return rw.readKeyData('globalvar', 'cardno')

        return fakeinfo('cardNo')

    if k=='cardNoProvider':
        return rw.readKeyData('globalvar', 'cardNoProvider'.lower())

def getPhoneNo():
    phone=rwKeyData.rwKeyData().readKeyData('globalvar', 'logindata')
    return phone.split('=')[-1]

def term_jisuan(funid,funids,term,termlist):
    #print(funid,funids)
    if str(funid) in funids:
        if term in termlist:
            return 1
        else:
            raise Exception('资方[{funid}]的期数不能是{term},只能是[12]中之一'.format(funid=funid, term=term))
    #raise Exception('无效的funid[{}]'.format(funid))

def judgeidValid(result):

    #print("========*****",result)
    idValidDate=jsonpath.jsonpath(result,'$..idValidDate')
    nowdate = gettime(0, format=1)
    flag=0
    if idValidDate:
        starttime,endtime=idValidDate[0].split('-')

        flag=0 if starttime<=nowdate and endtime>=nowdate else 1

        if flag==1:
            flag=2 if not endtime or not starttime else 1

        return flag









def getCircle(*args,**kwargs):
    #print("list====",args)
    #print("ict=====",kwargs)
    dikaerji_list = []
    if kwargs:
        for k,v in kwargs.items():
            print('==', k,len(k), v, k == 'rigth')
            if k == 'rigth' or k=='right':
                if isinstance(v,list):
                    dikaerji_list=v#
                else:
                    raise Exception('{v}不符合规则，格式:[(k1,k2...),(k3,k4...)....]'.format(v={k:v}))

    else:
        t=product(*args)

        for i in product(*args):
            dikaerji_list.append(i)
    if len(dikaerji_list)>0:
        rwKeyData.rwKeyData().writeKeyData('circleData','circleData',dikaerji_list)
        rwKeyData.rwKeyData().writeKeyData('circleData', 'circleflag', len(dikaerji_list)-1)
        rwKeyData.rwKeyData().writeKeyData('circleData', 'circleparam', len(args))
        return dikaerji_list
    else:
        raise Exception('getCircle 执行出错:')



def fundCorpProduct_term(sql):
    from blueprints.tools.deals import getenvconfig
    config=deals.getenvconfig()
    return dealDatabase.delDatabase(config,sql)
    #return dealDatabase(config,sql)


def momeyRate(funid,term,momeey,n=2):
    '''

    :param funid: 资方id
    :param term: 分期
    :param momeey: 贷款额度
    :param n: 小数点保留位数
    :return: 每期还款额
    '''
    if n==2:
        f=Decimal('0.00')
    else:
        tt=''.join([str(0) for i in range(n)])
        f=Decimal('0.{tt}'.format(tt=tt))

    ##广达4+融担公司合作
    #if str(funid)=='790' or str(funid)=='710':
    if term_jisuan(funid,['790'],term,[6,9,12]):
        shijieveryone=numpy_financial.pmt(0.36/12,term,momeey,0)
        yuji=momeey/term+0.03*momeey
        ##融担应得
        rongdan=xiaoshudian(yuji,n)-xiaoshudian(shijieveryone,n)
        #print(yuji)
        return xiaoshudian(shijieveryone,n),xiaoshudian(rongdan,n)

    ###广达480资方利率改造
    elif str(funid)=='480':
        if term==2:
            rate=2.2610*0.01
        elif term==3:
            rate=2.0197*0.01
        elif term==6:
            rate=1.7930*0.01
        elif term==9:
            rate=1.7322*0.01
        elif term==12:
            rate=1.7128*0.01
        else:
            raise Exception('资方[{funid}]的期数不能是{term},只能是[2,3,6,9,12]中之一'.format(funid=funid,term=term))
        return xiaoshudian(momeey*rate+momeey/term,n)#Decimal().quantize(f)

    ##同业资方800，同业分期820
    elif term_jisuan(funid,['800','820'],term,[6]):
        everyone=xiaoshudian(momeey*0.14/12,n)
        return everyone

    elif term_jisuan(funid,['930','10001'],term,[3,6,9,12]):
        everyone=numpy_financial.pmt(0.36/12,term,momeey,0)
        return everyone

    elif term_jisuan(funid,['900','710'],term,[3,6,9,12]):
        everyone=xiaoshudian(momeey/term+momeey*0.09/term,n)
        return everyone

    ##广达 + 巧盼（960）
    elif term_jisuan(funid,['960'],term,[6,9,12]):

        ##广达
        guangda=Decimal(numpy_financial.pmt(0.14/12,term,momeey,0)).quantize(f)
        ##每期待还
        everyone=xiaoshudian(numpy_financial.pmt(0.36/12,term,momeey,0),n)
        ##fabs(everyone)-fabs(guangda)表示巧盼应得的
        return everyone,fabs(guangda),xiaoshudian(fabs(everyone)-fabs(guangda),n)
    raise Exception('无效的funid[{}]'.format(funid))


def getrandomOne(lists):
    return random.choice(lists)


def newmsgtemplate(k,flag=1):
    rw=rwKeyData.rwKeyData()
    if k=='templateType':
        return random.choice([0,1,2,3,4])
    elif k=='templateTypeOld' or k=='auditResult':
        return random.choice([0,1])
    elif k=='assetsResult':
        return random.choice([0,1,2,3])
    elif k=='channelType':
        return random.choice([0,1])
    elif k=='content':
        msg="【测试测试testing】{0}".format(fakeinfo('text'))
        return msg
    elif k=='merchantId':
        return random.choice([i for i in range(1,23)])
    elif k=='appIds':
        return [random.choice(["2882303761518006691","2882303761518053418"])]
    elif k=='sortStrategy':
        return random.choice(['desc','asc'])
    elif k=='msgType':
        return random.choice(['0','1','all'])
    elif k=='businessType':
        return random.choice(['3','20'])
    elif k=='platformId':
        return random.choice([2,4,5])
    elif k=='source':
        return random.choice([3,20])
    elif k=='clientType':
        return getrandomOne(['app','h5','web','native'])
    elif k=='productType':
        return getrandomOne([0,4,9])

    elif k=='sceneId':
        if rw.readKeyData('globalvar','sceneid') and flag:
            t = rw.readKeyData('globalvar', 'sceneid')
        else:
            t = random.choice([i for i in range(0, 7)])
            rw.writeKeyData('globalvar', 'sceneId', t)

        return t

    else:
        raise Exception('不支持',k,'====需要加')


def general_rule(*args,**kwargs):
    #print(type(args),args)
    #print(kwargs)
    rulemapping={'lt':'<','gt':'>','le':'='}
    temp=random.choice([i for i in range(60,65)])
    #print(temp)
    if args and isinstance(args,(list,tuple)):
        return random.choice(*args)
    if kwargs:
        if kwargs.get('max'):
            rule=kwargs.get('max')
            return rule if eval('{0}>{1}'.format(temp,rule)) else temp
        if kwargs.get('min'):
            rule = kwargs.get('min')
            return rule if eval('{0}<{1}'.format(temp,rule)) else temp
        if kwargs.get('min') and kwargs.get('max'):
            rule1 = kwargs.get('max')
            rule2=kwargs.get('min')

            return rule2 if eval('{0}<{1}'.format(temp,rule2)) or eval('{0}>{1}'.format(temp,rule1)) else temp

    return temp


def setglobalvalue(gvalue,casejson,fromto='body'):
    fromto=casejson.get(fromto)
    rw = rwKeyData.rwKeyData()
    if fromto and isinstance(fromto,dict):
        t=jsonpath.jsonpath(fromto,'$..{0}'.format(gvalue)) or jsonpath.jsonpath(fromto,'$.{0}'.format(gvalue))
        rw.readKeyData('globalvar',gvalue,t) if t else 0



def nowtime():
    return time.strftime('%Y-%m-%d %H:%M:%S')


def gettime(timedata,unit='days',flag=0,format=0,all=0):
    t = datetime.datetime.now()
    tt=t+datetime.timedelta(**{unit:timedata})
    formatdate=time.strptime(str(tt),'%Y-%m-%d %H:%M:%S.%f')
    ttt=int(time.mktime(formatdate))*1000
    rwKeyData.rwKeyData().writeKeyData('globalvar','deadline',ttt)
    if flag:
        return str(round(ttt/1000))
    if format:
        return (datetime.datetime.now()+datetime.timedelta(**{unit:timedata})).strftime("%Y-%m-%d")
    if all:
        return (datetime.datetime.now()+datetime.timedelta(**{unit:timedata})).strftime('%Y-%m-%d %H:%M:%S')
    return ttt



def saveuserId(user_id):
    rw=rwKeyData.rwKeyData()
    #sql="select id from xyqb_user.user where phone_no='%s'"
    rw.writeKeyData('globalvar','user_id','user_id={0}'.format(user_id))


def b64encodeXyqb(phone_no):
    ##暂时没用上
    header_Authorization = 'Verification ' + bytes.decode(base64.b64encode(phone_no.encode()))
    return header_Authorization

def getstrlist(*args):
    t=map(str,args)
    return ','.join(t)


def finalexecaql(sql):
    #print(dealDatabase,type(dealDatabase))
    from blueprints.tools.deals import getenvconfig
    config=getenvconfig()
    t=dealDatabase.delDatabase(config,sql)
    #print(t,sql)
    return t


def clear_redis():
    from blueprints.tools.deals import getenv
    environment = deals.getenv()
    #print(environment)
    header={'content-type':'application/json'}
    url = 'https://qaapi.liangkebang.com'
    ##login
    t='user=qiuyue.gui@quantgroup.cn&password=1234567890Yue@'
    auth={'auth':bytes.decode(base64.b64encode(t.encode()))}
    result=requests.post(url+'/user/login',headers=header,json=auth,verify=False)
    #print('333', result.text)
    ##token验证
    token=result.json().get('data').get('token')
    checktoken='/user/check_token_new?token='+token
    result11=requests.get(url +checktoken,verify=False)
    #print('333', result11.text)
    ##redis清理
    header['x-token']=token
    clear_redis_url=url+'/docker/flush_redis_tke?namespace={environment}'.format(environment=environment)
    header.pop('content-type')
    header['cluster']='qa'
    tt=requests.get(clear_redis_url,headers=header,verify=False)
    #print('333',tt.text)






if __name__ == '__main__':
    t=fakeinfo('cardNo')
    # print(t,type(t))
    # # tt=fakeinfo('cardNoProvider')
    # # print(tt,type(tt))
    # print(getBankInfo('cardNoProvider'))
    print(fakeinfo('idno'))
    #print(fakeinfo('username'))

    # a=momeyRate('900',6,10000,2)
    print(t)
    #
    # print(2)
    #t=fakeinfo('ip')
    #print(nowtime())
    # t=newmsgtemplate('clientType')
    # print(gettime(1,'days'))
    # t=getCircle((1,2,3),(4,5,6),(7,9))
    #
    # #t=general_rule(max=60)
    # print(t,type(t))

    #print(getCircle([480,880,770,580,910,540,630],[0,1],rigth=[(3,1)],b=2))
    #print(getCircle([1,2]))
    # sql="select  distinct id,IF(length(service_fee_config)>0,concat(3,',',6,',',9,',',12),concat(1,',',3,',',6,',',9,',',12)) from xyqb.finance_product where is_active=1 limit 10;"
    # t=fundCorpProduct_term(sql)
    # print(t)


    # print(gettime(1,'days',format=1))
    # print(gettime(-1,'weeks'))
    #
    # print(getstrlist(1,2,3))

    #print(clear_redis())

    # print(momeyRate('10001',3,-15.12))
    print(getCircle(right=[(20,'true'),(8,'false')]))

