#-*- encoding:utf-8 -*-
from elasticsearch import Elasticsearch
import time, datetime
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
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
from wordcloud import WordCloud

file_object = open('ncltwo.json',encoding='UTF-8')
app = Flask(__name__)
# esip = "43.247.184.94"
# esport = 9200
# # esip = "172.16.18.120"
# # esport = 9201
# esuser = "admines"
# espassword = "adminGSBes"
# es = Elasticsearch([esip], http_auth=(esuser, espassword), port=esport)
#
# esip1 = "43.247.184.94"
# esport1 = 9200
# es1 = Elasticsearch([esip], http_auth=(esuser, espassword), port=7200)


# esip = "43.247.184.94"
#esport = 9200
esip = "172.16.18.110"
esport = 9201
esuser = "admines"
espassword = "adminGSBes"
es = Elasticsearch([esip], http_auth=(esuser, espassword), port=esport)

esip1 = "172.16.18.10"
esport1 = 9200
es1 = Elasticsearch([esip1], http_auth=(esuser, espassword), port=esport1)

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

ncl_one=[ "化学原料","颜料油漆","日化用品","燃料油脂","医药","金属材料","机械设备","手工器械","科学仪器","医疗器械","灯具空调","运输工具","军火烟火","珠宝钟表","乐器","办公用品","橡胶制品","皮革皮具","筑材料","家具","厨房洁具","绳网袋蓬","纱线丝","布料床单","服装鞋帽","钮扣拉链","地毯席垫",
          "健身器材","食品","方便食品","农林生鲜","啤酒饮料","酒","烟草烟具","广告销售","金融物管","建筑修理","通讯服务","运输贮藏","材料加工","教育娱乐","科技服务","餐饮住宿","医疗园艺","社会服务"]



file_context = json.load(file_object)
ncl_two=file_context["RECORDS"]
dict_ncl_two={}
for n in ncl_two:
    dict_ncl_two[n["code"]]=n["name"]
b=dict_ncl_two
#生成图片
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])
        if img:
            make_snapshot(snapshot, img.render(), pngpath)
            return  True
        else:
            return False
    except Exception as e:
        print(e)
        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 sortlist(lis):
  #进行去重
  c = []
  for i in lis:
    if i not in c:
      c.append(i)
  #进行统计，生成二维列表
  b = []
  for i in c:
    num = 0
    for j in range(len(lis)):
      if lis[j] == i:
        num += 1
    a = []
    a.append(i)
    a.append(num)
    b.append(a)
  # 排序算法，按出现次数进行降序排列
  for i in range(len(b)):
    for j in range(i,len(b)):
      if b[i][1] < b[j][1]:
        temp = b[i]
        b[i] = b[j]
        b[j] = temp
  print(b)
  strlist=""
  if len(b)>5:
      for k1 in range(5):
          if int(b[k1][0])<50:
              strlist += str(ncl_one[int(b[k1][0])-1]) + "、"
          else:
              strlist+=str(b[k1][0])+"、"
  else:
      for k2 in b:
          if int(k2[0])<50:
              strlist += str(ncl_one[int(k2[0])-1]) + "、"
          else:
              strlist+=str(k2[0])+"、"
  strlist=strlist[:-1]
  return strlist


def createciyun(list):
    cut_text=""
    mask=np.array(image.open("tm.jpg"))
    for i in list:
        if i in dict_ncl_two.keys():
            cut_text+=dict_ncl_two[i]+" "
    if not cut_text:
        cut_text="暂无数据 "    
    wordcloud = WordCloud(
        font_path="SIMSUN.TTC",
        mask=mask,
        background_color="white", width=100, height=80).generate(cut_text)
    wordcloud.to_file("ciyun.png")
    return True

def createciyuntm(cut_text):
    mask=np.array(image.open("tm2.jpg"))
    if not cut_text:
        cut_text="暂无数据 "
    wordcloud = WordCloud(
        font_path="SIMSUN.TTC",
        mask=mask,
        background_color="white", width=100, height=80).generate(cut_text)
    wordcloud.to_file("ciyuntm.png")
    return True

def categorylist(lis):
  #进行去重
  c = []
  for i in lis:
    if i not in c:
      c.append(i)
  #进行统计，生成二维列表
  b = []
  for i in c:
    num = 0
    for j in range(len(lis)):
      if lis[j] == i:
        num += 1
    a = []
    a.append(i)
    a.append(num)
    b.append(a)
  # 排序算法，按出现次数进行降序排列
  for i in range(len(b)):
    for j in range(i,len(b)):
      if b[i][1] < b[j][1]:
        temp = b[i]
        b[i] = b[j]
        b[j] = temp
  print(b)
  strlist=[]
  if len(b)>5:
      for k1 in range(5):
          source={"key":b[k1][0],"value":b[k1][1]}
          strlist.append(source)
  else:
      for k2 in b:
          source ={"key":ncl_one[int(k2[0])-1], "value": k2[1]}
          strlist.append(source)
  return strlist


def ncltwolist(lis):
  #进行去重
  c = []
  for i in lis:
    if i not in c:
      c.append(i)
  #进行统计，生成二维列表
  b = []
  for i in c:
    num = 0
    for j in range(len(lis)):
      if lis[j] == i:
        num += 1
    a = []
    a.append(i)
    a.append(num)
    b.append(a)
  # 排序算法，按出现次数进行降序排列
  for i in range(len(b)):
    for j in range(i,len(b)):
      if b[i][1] < b[j][1]:
        temp = b[i]
        b[i] = b[j]
        b[j] = temp
  print(b)
  strlist=[]
  for k2 in b:
      if k2[0] in dict_ncl_two.keys():
          source = {"key": dict_ncl_two[k2[0]], "value": k2[1]}
      strlist.append(source)
  return strlist

def yearlist(lis):
    count2014 = 0
    count2015 = 0
    count2016 = 0
    count2017 = 0
    count2018 = 0
    count2019 = 0
    for i in lis:
        if i==2014:
            count2014+=1
        if i==2015:
            count2015+=1
        if i==2016:
            count2016+=1
        if i==2017:
            count2017+=1
        if i==2018:
            count2018+=1
        if i==2019:
            count2019+=1
    count = [{"key":"2014","value":str(count2014)},{"key":"2015","value":str(count2015)},{"key":"2016","value":str(count2016)},
             {"key":"2017","value":str(count2017)},{"key":"2018","value":str(count2018)},{"key":"2019","value":str(count2019)}]
    return count



def create_doc(mycompanyname,rivalcompanyname):
    # 读取模板文件
    tpl = DocxTemplate('cellbg.docx')
    # 工商接口
    resjq = es.search(index="bigdata_ic_gsb_company_op",
                      body={"query": {"term": {"company_name.raw": 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['estibish_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
    #  商标接口
    resjq = es1.search(index="bigdata_middle_gsb_tm_info",
                       body={"size": 1000, "query": {"term": {"applicant_cn": mycompanyname}}})
    mytminfo = resjq["hits"]["hits"]
    yx = 0
    sqz = 0
    wx = 0
    ot = 0
    years = []
    nclone = []
    ncltwos=[]
    tmnames=""
    if mytminfo:
        # 获得所需数组
        for i in mytminfo:
            years.append(i["_source"]["apply_year"])
            nclone.append(i["_source"]["ncl_one_codes"])
            if 'ncl_two_codes' in i["_source"].keys():
                if i["_source"]["ncl_two_codes"]:
                    ncltwos+=i["_source"]["ncl_two_codes"]
            if i["_source"]["tm_name"]:
                if "图形" not in i["_source"]["tm_name"]:
                    tmnames+=i["_source"]["tm_name"]+" "
            if i["_source"]["status"] == 1:
                sqz += 1
            elif i["_source"]["status"] == 2 or i["_source"]["status"] == 3:
                yx += 1
            elif i["_source"]["status"] == 4:
                wx += 1
            else:
                ot += 1
        # 计算评分
        grades = 70
        if len(mytminfo) > 50 and len(mytminfo) <= 100:
            grades = 75
        elif len(mytminfo) > 100 and len(mytminfo) <= 200:
            grades = 80
        elif len(mytminfo) > 200 and len(mytminfo) <= 500:
            grades = 85
        elif len(mytminfo) > 500:
            grades = 90
        pie=""
        guage=""
        line=""
        bar=""
        tciyun=""
        tciyuntm=""
        if charts([{"key": "", "value": grades}], 1, "yibiaopan.png"):
            guage="yibiaopan.png"
        info = [{"key": "有效注册", "value": str(yx)}, {"key": "申请中", "value": str(sqz)},
                {"key": "无效", "value": str(wx)}, {"key": "其他", "value": str(ot)}]
        if charts(info, 2, "bar01.png"):
            pie = "bar01.png"
        yearls=yearlist(years)
        if charts(yearls, 3, "zx01.png"):
            line="zx01.png"
        if createciyun(ncltwos):
            tciyun="ciyun.png"

        if createciyuntm(tmnames):
            tciyuntm="ciyuntm.png"
        nclones = categorylist(nclone)
        nclone1=""
        countnclone1=""
        nclone2 = ""
        countnclone2 = ""
        nclone3 = ""
        countnclone3 = ""
        nclone4 = ""
        countnclone4 = ""
        nclone5 = ""
        countnclone5 = ""
        if charts(nclones, 4, "zz01.png"):
            bar="zz01.png"
            nclone1 = nclones[0]['key']
            countnclone1 = nclones[0]['value']
            if len(nclones)>1:
                nclone2 = nclones[1]['key']
                countnclone2 = nclones[1]['value']
            if len(nclones)>2:
                nclone3 = nclones[2]['key']
                countnclone3 = nclones[2]['value']
            if len(nclones)>3:
                nclone4 = nclones[3]['key']
                countnclone4 = nclones[3]['value']
            if len(nclones)>4:
                nclone5 = nclones[4]['key']
                countnclone5 = nclones[4]['value']

        ncltwotables=ncltwolist(ncltwos)
        ncltwo1 = ""
        countncltwo1 = ""
        ncltwo2 = ""
        countncltwo2 = ""
        ncltwo3 = ""
        countncltwo3 = ""
        ncltwo4 = ""
        countncltwo4 = ""
        ncltwo5 = ""
        countncltwo5 = ""
        if len(ncltwotables) > 0:
            ncltwo1 = ncltwotables[0]['key']
            countncltwo1 = ncltwotables[0]['value']
        if len(ncltwotables)>1:
            ncltwo2 = ncltwotables[1]['key']
            countncltwo2 = ncltwotables[1]['value']
        if len(ncltwotables)>2:
            ncltwo3 = ncltwotables[2]['key']
            countncltwo3 = ncltwotables[2]['value']
        if len(ncltwotables)>3:
            ncltwo4 = ncltwotables[3]['key']
            countncltwo4 = ncltwotables[3]['value']
        if len(ncltwotables)>4:
            ncltwo5 = ncltwotables[4]['key']
            countncltwo5 = ncltwotables[4]['value']
        # 获取时间戳
        beforetime = datetime.datetime.now() + datetime.timedelta(days=365)
        aftertime = datetime.datetime.now() - datetime.timedelta(days=183)
        nowTime = datetime.datetime.now()
        nowday = datetime.date.today()
        sources=[]
        for m in mytminfo:
            tm_regist_num=m["_source"]["tm_regist_num"]
            tm_name="未公开"
            if m["_source"]["tm_name"]:
                tm_name=m["_source"]["tm_name"]
            bg="FFFFFF"
            if m["_source"]["tm_end_day"]:
                if int(m["_source"]["tm_end_day"]) < int(beforetime.timestamp()) and int(
                        m["_source"]["tm_end_day"]) > int(nowTime.timestamp()):
                    bg = 'FF0000'
                elif int(m["_source"]["tm_end_day"]) < int(nowTime.timestamp()) and int(
                        m["_source"]["tm_end_day"]) > int(aftertime.timestamp()):
                    bg = 'FF0000'
            tm_status = "未公开"
            if m["_source"]["status"] == 1:
                tm_status = "申请中"
            elif m["_source"]["status"] == 2:
                tm_status = "初审"
            elif m["_source"]["status"] == 3:
                tm_status = "注册"
            apply_day = "未公开"
            if m["_source"]["apply_day"]:
                apply_day = time.strftime("%Y-%m-%d", time.localtime(m["_source"]["apply_day"]))
            regist_notice_day = "未公开"
            if m["_source"]["regist_notice_day"]:
                regist_notice_day = time.strftime("%Y-%m-%d", time.localtime(m["_source"]["regist_notice_day"]))
            tm_end_day = "未公开"
            if m["_source"]["regist_notice_day"]:
                tm_end_day = time.strftime("%Y-%m-%d", time.localtime(m["_source"]["tm_end_day"]))
            ncl_one_codes = m["_source"]["ncl_one_codes"]
            source={"tm_regist_num":tm_regist_num,"tm_name":tm_name,"tm_status":tm_status,"apply_day":apply_day,"regist_notice_day":regist_notice_day,"tm_end_day":tm_end_day,"ncl_one_codes":ncl_one_codes,"bg":bg}
            sources.append(source)
        context['validate_Num'] = str(yx)
        context['invalidate_Num'] = str(wx)
        context['application_Num'] = str(sqz)
        context['other_Num'] = str(ot)
        context['tms'] = sources
        context['guage'] = InlineImage(tpl, guage, width=Mm(80))
        context['pie'] = InlineImage(tpl, pie, width=Mm(80))
        context['line'] = InlineImage(tpl, line, width=Mm(130))
        context['bar'] = InlineImage(tpl, bar, width=Mm(130))
        context['tciyun'] = InlineImage(tpl, tciyun, width=Mm(130))
        context['tciyuntm'] = InlineImage(tpl, tciyuntm, width=Mm(130))
        context['count2014'] = yearls[0]['value']
        context['count2015'] = yearls[1]['value']
        context['count2016'] = yearls[2]['value']
        context['count2017'] = yearls[3]['value']
        context['count2018'] = yearls[4]['value']
        context['count2019'] = yearls[5]['value']
        context['nclone1'] = nclone1
        context['countnclone1'] = countnclone1
        context['nclone2'] = nclone2
        context['countnclone2'] = countnclone2
        context['nclone3'] = nclone3
        context['countnclone3'] = countnclone3
        context['nclone4'] = nclone4
        context['countnclone4'] = countnclone4
        context['nclone5'] = nclone5
        context['countnclone5'] = countnclone5
        context['ncltwo1'] = ncltwo1
        context['countncltwo1'] = countncltwo1
        context['ncltwo2'] = ncltwo2
        context['countncltwo2'] = countncltwo2
        context['ncltwo3'] = ncltwo3
        context['countncltwo3'] = countncltwo3
        context['ncltwo4'] = ncltwo4
        context['countncltwo4'] = countncltwo4
        context['ncltwo5'] = ncltwo5
        context['countncltwo5'] = countncltwo5
    tpl.render(context)
    tpl.save('cellbg1.docx')
    # 生成新的word文件
    # Docx = Document("aaa.docx")
    # os.remove("aaa.docx")

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

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

if __name__ == '__main__':
    #server.run(host='127.0.0.1', port=8888, debug=True)
    # app.run(host='192.168.18.181', port=8888, debug=True)
    app.run(
	host='172.16.18.2',
	port=8015,
	debug=True
    )

