#-*- encoding:utf-8 -*-
#!/usr/bin/python
from docx import Document
from docx.oxml import shared
from docx.opc import constants
from elasticsearch import Elasticsearch
import time, datetime
import requests
from PIL import Image
import os
import oss2
from flask import Flask , render_template,request
from docxtpl import DocxTemplate, RichText,InlineImage
import os
from docx.shared import Inches, Pt, RGBColor, Mm
from pyecharts.charts import Gauge,Pie,Line,Bar,WordCloud
from pyecharts.render import make_snapshot
from snapshot_selenium import snapshot
from pyecharts import options as opts
import json
import numpy as np
import PIL.Image as image
import flask
from flask_cors import CORS
from wordcloud import WordCloud

app = flask.Flask(__name__)
CORS(app, supports_credentials=True)
app.config['JSON_AS_ASCII'] = False
#esip = "43.247.184.94"
#esport = 9200
esip = "172.16.18.110"
esport = 9203
esuser = "admines"
espassword = "adminGSBes"
es = Elasticsearch([esip], http_auth=(esuser, espassword), port=esport)

# 阿里云接口地址
endpoint = 'http://oss-cn-beijing.aliyuncs.com'
auth = oss2.Auth('LTAI4GC5tSKvqsH2hMqj6pvd', '3KV9nIwW8qkTGlrPmAe3HnR3fzM6r5')
bucket = oss2.Bucket(auth, endpoint, 'gsb-zc')

#生成图片
def charts(datalist,charttype,pngpath):
    try:
        img = None
        if charttype == 1: #仪表盘
            img = Gauge()
            img.add("知产价值评估",[("", datalist[0]["value"])], axisline_opts=opts.AxisLineOpts(
                    linestyle_opts=opts.LineStyleOpts(
                        color=[(0.3, "#67e0e3"), (0.7, "#37a2da"), (1, "#fd666d")], width=30
                    )),label_opts=opts.LabelOpts(formatter="{value}"))
        elif charttype == 2:#饼状图
            img = Pie()
            valuelist = []
            for list in datalist:
                valuelist.append((list["key"],list["value"]))
            img.add("", valuelist, label_opts=opts.LabelOpts(formatter="{b}: {c}"))
        elif charttype ==3:#折线图
            img = Line()
            keylist = []
            valuelist = []
            for list in datalist:
                keylist.append(list["key"])
                valuelist.append(list["value"])
            img.add_xaxis(keylist)
            img.add_yaxis("",valuelist,color= "#1E90FF")
        elif charttype ==4:#柱状图
            img = Bar()
            keylist = []
            valuelist = []
            for list in datalist:
                keylist.append(list["key"])
                valuelist.append(list["value"])
            img.add_xaxis(keylist)
            img.add_yaxis("",valuelist,color= "#1E90FF")
        elif charttype ==5:
            img=WordCloud()
            words=[]
            for list in datalist:
                if len(words)<10:
                    word=(list["key"],int(list["value"]))
                    words.append(word)
                else:
                    break
            img.add("",words,word_size_range=[20,100])
        elif charttype == 6:  # 条形图
            img = Bar()
            keylist = []
            valuelist = []
            for list in datalist:
                keylist.append(list["key"])
                valuelist.append(list["value"])
            img.add_xaxis(keylist)
            img.add_yaxis("", valuelist, color="#1E90FF")
            img.reversal_axis()
        if img:
            make_snapshot(snapshot, img.render(), pngpath)
            return  True
        else:
            return False
    except Exception as e:
        print(e)
        return  False

def chartslines(xlist,datalist1,datalist2,datalist3,pngpath):#多折线
    try:
        img = Line()
        img.add_xaxis(xlist)
        img.add_yaxis("发明专利", datalist1,color= "#67e0e3")
        img.add_yaxis("新型新型", datalist2,color= "#37a2da")
        img.add_yaxis("外观设计", datalist3,color= "#fd666d")
        if img:
            make_snapshot(snapshot, img.render(), pngpath)
            return  True
        else:
            return False
    except:
        return False

def chartsbars(xlist,datalist1,datalist2,datalist3,pngpath):#多条形图
    try:
        img = Bar()
        img.add_xaxis(xlist)
        img.add_yaxis("发明专利", datalist1, stack="stack1",color= "#37a2da")
        img.add_yaxis("新型实用新型", datalist2, stack="stack1",color= "#67e0e3")
        img.add_yaxis("外观设计", datalist3, stack="stack1",color= "#fd666d")
        img.reversal_axis()
        if img:
            make_snapshot(snapshot, img.render(), pngpath)
            return True
        else:
            return False
    except:
        return  False

def strQ2B(ustring):
    """全角转半角"""
    rstring = ""
    for uchar in ustring:
        inside_code=ord(uchar)
        if inside_code == 12288:                              #全角空格直接转换
            inside_code = 32
        elif (inside_code >= 65281 and inside_code <= 65374): #全角字符（除空格）根据关系转化
            inside_code -= 65248
        rstring += chr(inside_code)
    return rstring


def createciyuntm(cut_text,png_path):#词云图
    try:
        mask = np.array(image.open("tm2.jpg"))
        if not cut_text:
            cut_text = "暂无数据 "
        wordcloud = WordCloud(
            font_path="SIMSUN.TTC",
            mask=mask,
            collocations=False,
            background_color="white", width=100, height=80).generate(cut_text)
        wordcloud.to_file(png_path)
        return True
    except:
        return  False


def create_doc(mycompanyname):
    # 读取模板文件
    tpl = DocxTemplate('cellbg.docx')
    # 工商接口
    resjq = es.search(index="bigdata_ic_gsb_company_op",
                      body={"query": {"term": {"company_name.raw": mycompanyname}}})
    #context = {'gsblg': InlineImage(tpl, "gsb.png", width=Mm(8)), 'template': mycompanyname}
    context = {'template': mycompanyname}
    if resjq["hits"]["hits"]:
        mycompanyinfo = resjq["hits"]["hits"][0]["_source"]
        reg_number=str(mycompanyinfo["reg_number"])
        context['reg_number']=reg_number
        org_number = "未公开"
        if mycompanyinfo["org_number"]:
            org_number = str(mycompanyinfo["org_number"])
        context['org_number'] = org_number
        legal_person = "未公开"
        if mycompanyinfo["legal_person"]:
            legal_person = str(mycompanyinfo["legal_person"])
        context['legal_person'] = legal_person
        reg_status = "未公开"
        if mycompanyinfo["reg_status"]:
            reg_status = str(mycompanyinfo["reg_status"])
        context['reg_status'] = reg_status
        estibish_time = "未公开"
        if mycompanyinfo["estiblish_time"]:
            estibish_time = str(time.strftime("%Y-%m-%d", time.localtime(mycompanyinfo["estiblish_time"])))
        context['estiblish_time'] = estibish_time
        to_time = "未公开"
        if mycompanyinfo["to_time"]:
            to_time = str(time.strftime("%Y-%m-%d", time.localtime(mycompanyinfo["to_time"])))
        #context['to_time'] = to_time
        reg_capital = "未公开"
        if mycompanyinfo["reg_capital"] and mycompanyinfo["reg_capital"]!=0 and mycompanyinfo["reg_unit"]:
            reg_capital = str(mycompanyinfo["reg_capital"])+" "+str(mycompanyinfo["reg_unit"])
        context['reg_capital'] = reg_capital
        reg_institute = "未公开"
        if mycompanyinfo["reg_institute"]:
            reg_institute = str(mycompanyinfo["reg_institute"])
        context['reg_institute'] = reg_institute
        reg_location = "未公开"
        if mycompanyinfo["reg_location"]:
            reg_location = str(mycompanyinfo["reg_location"])
        context['reg_location'] = reg_location
        business_scope = "未公开"
        if mycompanyinfo["business_scope"]:
            business_scope = str(mycompanyinfo["business_scope"])
        context['business_scope'] = business_scope
    #  专利接口
    index_name = "bigdata_patent_bib"
    doc = {
        "query": {
            "bool": {
                "must": [
                    {
                        "term": {
                            "applicant_name.raw": mycompanyname
                        }
                    },
                    {
                        "term": {
                            "pub_type": "发明"
                        }
                    }
                ]
            }
        }
    }
    searched = es.search(index=index_name,body=doc)
    fm_pub_count = searched["hits"]["total"]#发明公开量
    context["fm_pub_count"] = str(fm_pub_count)

    doc = {
        "query": {
            "bool": {
                "must": [
                    {
                        "term": {
                            "applicant_name.raw": mycompanyname
                        }
                    },
                    {
                        "term": {
                            "pub_type": "发明"
                        }
                    },
                    {"exists": {"field": "gr_no"}}
                ]
            }
        }
    }
    searched = es.search(index=index_name,body=doc)
    fm_gr_count = searched["hits"]["total"]#发明公开量
    context["fm_gr_count"] = str(fm_gr_count)

    doc = {
        "query": {
            "bool": {
                "must": [
                    {
                        "term": {
                            "applicant_name.raw": mycompanyname
                        }
                    },
                    {
                        "term": {
                            "pub_type": "实用新型"
                        }
                    }
                ]
            }
        }
    }
    searched = es.search(index=index_name,body=doc)
    xx_pub_count = searched["hits"]["total"]#新型公开量
    xx_gr_count = searched["hits"]["total"]#新型授权量
    context["xx_pub_count"] = str(xx_pub_count)
    context["xx_gr_count"] = str(xx_gr_count)

    doc = {
        "query": {
            "bool": {
                "must": [
                    {
                        "term": {
                            "applicant_name.raw": mycompanyname
                        }
                    },
                    {
                        "term": {
                            "pub_type": "外观设计"
                        }
                    }
                ]
            }
        }
    }
    searched = es.search(index=index_name, body=doc)
    wg_pub_count = searched["hits"]["total"]#新型公开量
    wg_gr_count = searched["hits"]["total"]#新型授权量
    context["wg_pub_count"] = str(wg_pub_count)
    context["wg_gr_count"] = str(wg_gr_count)

    doc = {
        "query": {
            "bool": {
                "must": [
                    {
                        "term": {
                            "applicant_name.raw": mycompanyname
                        }
                    },
                    {
                        "term": {
                            "pub_status": "有效"
                        }
                    }
                ]
            }
        },
        "aggregations": {
            "group_by_type": {
                "terms": {
                    "field": "pub_type",
                    "size": 20,
                    "min_doc_count": 0,
                    "order": {
                        "_term": "asc"
                    }
                }
            }
        }
    }
    searched = es.search(index=index_name,body=doc)
    buckets = searched["aggregations"]["group_by_type"]["buckets"]#发明公开量
    fm_yx_count = buckets[0]["doc_count"]
    context["fm_yx_count"] = str(fm_yx_count)
    wg_yx_count = buckets[1]["doc_count"]
    context["wg_yx_count"] = str(wg_yx_count)
    xx_yx_count = buckets[2]["doc_count"]
    context["xx_yx_count"] = str(xx_yx_count)

    context["total_pub_count"] = str(fm_pub_count + xx_pub_count + wg_pub_count)
    context["total_gr_count"] = str(fm_gr_count + xx_gr_count + wg_gr_count)
    context["total_yx_count"] = str(fm_yx_count + xx_yx_count + wg_yx_count)

    info = [{"key": "发明专利", "value": str(fm_pub_count)}, {"key": "实用新型", "value": str(xx_pub_count)},
            {"key": "外观设计", "value": str(wg_pub_count)}]#公开量做饼图

    if charts(info, 2, "pie01.png"):
        context['pub_pie'] = InlineImage(tpl, "pie01.png", width=Mm(60))

    info = [{"key": "发明专利", "value": str(fm_gr_count)}, {"key": "实用新型", "value": str(xx_gr_count)},
            {"key": "外观设计", "value": str(wg_gr_count)}]#授权量做饼图
    if charts(info, 2, "pie02.png"):
        context['gr_pie'] = InlineImage(tpl, "pie02.png", width=Mm(60))

    info = [{"key": "发明专利", "value": str(fm_yx_count)}, {"key": "实用新型", "value": str(xx_yx_count)},
            {"key": "外观设计", "value": str(wg_yx_count)}]#有效量做饼图
    if charts(info, 2, "pie03.png"):
        context['yx_pie'] = InlineImage(tpl, "pie03.png", width=Mm(60))

    #发展趋势-申请量
    yearlist = ["2009", "2010", "2011", "2012", "2013", "2014", "2015", "2016", "2017", "2018"]
    doc = {
        "query": {
            "bool": {
                "must": [
                    {
                        "term": {
                            "applicant_name.raw": mycompanyname
                        }
                    },
                    {"terms": {"filing_year": yearlist}}
                ]
            }
        },
        "from": 0,
        "size": 0,
        "aggregations": {
            "group_by_year": {
                "terms": {
                    "field": "filing_year",
                    "size": 10,
                    "order": {
                        "_term": "asc"
                    }
                },
                "aggregations": {
                    "group_by_type": {
                        "terms": {
                            "field": "pub_type",
                            "size": 10,
                            "min_doc_count": 0,
                            "order": {
                                "_term": "asc"
                            }
                        }
                    }
                }
            }
        }
    }
    searched = es.search(index=index_name, body=doc)
    sources = []
    fmlist = [0,0,0,0,0,0,0,0,0,0]
    xxlist = [0,0,0,0,0,0,0,0,0,0]
    wglist = [0,0,0,0,0,0,0,0,0,0]
    for aggs in searched["aggregations"]["group_by_year"]["buckets"]:
        m=0
        for year in yearlist:
            if aggs["key"] == year:
                fmlist[m] = aggs["group_by_type"]["buckets"][0]["doc_count"]
                wglist[m] = aggs["group_by_type"]["buckets"][1]["doc_count"]
                xxlist[m] = aggs["group_by_type"]["buckets"][2]["doc_count"]
            m += 1
    m=0
    totallist = []
    for year in yearlist:
        total = fmlist[m] + xxlist[m] + wglist[m]
        totallist.append({"key":year,"value":total})
        source = {"year2":year,"fm2count":fmlist[m],"xx2count":xxlist[m],"wg2count":wglist[m],"total2count":total}
        sources.append(source)
        m+=1
    context["tms"] = sources
    if chartslines(yearlist, fmlist,xxlist,wglist, "linefiling.png"):
        context['filing2_line'] = InlineImage(tpl, "linefiling.png", width=Mm(120))
    if charts(totallist,3,"lineftotal.png"):
        context['filing2_total_line'] = InlineImage(tpl, "linefiling.png", width=Mm(120))

    # 发展趋势-公开量
    doc = {
        "query": {
            "bool": {
                "must": [
                    {
                        "term": {
                            "applicant_name.raw": mycompanyname
                        }
                    },
                    {"terms": {"pub_year": yearlist}}
                ]
            }
        },
        "from": 0,
        "size": 0,
        "aggregations": {
            "group_by_year": {
                "terms": {
                    "field": "pub_year",
                    "size": 10,
                    "order": {
                        "_term": "asc"
                    }
                },
                "aggregations": {
                    "group_by_type": {
                        "terms": {
                            "field": "pub_type",
                            "size": 10,
                            "min_doc_count": 0,
                            "order": {
                                "_term": "asc"
                            }
                        }
                    }
                }
            }
        }
    }
    searched = es.search(index=index_name, body=doc)
    sources = []
    fmlist = [0,0,0,0,0,0,0,0,0,0]
    xxlist = [0,0,0,0,0,0,0,0,0,0]
    wglist = [0,0,0,0,0,0,0,0,0,0]
    for aggs in searched["aggregations"]["group_by_year"]["buckets"]:
        m=0
        for year in yearlist:
            if aggs["key"] == year:
                fmlist[m] = aggs["group_by_type"]["buckets"][0]["doc_count"]
                wglist[m] = aggs["group_by_type"]["buckets"][1]["doc_count"]
                xxlist[m] = aggs["group_by_type"]["buckets"][2]["doc_count"]
            m += 1
    m=0
    totallist = []
    for year in yearlist:
        total = fmlist[m] + xxlist[m] + wglist[m]
        totallist.append({"key":year,"value":total})
        source = {"year2":year,"fm2count":fmlist[m],"xx2count":xxlist[m],"wg2count":wglist[m],"total2count":total}
        sources.append(source)
        m+=1
    context["pubtms"] = sources
    if chartslines(yearlist, fmlist,xxlist,wglist, "linepub.png"):
        context['filing2_pub_line'] = InlineImage(tpl, "linepub.png", width=Mm(120))
    if charts(totallist,3,"lineptotal.png"):
        context['filing2_pub_total_line'] = InlineImage(tpl, "lineptotal.png", width=Mm(120))

    # 发展趋势-授权量
    doc = {
        "query": {
            "bool": {
                "must": [
                    {
                        "term": {
                            "applicant_name.raw": mycompanyname
                        }
                    },
                    {"terms": {"gr_year": yearlist}}
                ]
            }
        },
        "from": 0,
        "size": 0,
        "aggregations": {
            "group_by_year": {
                "terms": {
                    "field": "gr_year",
                    "size": 10,
                    "order": {
                        "_term": "asc"
                    }
                },
                "aggregations": {
                    "group_by_type": {
                        "terms": {
                            "field": "pub_type",
                            "size": 10,
                            "min_doc_count": 0,
                            "order": {
                                "_term": "asc"
                            }
                        }
                    }
                }
            }
        }
    }
    searched = es.search(index=index_name, body=doc)
    sources = []
    fmlist = [0,0,0,0,0,0,0,0,0,0]
    xxlist = [0,0,0,0,0,0,0,0,0,0]
    wglist = [0,0,0,0,0,0,0,0,0,0]
    for aggs in searched["aggregations"]["group_by_year"]["buckets"]:
        m=0
        for year in yearlist:
            if aggs["key"] == year:
                fmlist[m] = aggs["group_by_type"]["buckets"][0]["doc_count"]
                wglist[m] = aggs["group_by_type"]["buckets"][1]["doc_count"]
                xxlist[m] = aggs["group_by_type"]["buckets"][2]["doc_count"]
            m += 1
    m=0
    totallist = []
    for year in yearlist:
        total = fmlist[m] + xxlist[m] + wglist[m]
        totallist.append({"key":year,"value":total})
        source = {"year2":year,"fm2count":fmlist[m],"xx2count":xxlist[m],"wg2count":wglist[m],"total2count":total}
        sources.append(source)
        m+=1
    context["grtms"] = sources
    if chartslines(yearlist, fmlist,xxlist,wglist, "linegr.png"):
        context['filing2_gr_line'] = InlineImage(tpl, "linegr.png", width=Mm(120))
    if charts(totallist,3,"linegtotal.png"):
        context['filing2_gr_total_line'] = InlineImage(tpl, "linegtotal.png", width=Mm(120))

    #IPC分析-大类
    doc = {
        "query": {
            "bool": {
                "must": [
                    {
                        "term": {
                            "applicant_name.raw": mycompanyname
                        }
                    },
                    {
                        "terms": {
                            "pub_type": ["发明", "实用新型"]
                        }
                    }
                ]
            }
        },
        "from": 0,
        "size": 0,
        "aggregations": {
            "group_by_ipc": {
                "terms": {
                    "field": "large class",
                    "size": 10,
                    "order": {
                        "_count": "desc"
                    }
                }
            }
        }
    }
    searched = es.search(index=index_name, body=doc)
    ipclist = []
    for agg in searched["aggregations"]["group_by_ipc"]["buckets"]:
        ipclist.append({"key":agg["key"],"value":agg["doc_count"]})
    if charts(ipclist,6,"ipclarge.png"):
        context['ipc_large'] = InlineImage(tpl, "ipclarge.png", width=Mm(120))

    #IPC分析-小类
    doc = {
        "query": {
            "bool": {
                "must": [
                    {
                        "term": {
                            "applicant_name.raw": mycompanyname
                        }
                    },
                    {
                        "terms": {
                            "pub_type": ["发明", "实用新型"]
                        }
                    }
                ]
            }
        },
        "from": 0,
        "size": 0,
        "aggregations": {
            "group_by_ipc": {
                "terms": {
                    "field": "sub_class",
                    "size": 10,
                    "order": {
                        "_count": "desc"
                    }
                }
            }
        }
    }
    searched = es.search(index=index_name, body=doc)
    ipclist = []
    for agg in searched["aggregations"]["group_by_ipc"]["buckets"]:
        ipclist.append({"key":agg["key"],"value":agg["doc_count"]})
    if charts(ipclist,6,"ipcsmall.png"):
        context['ipc_small'] = InlineImage(tpl, "ipcsmall.png", width=Mm(120))

    #IPC分析-洛迦诺大类
    doc = {
        "query": {
            "bool": {
                "must": [
                    {
                        "term": {
                            "applicant_name.raw": mycompanyname
                        }
                    },
                    {
                        "term": {
                            "pub_type": "外观设计"
                        }
                    }
                ]
            }
        },
        "from": 0,
        "size": 0,
        "aggregations": {
            "group_by_ipc": {
                "terms": {
                    "field": "class_code",
                    "size": 10,
                    "order": {
                        "_count": "desc"
                    }
                }
            }
        }
    }
    searched = es.search(index=index_name, body=doc)
    ipclist = []
    for agg in searched["aggregations"]["group_by_ipc"]["buckets"]:
        ipclist.append({"key":agg["key"],"value":agg["doc_count"]})
    if charts(ipclist,6,"ljnlarge.png"):
        context['ljn_large'] = InlineImage(tpl, "ljnlarge.png", width=Mm(120))

    #IPC分析-洛迦诺小类
    doc = {
        "query": {
            "bool": {
                "must": [
                    {
                        "term": {
                            "applicant_name.raw": mycompanyname
                        }
                    },
                    {
                        "term": {
                            "pub_type": "外观设计"
                        }
                    }
                ]
            }
        },
        "from": 0,
        "size": 0,
        "aggregations": {
            "group_by_ipc": {
                "terms": {
                    "field": "main_ipc",
                    "size": 10,
                    "order": {
                        "_count": "desc"
                    }
                }
            }
        }
    }
    searched = es.search(index=index_name, body=doc)
    ipclist = []
    for agg in searched["aggregations"]["group_by_ipc"]["buckets"]:
        ipclist.append({"key":agg["key"],"value":agg["doc_count"]})
    if charts(ipclist,6,"ljnsmall.png"):
        context['ljn_small'] = InlineImage(tpl, "ljnsmall.png", width=Mm(120))

    #法律状态
    doc = {
        "query": {
            "bool": {
                "must": [
                    {
                        "term": {
                            "applicant_name.raw": mycompanyname
                        }
                    }
                ]
            }
        },
        "from": 0,
        "size": 0,
        "aggregations": {
        "group_by_type": {
            "terms": {
                "field": "pub_type",
                "size": 20,
                "min_doc_count": 0,
                "order": {
                    "_term": "asc"
                }
            },
            "aggregations": {
                "group_by_status": {
                    "terms": {
                        "field": "pub_status",
                        "size": 10,
                        "min_doc_count": 0,
                        "order": {
                            "_term": "asc"
                        }
                    }
                }
            }
        }
    }
    }
    searched = es.search(index=index_name, body=doc)
    fminfo = []
    xxinfo = []
    wginfo = []
    zxcount = [0,0,0]
    wxcount = [0,0,0]
    yxcount = [0,0,0]
    for aggs in searched["aggregations"]["group_by_type"]["buckets"]:
        if  aggs["key"] == "发明":
            for agg in aggs["group_by_status"]["buckets"]:
                fminfo.append({"key":agg["key"],"value":agg["doc_count"]})
                if agg["key"] == "在审":
                    zxcount[0] = agg["doc_count"]
                elif agg["key"] == "有效":
                    yxcount[0] = agg["doc_count"]
                elif agg["key"] == "无效":
                    wxcount[0] = agg["doc_count"]
        elif aggs["key"] == "实用新型":
            for agg in aggs["group_by_status"]["buckets"]:
                xxinfo.append({"key":agg["key"],"value":agg["doc_count"]})
                if agg["key"] == "在审":
                    zxcount[1] = agg["doc_count"]
                elif agg["key"] == "有效":
                    yxcount[1] = agg["doc_count"]
                elif agg["key"] == "无效":
                    wxcount[1] = agg["doc_count"]
        elif aggs["key"] == "外观设计":
            for agg in aggs["group_by_status"]["buckets"]:
                wginfo.append({"key":agg["key"],"value":agg["doc_count"]})
                if agg["key"] == "在审":
                    zxcount[2] = agg["doc_count"]
                elif agg["key"] == "有效":
                    yxcount[2] = agg["doc_count"]
                elif agg["key"] == "无效":
                    wxcount[2] = agg["doc_count"]

    context["fl_fm_0"] = yxcount[0]
    context["fl_xx_0"] = yxcount[1]
    context["fl_wg_0"] = yxcount[2]
    context["fl_fm_1"] = wxcount[0]
    context["fl_xx_1"] = wxcount[1]
    context["fl_wg_1"] = wxcount[2]
    context["fl_fm_2"] = zxcount[0]
    context["fl_xx_2"] = zxcount[1]
    context["fl_wg_2"] = zxcount[2]

    if charts(fminfo, 2, "piefmzs.png"):
        context['fl_fm_pie'] = InlineImage(tpl, "piefmzs.png", width=Mm(60))
    if charts(xxinfo, 2, "piexxzs.png"):
        context['fl_xx_pie'] = InlineImage(tpl, "piexxzs.png", width=Mm(60))
    if charts(wginfo, 2, "piewgzs.png"):
        context['fl_wg_pie'] = InlineImage(tpl, "piewgzs.png", width=Mm(60))

    #无效原因
    doc = {
        "query": {
            "bool": {
                "must": [
                    {
                        "term": {
                            "applicant_name.raw": mycompanyname
                        }
                    },
                    {
                        "term": {
                            "pub_status": "无效"
                        }
                    }
                ]
            }
        },
        "from": 0,
        "size": 0,
        "aggregations": {
            "group_by_status": {
                "terms": {
                    "field": "pub_status_now",
                    "size": 20,
                    "order": {
                        "_count": "desc"
                    }
                }
            }
        }
    }
    searched = es.search(index=index_name, body=doc)
    info = []
    for agg in searched["aggregations"]["group_by_status"]["buckets"]:
        info.append({"key":agg["key"],"value":agg["doc_count"]})
    if charts(info, 2, "flpie.png"):
        context['fl_pie'] = InlineImage(tpl, "flpie.png", width=Mm(120))

    #申请人分析
    doc = {
        "query": {
            "bool": {
                "must": [
                    {
                        "term": {
                            "applicant_name.raw": mycompanyname
                        }
                    }
                ]
            }
        },
        "from": 0,
        "size": 0,
        "aggregations": {
            "group_by_appl": {
                "terms": {
                    "field": "applicant_name.raw",
                    "size": 11,
                    "order": {
                        "_count": "desc"
                    }
                },
                "aggregations": {
                    "group_by_type": {
                        "terms": {
                            "field": "pub_type",
                            "size": 10,
                            "min_doc_count": 0,
                            "order": {
                                "_term": "asc"
                            }
                        }
                    }
                }
            }
        }
    }
    searched = es.search(index=index_name, body=doc)
    appllist = []
    fmlist = []
    xxlist = []
    wglist = []
    sources = []
    if len(searched["aggregations"]["group_by_appl"]["buckets"]) > 1:
        for m in range(1,len(searched["aggregations"]["group_by_appl"]["buckets"])):
            key = searched["aggregations"]["group_by_appl"]["buckets"][m]["key"]
            appllist.append(key)
            fmcount = searched["aggregations"]["group_by_appl"]["buckets"][m]["group_by_type"]["buckets"][0]["doc_count"]
            fmlist.append(fmcount)
            wgcount = searched["aggregations"]["group_by_appl"]["buckets"][m]["group_by_type"]["buckets"][1]["doc_count"]
            wglist.append(wgcount)
            xxcount = searched["aggregations"]["group_by_appl"]["buckets"][m]["group_by_type"]["buckets"][2]["doc_count"]
            xxlist.append(xxcount)
            total = fmcount + xxcount + wgcount
            sources.append({"name": key, "fmcount": fmcount, "xxcount": xxcount, "wgcount": wgcount,"totalcount": total})
    context["appls"] = sources

    if chartsbars(appllist,fmlist,xxlist,wglist,"appls.png"):
        context['appl_line'] = InlineImage(tpl, "appls.png", width=Mm(120))

    #发明人分析
    doc = {
        "query": {
            "bool": {
                "must": [
                    {
                        "term": {
                            "applicant_name.raw": mycompanyname
                        }
                    }
                ]
            }
        },
        "from": 0,
        "size": 0,
        "aggregations": {
            "group_by_appl": {
                "terms": {
                    "field": "inventor_name.raw",
                    "size": 10,
                    "order": {
                        "_count": "desc"
                    }
                },
                "aggregations": {
                    "group_by_type": {
                        "terms": {
                            "field": "pub_type",
                            "size": 10,
                            "min_doc_count": 0,
                            "order": {
                                "_term": "asc"
                            }
                        }
                    }
                }
            }
        }
    }
    searched = es.search(index=index_name, body=doc)
    appllist = []
    fmlist = []
    xxlist = []
    wglist = []
    sources = []
    for agg in searched["aggregations"]["group_by_appl"]["buckets"]:
        key = agg["key"]
        appllist.append(key)
        fmcount = agg["group_by_type"]["buckets"][0]["doc_count"]
        fmlist.append(fmcount)
        wgcount = agg["group_by_type"]["buckets"][1]["doc_count"]
        wglist.append(wgcount)
        xxcount = agg["group_by_type"]["buckets"][2]["doc_count"]
        xxlist.append(xxcount)
        total = fmcount + xxcount + wgcount
        sources.append({"name": key, "fmcount": fmcount, "xxcount": xxcount, "wgcount": wgcount, "totalcount": total})
    context["invs"] = sources

    if chartsbars(appllist,fmlist,xxlist,wglist,"invs.png"):
        context['inv_line'] = InlineImage(tpl, "invs.png", width=Mm(120))

    #代理机构分析
    doc = {
        "query": {
            "bool": {
                "must": [
                    {
                        "term": {
                            "applicant_name.raw": mycompanyname
                        }
                    }
                ]
            }
        },
        "from": 0,
        "size": 0,
        "aggregations": {
            "group_by_appl": {
                "terms": {
                    "field": "agency_name.raw",
                    "size": 10,
                    "order": {
                        "_count": "desc"
                    }
                },
                "aggregations": {
                    "group_by_type": {
                        "terms": {
                            "field": "pub_type",
                            "size": 10,
                            "min_doc_count": 0,
                            "order": {
                                "_term": "asc"
                            }
                        }
                    }
                }
            }
        }
    }
    searched = es.search(index=index_name, body=doc)
    appllist = []
    fmlist = []
    xxlist = []
    wglist = []
    sources = []
    for agg in searched["aggregations"]["group_by_appl"]["buckets"]:
        key = agg["key"]
        appllist.append(key)
        fmcount = agg["group_by_type"]["buckets"][0]["doc_count"]
        fmlist.append(fmcount)
        wgcount = agg["group_by_type"]["buckets"][1]["doc_count"]
        wglist.append(wgcount)
        xxcount = agg["group_by_type"]["buckets"][2]["doc_count"]
        xxlist.append(xxcount)
        total = fmcount + xxcount + wgcount
        sources.append({"name": key, "fmcount": fmcount, "xxcount": xxcount, "wgcount": wgcount, "totalcount": total})
    context["agns"] = sources

    if chartsbars(appllist,fmlist,xxlist,wglist,"agns.png"):
        context['agn_line'] = InlineImage(tpl, "agns.png", width=Mm(120))


    #专利技术分析
    doc = {"query": {"bool": {"must": [{"term": {"applicant_name.raw": mycompanyname}}]}},
           "aggregations": {
               "types": {
                   "terms": {
                       "field": "key_word",
                       "size": 50,
                       "order": {
                           "_count": "desc"
                       }
                   }
               }
           }}
    searched = es.search(index=index_name, body=doc)
    tmnames = ""
    m=1
    for buk in searched["aggregations"]["types"]["buckets"]:
        if m==1:
            context["keyword1"] = buk["key"]
            context["key_word1"] = buk["key"]
            context["key_count1"] = buk["doc_count"]
        elif m==2:
            context["keyword2"] = buk["key"]
            context["key_word2"] = buk["key"]
            context["key_count2"] = buk["doc_count"]
        elif m==3:
            context["keyword3"] = buk["key"]
            context["key_word3"] = buk["key"]
            context["key_count3"] = buk["doc_count"]
        elif m==4:
            context["keyword4"] = buk["key"]
            context["key_word4"] = buk["key"]
            context["key_count4"] = buk["doc_count"]
        m+=1
        for i in range(buk["doc_count"]):
            tmnames = tmnames + buk["key"] + " "
    if tmnames:
        if createciyuntm(tmnames,"ciyun.png"):
            context['key_yun'] = InlineImage(tpl, "ciyun.png", width=Mm(150))

    #专利产业布局
    doc = {
            "query": {
                "bool": {
                    "must": [
                        {
                            "term": {
                                "applicant_name.raw": mycompanyname
                            }
                        }
                    ]
                }
            },
            "aggregations": {
                "types": {
                    "terms": {
                        "field": "broad_name",
                        "size": 50,
                        "order": {
                            "_count": "desc"
                        }
                    }
                }
            }
        }
    searched = es.search(index=index_name, body=doc)
    if len(searched["aggregations"]["types"]["buckets"]) >0:
        brodinfo = []
        if len(searched["aggregations"]["types"]["buckets"]) <= 10:
            m = 1
            for buk in searched["aggregations"]["types"]["buckets"]:
                if m == 1:
                    context["broad1"] = buk["key"]
                elif m == 2:
                    context["broad2"] = buk["key"]
                elif m == 3:
                    context["broad3"] = buk["key"]
                elif m == 4:
                    context["broad4"] = buk["key"]
                m += 1
                brodinfo.append({"key":buk["key"],"value":buk["doc_count"]})
        else:
            for i in range(10):
                brodinfo.append({"key": searched["aggregations"]["types"]["buckets"][i]["key"], "value":
                    searched["aggregations"]["types"]["buckets"][i]["doc_count"]})
                if i==0:
                    context["broad1"] = searched["aggregations"]["types"]["buckets"][i]["key"]
                elif i==1:
                    context["broad2"] = searched["aggregations"]["types"]["buckets"][i]["key"]
                elif i==2:
                    context["broad3"] = searched["aggregations"]["types"]["buckets"][i]["key"]
                elif i==3:
                    context["broad3"] = searched["aggregations"]["types"]["buckets"][i]["key"]
            other_count = 0;
            for i in range(10,len(searched["aggregations"]["types"]["buckets"])):
                other_count += searched["aggregations"]["types"]["buckets"][i]["doc_count"]
            if other_count:
                brodinfo.append({"key": "其它", "value": other_count})
        if brodinfo:
            if charts(brodinfo, 2, "piebrod.png"):
                context['broad_pai'] = InlineImage(tpl, "piebrod.png", width=Mm(120))

    #专利详情
    doc = {
            "query": {
                "bool": {
                    "must": [
                        {
                            "term": {
                                "applicant_name.raw": mycompanyname
                            }
                        }
                    ]
                }
            },
            "from": 0,
            "size": 100,
            "sort": [
                {
                    "pub_date": "desc"
                }
            ],
            "_source": [
                "filing_no",
                "pub_type",
                "filing_time",
                "pub_time",
                "pub_no",
                "gr_time",
                "gr_no",
                "filing_name",
                "pub_status",
                "abstr_text",
                "main_ipc",
                "broad_name"
            ]
        }
    searched = es.search(index=index_name, body=doc)
    p_source = []
    m=1
    for hit in searched["hits"]["hits"]:
        bg = "000000"
        if hit["_source"]["pub_status"] == "无效":
            bg =  'FF0000'
        if hit["_source"]["gr_no"]:
            pn = hit["_source"]["gr_no"]
            pd = hit["_source"]["gr_time"]
        else:
            pn = hit["_source"]["pub_no"]
            pd = hit["_source"]["pub_time"]
        list = hit["_source"]["broad_name"]
        broad_name = ""
        if list:
            for br in list:
                broad_name += br + ";"
            broad_name = broad_name.strip(";")
        p_source.append({"no": m, "fn":  hit["_source"]["filing_no"], "fd": hit["_source"]["filing_time"],
                         "pn": pn, "pd": pd,"pt":hit["_source"]["pub_type"],"ps":RichText(hit["_source"]["pub_status"],color=bg),
                         "title":hit["_source"]["filing_name"],"bord":broad_name})

        m+=1

        if p_source:
            context["ps"] = p_source

    nowtime = time.strftime('%Y-%m-%d', time.localtime())
    context['nowtime'] = nowtime

    tpl.render(context)
    tpl.save('cellbg1.docx')
    # 生成新的word文件
    # Docx = Document("aaa.docx")
    # os.remove("aaa.docx")


    # 保存文件
    #Docx.save(mycompanyname + "python.docx")
    current_file_path = "patent.docx"
    current_fold = time.strftime('%Y%m%d%H%M%S', time.localtime())
    file_path = mycompanyname + "patent.docx"
    p = mycompanyname + "_" + str(current_fold) + "_" + current_file_path
    print(p)
    # 上传阿里云
    bucket.put_object_from_file(p, "cellbg1.docx")
    os.remove("cellbg1.docx")
    return "https://gsb-zc.oss-cn-beijing.aliyuncs.com/"+p

# 服务器接口API
@app.route('/patentdoc/api/createdoc',methods=['POST', 'GET'])
def PatentDocApi():
    if request.method == "GET":
        mycompanyname = request.args.get("mycompanyname")  # 得到问题
    if request.method == "POST":
        mycompanyname = request.get_json().get("mycompanyname")  # 得到问题
    r_1 = create_doc(strQ2B(mycompanyname))
    return r_1

if __name__ == '__main__':
    #app.run(host='127.0.0.1', port=5000, debug=True)
    app.run(host='172.16.18.120', port=9500, debug=True)



