from .common import *
dqpath=os.path.split(os.path.realpath(__file__))[0]
def before_request():
    pass
from PIL import Image, ImageDraw, ImageFont
import io
def generate_image_with_text(text=['福州','公司'],bg_color=(245, 187, 150)):
    image = Image.new('RGB',(128,128), color = bg_color)
    # 创建一个可以在给定图像上绘图的对象
    draw = ImageDraw.Draw(image)
    # 设置字体和大小（需要事先下载字体文件或使用系统字体）
    # 例如，使用系统字体Arial，大小为36
    # 在图片上添加文字
    # print('texts',text)
    current_directory = dqpath+"/common/file/fzxst.TTF"
    if len(text)==1:
        if len(text[0])==1:
            font = ImageFont.truetype(current_directory, 90)
            textsize = draw.textlength(text[0], font=font)
            draw.text(((128-textsize)/2,20), text[0], fill=(255,255,255), font=font)
        elif len(text[0])==2:
            font = ImageFont.truetype(current_directory, 50)
            textsize = draw.textlength(text[0], font=font)
            draw.text(((128-textsize)/2,35), text[0], fill=(255,255,255), font=font)
        elif len(text[0])==3:
            font = ImageFont.truetype(current_directory, 38)
            textsize = draw.textlength(text[0], font=font)
            draw.text(((128-textsize)/2,48), text[0], fill=(255,255,255), font=font)
    elif len(text)==2:
        if len(text[0])==2:
            font = ImageFont.truetype(current_directory, 50)
            textsize1 = draw.textlength(text[0], font=font)
            textsize2 = draw.textlength(text[1], font=font)
            draw.text(((128-textsize1)/2,10), text[0], fill=(255,255,255), font=font)
            draw.text(((128-textsize2)/2,64), text[1], fill=(255,255,255), font=font)
        else:
            font = ImageFont.truetype(current_directory, 38)
            textsize1 = draw.textlength(text[0], font=font)
            textsize2 = draw.textlength(text[1], font=font)
            draw.text(((128-textsize1)/2,20), text[0], fill=(255,255,255), font=font)
            draw.text(((128-textsize2)/2,66), text[1], fill=(255,255,255), font=font)
    elif len(text)==3:
        font = ImageFont.truetype(current_directory, 35)
        textsize1 = draw.textlength(text[0], font=font)
        textsize2 = draw.textlength(text[1], font=font)
        textsize3 = draw.textlength(text[2], font=font)
        draw.text(((128-textsize1)/2,6), text[0], fill=(255,255,255), font=font)
        draw.text(((128-textsize2)/2,46), text[1], fill=(255,255,255), font=font)
        draw.text(((128-textsize3)/2,86), text[2], fill=(255,255,255), font=font)
    elif len(text)==4:
        font = ImageFont.truetype(current_directory, 25)
        textsize1 = draw.textlength(text[0], font=font)
        textsize2 = draw.textlength(text[1], font=font)
        textsize3 = draw.textlength(text[2], font=font)
        textsize4 = draw.textlength(text[3], font=font)
        draw.text(((128-textsize1)/2,5), text[0], fill=(255,255,255), font=font)
        draw.text(((128-textsize2)/2,35), text[1], fill=(255,255,255), font=font)
        draw.text(((128-textsize3)/2,65), text[2], fill=(255,255,255), font=font)
        draw.text(((128-textsize4)/2,95), text[3], fill=(255,255,255), font=font)
    
    # 将图像转换为字节流
    img_byte_arr = io.BytesIO()
    image.save(img_byte_arr, format='PNG')
    img_byte_arr = img_byte_arr.getvalue()  # 获取字节流的值
    return img_byte_arr
class pub:
    def icon(texts='',t=''):
        try:
            HTTP_IF_NONE_MATCH=globals.HEADER.GET['HTTP_IF_NONE_MATCH']
        except:
            HTTP_IF_NONE_MATCH=None
        if not HTTP_IF_NONE_MATCH:
            texts=request.args.get('text')
            bg_color=request.args.get('bg_color')
            cl=request.args.get('cl')
            if not cl:
                if len(texts)>=16:
                    cl=4
                elif len(texts)>=9:
                    cl=3
                elif len(texts) >= 6:
                    cl=2
                elif len(texts) in [1,2,3]:
                    cl=1
                else:
                    cl=2
            else:
                cl=int(cl)
            if not bg_color:
                bg_color='207,20,7'
            bg_arr=bg_color.split(",")
            bg_color=[]
            for k in bg_arr:
                bg_color.append(int(k))
            bg_color=tuple(bg_color)
            if cl==1:
                text=[texts[0:3].upper()]
            elif cl==2:
                if len(texts)>=6:
                    text=[texts[0:3].upper()]
                    if texts[3:6]:
                        text.append(texts[3:6].upper())
                else:
                    text=[texts[0:2].upper()]
                    if texts[2:4]:
                        text.append(texts[2:4].upper())
            elif cl==3:
                text=[texts[0:3].upper()]
                if texts[3:6]:
                    text.append(texts[3:6].upper())
                if texts[6:9]:
                    text.append(texts[6:9].upper())
            elif cl==4:
                text=[texts[0:4].upper()]
                if texts[4:8]:
                    text.append(texts[4:8].upper())
                if texts[8:12]:
                    text.append(texts[8:12].upper())
                if texts[12:16]:
                    text.append(texts[12:16].upper())
            body=generate_image_with_text(text,bg_color)
        else:
            body=''
        return response.pic(body=body)
    def outlogin():
        account_token=request.args.get("account_token")
        if account_token:
            del_cache(account_token)
        else:
            del_session('userinfo')
        return successjson()
    def get_account_token(username,sign,timestamp,random,types="get_account_token"):
        "获取用户token"
        status,code,msg,account_token=serlogin(username,sign,timestamp,random,types)
        if status:
            return successjson(data={"account_token":account_token},msg=msg)
        else:
            return errorjson(code=-1,msg=msg)
    def login(username,sign,timestamp,random,types="session"):
        "登录"
        G.setadminlog=username+",登录系统"
        status,code,msg,account_token=serlogin(username,sign,timestamp,random,types)
        if status:
            return successjson(data=account_token,msg=msg)
        else:
            return errorjson(code=code,msg=msg)
    def addr():
        return successjson(request.HEADER.Physical_IP())

    def getkwebs():
        config.kwebs['path']=get_kwebs_folder()
        return successjson(config.kwebs)
    
    def checkserver():
        return successjson()
    
    def clistartplan():
        #这里是初始化计划任务 （cli方式运行）
        try:
            serverserverintervals=sqlite("interval",model_intapp_index_path).select()
            if serverserverintervals and (times()-int(serverserverintervals[0]['updtime'])) > 5:
                for serverserverinterval in serverserverintervals:
                        serverserverinterval['updtime']=times()
                        sqlite("interval",model_intapp_index_path).where("id",serverserverinterval['id']).update(serverserverinterval)
                        PLANTASK.plantask(serverserverinterval) #添加计划任务
                while True:
                    time.sleep(100)
        except:
            pass
    def webclosemsg(a1='',a2='',a3='',a4='',a5='',a6='',a7='',a8='',a9='',a10=''):
        format='json'
        if format=='html':
            return '您访问的站点正在维护中，暂时无法访问，请稍后在试'
        elif format=='json':
            return errorjson(code=-1,msg='您访问的站点正在维护中，暂时无法访问，请稍后在试')
    def gitpull():
        "执行git"
        path=request.args.get('path')
        branch=request.args.get('branch') #强制更新指定分支
        title=request.args.get('title')
        taskid=md5(randoms()+str(times()))
        if not title:
            title="git pull，"+path
        if 'Linux' in get_sysinfo()['platform']:
            shell='cd '+path+' && git reset --hard'
            if branch:
                shell+=' origin/'+branch
            shell+=' && git clean -f && git pull'
            Queues.insert(target=PUBLICOther.gitpull,args=(taskid,path,shell),title=title,describes="执行命令："+shell,taskid=taskid,start=10,updtime=times()+1)
        elif 'Window' in get_sysinfo()['platform']:
            shell="git reset --hard"
            if branch:
                shell+=' origin/'+branch
            Queues.insert(target=PUBLICOther.gitpull,args=(taskid,path,shell),title=title,describes="执行命令："+shell,taskid=taskid)
            shell='git clean -f'
            Queues.insert(target=PUBLICOther.gitpull,args=(taskid,path,shell),title=title,describes="执行命令："+shell,taskid=taskid)
            shell='git pull'
            Queues.insert(target=PUBLICOther.gitpull,args=(taskid,path,shell),title=title,describes="执行命令："+shell,taskid=taskid)
        G.setadminlog="执行命令："+shell
        return successjson("命令已添加到任务队列中")
    
class PUBLICOther():
    def gitpull(taskid,path,shell):
        pi=subprocess.Popen(shell,shell=True, stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
        strs=pi.stdout.read().decode()
        if path=='/kwebsp/pythoninvdatap':
            try:
                os.remove("app/zcg.zip")
            except:pass
            # time.sleep(1)
            kcwebszip.packzip("pythoninvdatap/app/zcg","app/zcg.zip")
            kcwebszip.unzip_file("app/zcg.zip","app/zcg")
            try:
                os.remove("app/zcg.zip")
            except:pass
            strs="文件已更新："+strs
        Queues.setfield(taskid,'msg',"执行结果："+str(strs))
        # f=open(path+"/gitpull.log","w",encoding='utf-8')
        # f.write("\n时间:%s\n%s\n%s\n" % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),shell,strs))
        # f.close()


    