"""
@autor:Yue
@date::14:12
@file:extra.py
@project:appQutoInfo

"""
import os,json,time,sys
aa=os.path.abspath(__file__)
sys.path.append(os.path.dirname(os.path.dirname(aa)))
from flask import render_template,current_app,Blueprint,request,url_for,redirect,jsonify
try:
    from blueprints.exec import runexec
except:
    from blueprints.exec import runexec
from blueprints.tools.dealScene import dealScene
from blueprints.tools import deals
indexpage=Blueprint("index",__name__)
from blueprints.tools import dingdingtalk
@indexpage.route("/",methods=["get"])
def index():
    c=current_app.config.get("sConfig")
    cdir=c.casedir
    projectname=[i for i in os.listdir(cdir) if  os.path.isdir(os.path.join(cdir,i))]
    #print("===",projectname,cdir,cc)
    t=[]
    for index,i in enumerate(projectname):
        casediri=os.path.join(cdir,i)
        t.append({i:[subi for subi in os.listdir(casediri) if os.path.splitext(subi)[-1]==".json"]})
        #print([os.path.splitext(subi)[-1] for subi in os.listdir(casediri)])
    #print(t)
    return render_template("index.html",data=t)



@indexpage.route("/scence",methods=["post"])
def scence():
    c = current_app.config.get("sConfig")
    f=request.form
    scencecase=[]
    p=f.get('projectname')
    namespace=f.get('namespace')
    reportdir=os.path.join(c.reportsfile,p)
    if not os.path.exists(reportdir):
        os.makedirs(reportdir)
    for k,v in f.items():
        if k!="projectname":
            t=f.getlist(k)
            t.remove(k)
            scencecase.append({k:t})

    print("***"*20,scencecase)
    cf=deals.renameFile('html')
    rf=os.path.join(reportdir,cf)
    scencecase=dealScene(c,scencecase)
    f,s,starttime,exectime=runexec(c, scencecase,rf)
    fname,houzui=cf.split(".")
    renamecf=os.path.join(reportdir,"_".join([fname,str(starttime),str(s),str(f),str(exectime)])+"."+houzui)
    os.rename(rf,renamecf)
    url=url_for('index.show',details=(s+f,s,f))
    url='http://67bc7a8d.ngrok.io'+url
    msg="执行总数:{0},是否执行成功:{1};成功数:{2};失败数：{3}；执行总时长:{4}".format(f+s,'Y' if s else 'N',s,f,exectime)
    dingdingtalk.dingRobot().sendMes(url,msg)
    return "<a href={0}>查看全部报告</a><br/><h1>执行总数:{1},是否执行成功:{2};成功数:{3};失败数：{4}；执行总时长:{5}</h1>".\
        format(url_for('index.show',_external=True,details=(s+f,s,f)),
               f+s,'Y' if s else 'N',s,f,exectime)

@indexpage.route("/showall",methods=["get"])
def show():
    c = current_app.config.get("sConfig")
    reportdir=c.reportsfile
    t={}

    for i in os.listdir(reportdir):
        #print("+++++>", i,os.path.isdir(i))
        cs=os.path.join(reportdir,i)
        if os.path.isdir(cs):
            #print("+++++",i)
            vv=[(os.path.join("reports",i,ii),
                             time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(os.path.getmtime(os.path.join(cs,ii))) ))
                            for ii in os.listdir(cs) if ii.split(".")[-1]=="html"]
            vv.sort(key=lambda k:k[-1],reverse=1)
            t.setdefault(i,vv)
    print("=========>",vv)
    return render_template("show.html",t=t)

@indexpage.route('/<string:projectname>',methods=['get'])
def reportstable(projectname):
    c=current_app.config.get('baseconfig')

    reportdir=c.reportsfile+os.sep+projectname
    reporttype=[i for i in os.listdir(reportdir) if os.path.isdir(reportdir+os.sep+i)]
    temp={}
    for i in reporttype:

        htmlpath=os.path.join(reportdir,i)
        #htmlpath=[i for i in os.listdir(reportdir) if os.path.isdir(htmlpath)]


        versionhtmlpath=[str(i) for i in os.listdir(htmlpath) if os.path.isdir(htmlpath+os.sep+i)]

        #print('htmlpversionhtmlpathath=====', versionhtmlpath)

        projectinfo={}
        for ii in versionhtmlpath:

            reportinfo = []
            t=os.popen("ls -tr {0} |sort -r | grep -i 'html' |head -1".format(os.path.join(htmlpath,ii))).readline().strip()
            htmlfile=os.path.join(htmlpath,ii,t)
            testall="\"testAll\":"
            testfail='\"testFail\":'
            beginTime='\"beginTime\":'
            testall=os.popen("cat {0} |grep -i '{1}' ".format(htmlfile,testall)).readline().split(testall)[-1].strip().strip(',') or 0
            testfail = os.popen("cat {0} |grep -i '{1}'".format(htmlfile, testfail)).readline().split(testfail)[-1].strip().strip(',') or 0
            beginTime = os.popen("cat {0} |grep -i '{1}' ".format(htmlfile, beginTime)).readline().split(beginTime)[-1].strip().strip(',') or 0
            print(t,'++++++', testall,testfail,htmlfile)
            if testall:
                testpass=eval("{0}-{1}".format(testall,testfail))
                reportinfo.append(t)
                reportinfo.append(testall)
                reportinfo.append(testfail)
                reportinfo.append(testpass)
                reportinfo.append(len(versionhtmlpath))
                reportinfo.append(beginTime)
                k=i+"_"+ii+"_"+projectname
                projectinfo[ii]=reportinfo #[t,testall,testfail,testpass,beginTime]


        projectkey = i + "_" + projectname
        if projectinfo:
            temp[projectkey]=dict(sorted(projectinfo.items(),key=lambda b:b[0]))#projectinfo
        #print('temp++++++', temp)

        # temp['info']=[testall,]
        # temp['testfail'] = testfail
        # temp['testpass'] = testpass
        # temp['beginTime'] = beginTime
        #temp.setdefault(i,os.path.getctime())

    print('测试报告的temp：',temp)
    return render_template('reportstable.html',info=dict(sorted(temp.items(), key=lambda d: d[0])),relativepath=reportdir)


@indexpage.route('/reportstable',methods=['get'])
def showall():
    msg="<a href={0}>中台</a><br/><a href={1}>考拉</a><br/><a href={2}>KA</a>"\
        .format(url_for('index.reportstable',projectname='中台'),url_for('index.reportstable',projectname='考拉'),url_for('index.reportstable',projectname='KA'))
    return msg


# @indexpage.route('/out-custom_link_batch',methods=['post'])
# def hetongcallback():
#     userId=request.json.get('userId')
#     templateId = request.json.get('contract')[0].get('templateId')
#     t={'userid':userId,'templateid':1,'msg':'return test flask out-custom_link_batch indexpage','code':'0'}
#     return jsonify(t)
#
#
# @indexpage.route('/out-custom_link',methods=['post'])
# def hetongcallback1():
#     userId=request.json.get('userId')
#     templateId = request.json.get('contract')[0].get('templateId')
#     t={'userid':userId,'templateid':1,'msg':'return test flask out-custom_link','code':'0'}
#     return jsonify(t)