# coding:utf-8

import requests,json,re,os,html
from urllib import  parse
from blueprints.tools import  baseConfig
from blueprints.cases_mapping import project_mapping
import pickle,jsonpath
import hashlib

testcasejsonpath=baseConfig.casedir

chandaourl="http://chandao.liangkebang.com"

def html_jsondata(url_result):
    result={}
    case_data_lists = []
    re_steps_v = ''
    json_data = json.loads(url_result['data'])
    #id=0
    #kk=""
    print(json_data)

    for steps_k,steps_v in json_data['case']['steps'].items():

        if steps_v['desc'] == 'type_int':
            re_steps_v = re.split(r'[,，]',steps_v['expect'])


    for steps_key, steps_value in json_data['case']['steps'].items():
        #print("---"*20)
        #print("***",steps_value)
        #print(json_data['case']['steps'])
        # if steps_value['desc'] in re_steps_v:
        #     case_data_lists.append({steps_value['desc']: int(steps_value['expect'])})
        #
        # else:
        #print("++", case_data_lists)
        case_data_lists.append([{steps_value['desc']: steps_value['expect'],"idss": steps_value['id'],"parent":steps_value['parent']}])
        #print("==",steps_value['desc'], steps_value['expect'])
        #ttttt={steps_value['desc']: steps_value['expect']}
        #print("++",ttttt)
        #print("++",case_data_lists)

    test_case_jsondata = {"commit":json_data['case']['title'],
                          "url":json_data['case']['precondition'],
                          "jsonInfo":case_data_lists}

    #print(test_case_jsondata["jsonInfo"])

    #print("test_case_jsondata---", test_case_jsondata)
    #print(json_data['case']['steps'])
    #print(case_data_lists)

    #print("====》",test_case_jsondata)
    result["method"]=re.findall(r"[a-zA-Z]{3,6}",test_case_jsondata["commit"])[-1]
    result["commit"]=test_case_jsondata["commit"]#.strip("\({0}\)".format(result["method"]))
    result["url"]=test_case_jsondata["url"]
    status=test_case_jsondata.get("status")
    if status:
        result["status"]=status
    if re.findall(r"/student_app/auth/login",result["url"]):
        result["casename"] ="ai_signin"
    elif re.findall(r"/teacher_app/auth/login",result["url"]):
        result["casename"] = "org-token"
    elif re.findall(r'tokenlogin',result["url"]):
        result["casename"] = 'org_web'
    elif re.findall(r'signin',result["url"]):
        result["casename"] = result["url"].split("/")[1]
    elif re.findall(r'mobile_login', result["url"]):
        result["casename"]="mobile_login"


    else:
        result["casename"]="token"  #result["url"].split("/")[1]#"-".join(result["url"].split("/"))[1:]


    for index,info1 in enumerate(test_case_jsondata["jsonInfo"]):

        info=info1[0]

        for k in info.keys():
            # if k=="type" or k=="sql" or k=="db":
            #     pass
            # else:
            #print("====",info)
            if info["parent"]==str(0) and info[k]=="" :
                id=info["idss"]
                result[k.strip()]={}
                #print(result,"----")
                for kk in test_case_jsondata["jsonInfo"]:
                    k1=kk[0]
                    #print("k1----",k1)
                    if k1["parent"]==id:
                        for k2,v2 in k1.items():
                            #print("k2,v2==",k2,v2)
                            if k2=="parent" or k2=="idss":
                                pass
                            else:
                                result[k.strip()][k2]=v2
            elif info["parent"]==str(0) and info[k]!="" and (k!="id" and k!="parent") :
                #print(k,k.strip(),len(k),info[k])
                info_vale = info[k].replace("&gt;",">")
                info_vale = info_vale.replace("&lt;","<")
                # info_vale.replace("&gt;",">")
                result[k.strip()]=info_vale

    if result.get("data"):
        t = html.unescape(json.dumps(result.get("data")).strip().replace("\\r\\n", "").replace("\\n","") \
                          .replace("\\t\\t", "")).replace(" ", "").replace("\'","\\\"")\
                          .replace("\\n\\t\\t","").replace("\\t","")
        #print(t.replace("\'","\\\""),type(t))
        #print(t)
        #print("t==",t,type(t))
        if isinstance(json.loads(t),(str,)):
            #print("t==",t)
            try:
                t1 = json.loads(json.loads(t))

            except :
                t1 = json.loads(t)

            #print("temp==", t1,type(t1))
            result["data"] = t1
        else:
            #print("temp==", t1, type(t1))
            result["data"] = json.loads(t)
        #print("temp==",t)
    #.replace("\"","\'")
    #print("==", t,type(t))


    print("==",result)
    if result.get("idss"):
        result.pop("idss")
    return result

def getprojectIds(cookies_requests,projectId,psid):
    #http://chandao.liangkebang.com/zentao/testcase-browse-4--byModule-29-id_desc-70-200-1.html
    #http://chandao.liangkebang.com/zentao/testcase-browse-1--byModule-16.json
    #http://chandao.liangkebang.com/zentao/testcase-browse-16--byModule-1.json
    url=chandaourl+"/zentao/testcase-browse-{0}--byModule-{1}-id_desc-40-200-1.json".format(psid,projectId)
    #print("url==",url)
    result=cookies_requests.get(url)
    #print("result==",result.text,url)
    try:
        tdr =json.loads(result.json().get("data")).get("cases")

        dr=json.dumps(tdr).strip().replace("\\","")
        getid = re.findall(r'"id": "([0-9]{1,})"', dr)
        #print("dr==",dr)
        print("getid",getid)

        return getid
    except Exception as e:
        print(e)



def getRand(url):

    #url="http://chandao.liangkebang.com/zentao/user-login.html"
    #return re.findall("",requests.get(url).text)
    result=requests.get(url)
    t=re.findall(r"id='verifyRand'(.*)/>",result.text)[0].strip()
    #print(result.cookies)
    with open("cookie.txt","wb") as f:
        pickle.dump(result.cookies,f)
    return t.replace("value=",'').replace("'",'')

def login():
    #verifyRand=getRand()
    cookies_requests = requests.session()
    login_url = chandaourl+'/zentao/user-login.html'
    password=hashlib.md5('Quantgroup2020'.encode()).hexdigest()
    rank = getRand(login_url)
    with open("cookie.txt", "rb") as f:
        cookie=pickle.load(f)

    tt=password+rank
    t=hashlib.md5(tt.encode()).hexdigest()

    #print("password",password,t)
    login_data = {'account': 'qiuyue.gui',
                 'password': t,
                  "verifyRand":getRand(login_url),
                  "referer":"/zentao/",
                  "keepLogin":1 }
    header={
        "content-type":"application/x-www-form-urlencoded; charset=UTF-8",
        "host":"chandao.liangkebang.com",
        "X-Requested-With":"XMLHttpRequest",
        "Accept":"application/json, text/javascript, */*; q=0.01",
        "origin":"http://chandao.liangkebang.com",
        "User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108",
        "refer":"http://chandao.liangkebang.com/zentao/user-login.html"}
    t=cookies_requests.post(url=login_url, data=login_data,headers=header,cookies=cookie)
    #print("login ===",t.text)
    return cookies_requests


def zentaopms_data(panda_name,projectId,psid):
    '''
    将用例存储到本地的tests/{{panda_name}}，并返回测试用例id组

    :param panda_name: 存储在本地的测试项目名
    :param projectId: 禅道的主项目名
    :param psid: 禅道的子项目名
    :return:测试用例id组
    '''
    #i=1
    testcasepath=testcasejsonpath+os.sep+panda_name

    #print(testcasepath)
    if os.path.exists(testcasepath):
        os.system("rm -rf {}".format(testcasepath))
    #if not os.path.exists(testcasepath):
    os.makedirs(testcasepath)
    #print()

    cookies_requests=login()

    cases_lists = []
    temp=getprojectIds(cookies_requests,projectId,psid)
    #print("temp",temp)
    cases_number=[int(i) for i in temp]
    #print("cases_number====",cases_number)

    #cases_number=[323,382,383,384,385,357,361,358,359,360,361]
    #cases_number=[357]

    #http://chandao.liangkebang.com/zentao/testcase-browse-1--byModule-16.json
    #http://chandao.liangkebang.com/zentao/testcase-view-40-1.json
    for i in cases_number:
        testcasefilepath=testcasepath+os.sep+str(i)+".json"
        url = chandaourl+'/zentao/testcase-view-%s.json'%i

        #print(i)

        http_re=cookies_requests.get(url=url)
        #print(i,"===",eval("u"+"\'"+http_re.text+"\'"))
        #print("@@@",http_re.json())

        temp=json.loads(http_re.json().get('data'))
        status=jsonpath.jsonpath(temp,'$..status')

        print("normal====",status)

        if 'investigate' in status[0]:
            continue

        re_data = html_jsondata(http_re.json())
        #print(testcasefilepath,"==",re_data)
        with open(testcasefilepath,"w+",encoding="utf-8") as file:
            json.dump(re_data,file,ensure_ascii=False,indent=4)

    return cases_lists
if __name__ == "__main__":


    #names=['ka_koala_repay','koala_risk','ka_koala_loan','trade']
    # names = ['risk']
    names=['zhongtai_hetong','msg','configuration_center','payment']


    for name in names:
        projectname=project_mapping.get(name)
        panda_name=projectname.get('casename') or name
        projectId=projectname.get('projectId')
        psid=projectname.get('psid')

        if not (projectname and panda_name and projectId and psid ):
            raise  Exception('{} 不能为空，需要到【cases_mapping】中查看'.format(name))
        zentaopms_data(panda_name, projectId, psid)


    # print(cases_number)
    #合同测试用例相关
    # panda_name = 'hetong'
    # projectId=16
    # psid=1

    #广达测试用例相关
    # projectId=29
    # psid=4
    # panda_name='passportapi'
    # zentaopms_data(panda_name, projectId, psid)


    # ##新合同接口
    # projectId = 32
    # psid = 1
    # panda_name = 'newhetong'
    # zentaopms_data(panda_name, projectId, psid)

    ##中台-合同
    # projectId = 46
    # psid = 5
    # panda_name = 'zhongtai_hetong'
    # zentaopms_data(panda_name, projectId, psid)

    ##新信息接口
    # projectId = 33
    # psid = 5
    # panda_name = 'msg'
    # zentaopms_data(panda_name, projectId, psid)

    # #新用户中心接口
    # projectId = 34
    # psid = 5
    # panda_name = 'usercenter'
    # zentaopms_data(panda_name, projectId, psid)

    # #风控系统
    # projectId = 36
    # psid = 5
    # panda_name = 'fengkong'
    # zentaopms_data(panda_name, projectId, psid)

    #资金系统接口
    # projectId = 37
    # psid = 5
    # panda_name = 'zijin'
    # zentaopms_data(panda_name, projectId, psid)

    # # 配置中心接口
    # projectId = 39
    # psid = 5
    # panda_name = 'configuration_center'
    # zentaopms_data(panda_name, projectId, psid)

    # # 财务系统
    # projectId = 40
    # psid = 5
    # panda_name = 'account'
    # zentaopms_data(panda_name, projectId, psid)

    # # 支付中心
    # projectId = 38
    # psid = 5
    # panda_name = 'payment'
    # zentaopms_data(panda_name, projectId, psid)

    # # 风控中心1.0
    # projectId = 42
    # psid = 5
    # panda_name = 'risk'
    # zentaopms_data(panda_name, projectId, psid)

    #交易系统
    # projectId = 41
    # psid = 5
    # panda_name = 'trade'
    # zentaopms_data(panda_name, projectId, psid)

    #考拉-放款系统
    # projectId = 44
    # psid = 7
    # panda_name = 'koala_loan'
    # zentaopms_data(panda_name, projectId, psid)

    # # 考拉-风审系统
    # projectId = 43
    # psid = 7
    # panda_name = 'koala_risk'
    # zentaopms_data(panda_name, projectId, psid)

    ## 考拉-还款系统
    # projectId = 45
    # psid = 7
    # panda_name = 'koala_repay'
    # zentaopms_data(panda_name, projectId, psid)

    # KA-考拉放款
    # projectId = 49
    # psid = 7
    # panda_name = 'ka_koala_loan'
    # zentaopms_data(panda_name, projectId, psid)
    # #
    # # KA-考拉还款
    # projectId = 50
    # psid = 7
    # panda_name = 'ka_koala_repay'
    # zentaopms_data(panda_name, projectId, psid)

    #a = zentaopms_data(cases_number)
    #print(a)
    #print(a[0])
    # print(type(a[0]['test_cases'][0]))
    # print()