#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/2/11 10:02
# @Author  : fanhui
# @File    : risk_to_word.py
# @Software: PyCharm

from getcompanyinfofromES import GetComanyinfoFromES
from GetFIinfoFromJson import GetFIinfoFromJson
from GetRiskinfoFromJson import Riskinfo
import time,requests,oss2,sys,os,json
from flask import Flask ,request
from docxtpl import DocxTemplate,InlineImage
from docx.shared import Mm
from pyecharts.charts import Gauge
from pyecharts.render import make_snapshot
from snapshot_selenium import snapshot
from pyecharts import options as opts
from flask_cors import *

server = Flask(__name__)
interface_path = os.path.dirname(__file__)
sys.path.insert(0, interface_path)  # 将当前文件的父目录加入临时系统变量
server.config['JSON_AS_ASCII'] = False
CORS(server, supports_credentials=True)  # 跨域请求



# 生成图片
def charts(datalist, charttype, pngpath):
    try:
        img = None
        if charttype == 1:  # 仪表盘
            img = Gauge(init_opts=opts.InitOpts(width="450px", height="450px"))
            img.add("", [(datalist[0]["key"], datalist[0]["value"])],
                axisline_opts=opts.AxisLineOpts(linestyle_opts=opts.LineStyleOpts(color=[(0.3, "#67e0e3"), (0.7, "#37a2da"), (1, "#fd666d")], width=35)),
                label_opts=opts.LabelOpts(font_size=55,formatter="{value}%"))
        if img:
            make_snapshot(snapshot, img.render(), pngpath)
            return True
        else:
            return False
    except Exception as e:
        print(e)
        return False


#生成报告(es工商、财务信息、风险监测（仪表盘图）)
def WriteReport(Else_info,Companyinfo,Fi_dict,Risk_info):
    tpl = DocxTemplate('tax_word_model.docx')
    context={}
    #其他传入参数
    context['CreatTime']=Else_info['CreatTime']
    context['Detection_zone'] = Else_info['Detection_zone']
    #01-02工商
    context['template'] =Companyinfo["companyname"]
    context['legal_person'] =Companyinfo["legal_person"]
    context['cred_code'] =Companyinfo["cred_code"]
    context['province'] =Companyinfo["province"]
    context['city'] =Companyinfo["city"]
    context['reg_location'] =Companyinfo["reg_location"]
    context['establish_time'] =Companyinfo["establish_time"]
    context['company_cate_1'] =Companyinfo["company_cate_1"]
    context['company_org_type'] =Companyinfo["company_org_type"]
    context['reg_institute'] =Companyinfo["reg_institute"]
    context['reg_capital'] =Companyinfo["reg_capital"]
    context['reg_status'] =Companyinfo["reg_status"]
    context['from_time'] =Companyinfo["from_time"]
    context['to_time'] =Companyinfo["to_time"]
    context['approved_time'] =Companyinfo["approved_time"]
    context['business_scope'] =Companyinfo["business_scope"]
    #03-05财务信息
    context["Bq_time"] = Fi_dict["Bq_time"]
    context["Sq_time"] = Fi_dict["Sq_time"]
    context["Bq_Total_trade_income"] = Fi_dict["Bq_Total_trade_income"]
    context["Sq_Total_trade_income"] = Fi_dict["Sq_Total_trade_income"]
    context["change_rate_1"] = Fi_dict["change_rate_1"]
    context["Bq_Total_profit"] = Fi_dict["Bq_Total_profit"]
    context["Sq_Total_profit"] = Fi_dict["Sq_Total_profit"]
    context["change_rate_2"] = Fi_dict["change_rate_2"]
    context["Bq_Net_profit"] = Fi_dict["Bq_Net_profit"]
    context["Sq_Net_profit"] = Fi_dict["Sq_Net_profit"]
    context["change_rate_3"] = Fi_dict["change_rate_3"]
    context["Bq_Total_Liabilities"] = Fi_dict["Bq_Total_Liabilities"]
    context["Sq_Total_Liabilities"] = Fi_dict["Sq_Total_Liabilities"]
    context["change_rate_4"] = Fi_dict["change_rate_4"]
    context["Bq_Owner_rights"] = Fi_dict["Bq_Owner_rights"]
    context["Sq_Owner_rights"] = Fi_dict["Sq_Owner_rights"]
    context["change_rate_5"] = Fi_dict["change_rate_5"]
    context["Bq_Total_sales"] = Fi_dict["Bq_Total_sales"]
    context["Sq_Total_sales"] = Fi_dict["Sq_Total_sales"]
    context["change_rate_6"] = Fi_dict["change_rate_6"]
    context["Bq_Total_assets"] = Fi_dict["Bq_Total_assets"]
    context["Sq_Total_assets"] = Fi_dict["Sq_Total_assets"]
    context["change_rate_7"] = Fi_dict["change_rate_7"]
    context["Bq_Total_liabilities_and_Owner_rights"] = Fi_dict["Bq_Total_liabilities_and_Owner_rights"]
    context["Sq_Total_liabilities_and_Owner_rights"] = Fi_dict["Sq_Total_liabilities_and_Owner_rights"]
    context["Bq_sales_expense"] = Fi_dict["Bq_sales_expense"]
    context["Sq_sales_expense"] = Fi_dict["Sq_sales_expense"]
    context["Bq_Net_interest_rate"] = Fi_dict["Bq_Net_interest_rate"]
    context["Sq_Net_interest_rate"] = Fi_dict["Sq_Net_interest_rate"]
    context["Bq_Equity_ratio"] = Fi_dict["Bq_Equity_ratio"]
    context["Sq_Equity_ratio"] = Fi_dict["Sq_Equity_ratio"]
    context["Bq_Gearing_ratio"] = Fi_dict["Bq_Gearing_ratio"]
    context["Sq_Gearing_ratio"] = Fi_dict["Sq_Gearing_ratio"]
    context["Bq_sales_growth_rate"] = Fi_dict["Bq_sales_growth_rate"]
    context["Sq_sales_growth_rate"] = Fi_dict["Sq_sales_growth_rate"]
    context["Bq_Net_profit_growth_rate"] = Fi_dict["Bq_Net_profit_growth_rate"]
    context["Sq_Net_profit_growth_rate"] = Fi_dict["Sq_Net_profit_growth_rate"]
    context["Bq_total_assets_growth_rate"] = Fi_dict["Bq_total_assets_growth_rate"]
    context["Sq_total_assets_growth_rate"] = Fi_dict["Sq_total_assets_growth_rate"]


    # 06仪表盘图（需获取评分grade）
    grades1 = Risk_info["RiskA"]["score"].replace('%', "")
    grades2 = Risk_info["MRisk"]["score"].replace('%', "")
    grades3 = Risk_info["ARisk"]["score"].replace('%', "")
    guage1 = ""
    guage2 = ""
    guage3 = ""
    if charts([{"key": "风险异常比例", "value": grades1}], 1, "yibiaopan1.png"):
        guage1 = "yibiaopan1.png"
    if charts([{"key": "被监测风险", "value": grades2}], 1, "yibiaopan2.png"):
        guage2 = "yibiaopan2.png"
    if charts([{"key": "被稽查风险", "value": grades3}], 1, "yibiaopan3.png"):
        guage3 = "yibiaopan3.png"
    context['guage1'] = InlineImage(tpl, guage1, width=Mm(60))
    context['guage2'] = InlineImage(tpl, guage2, width=Mm(60))
    context['guage3'] = InlineImage(tpl, guage3, width=Mm(60))
    context['RiskA_desc'] ="企业风险异常同比其他企业比例较低"
    context['MRisk_desc'] = "企业风险异常同比其他企业比例较低"
    context['ARisk_desc'] = "企业风险异常同比其他企业比例较低"
    # 风险信息
    context["RiskA_desc"] = Risk_info["RiskA"]["describe"]
    context["MRisk_desc"] = Risk_info["MRisk"]["describe"]
    context["ARisk_desc"] = Risk_info["ARisk"]["describe"]
    context["describe_info"] = Risk_info["info"]["describe"]
    #细分风险项
    context["IT_YCSR_Risk_desc"] = str(Risk_info["Risk_IT_YCSR"]["describe"]).replace("['","").replace("']","").replace("'","")
    context["IT_XZFY_Risk_desc"] = str(Risk_info["Risk_IT_XZFY"]["describe"]).replace("['","").replace("']","").replace("'","")
    context["IT_XZCB_Risk_desc"] = str(Risk_info["Risk_IT_XZCB"]["describe"]).replace("['","").replace("']","").replace("'","")
    context["VAT_XKFP_Risk_desc"] = str(Risk_info["Risk_VAT_XKFP"]["describe"]).replace("['","").replace("']","").replace("'","")
    context["VAT_YCXX_Risk_desc"] = str(Risk_info["Risk_VAT_YCXX"]["describe"]).replace("['","").replace("']","").replace("'","")
    context["VAT_XZJX_Risk_desc"] = str(Risk_info["Risk_VAT_XZJX"]["describe"]).replace("['","").replace("']","").replace("'","")
    context["CT_FX_Risk_desc"] = str(Risk_info["Risk_CT_FX"]["describe"]).replace("['","").replace("']","").replace("'","")
    context["ALLT_FX_Risk_desc"] = str(Risk_info["Risk_ALLT_FX"]["describe"]).replace("['","").replace("']","").replace("'","")

    tpl.render(context)
    addr = "/tmp/TaxRiskReport.docx"
    # addr = "G://TaxRiskReport26.docx"
    tpl.save(addr)
    print(addr,"+++++++++")
    return addr


def put2oss(report):
    # 阿里云接口地址
    endpoint = 'http://oss-cn-beijing.aliyuncs.com'
    auth = oss2.Auth('LTAIyAUK8AD04P5S', 'DHmRtFlw2Zr3KaRwUFeiu7FWATnmla')
    bucket = oss2.Bucket(auth, endpoint, 'gsb-zc')
    current_file_path = "TaxRiskReport.docx"
    current_fold = time.strftime('%Y%m%d%H%M%S', time.localtime())
    p = str(current_fold) + "_" + current_file_path
    bucket.put_object_from_file(p, report)
    addr="https://gsb-zc.oss-cn-beijing.aliyuncs.com/"+p
    return addr

#全半角转化函数
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 UpdateTaskRptUrl(batchid, rptUrl):
    url = 'https://fkctlapi.gongsibao.com/api/rpt/rptApi/updateTaskRptUrl'  # 获取更新报告接口
    report_addr = {"batchid": batchid, "rptUrl": rptUrl}  # 根据任务号进行接口访问参数
    UpdateInfo = requests.post(url, report_addr)  #传参并访问接口
    companyInfo_New = json.loads(UpdateInfo.text)# 访问接口返回的信息
    print(companyInfo_New)
    if companyInfo_New["msg"]=="操作成功":
        return batchid+"报告已更新完成"
    else:
        return batchid+"报告更新失败"




# 风险监测自动报告接口
@server.route('/gsb/api/report2', methods=['POST'])
def report():
    if request.method =='POST':
        print("=======调用风险检测自动报告接口")
        data = request.json
        json_str = json.dumps(data)
        GetAllinfo = json.loads(json_str)
        companyname=GetAllinfo["company_name"] #获取监测企业名称
        batchid=GetAllinfo["Task_Num"] #获取任务号
        companyname = strQ2B(companyname)
        if companyname:
            Companyinfo=GetComanyinfoFromES(companyname) #根据输入公司名获取工商信息
            Else_info, Fi_dict=GetFIinfoFromJson(GetAllinfo)#获取输入其他信息和财务信息
            Risk_info=Riskinfo(GetAllinfo)#计算风险项
            report = WriteReport(Else_info,Companyinfo,Fi_dict,Risk_info) #将工商、财务、风险三部分内容写入word中
            rptUrl = put2oss(report) # 上传文件到oss上
            print("报告已生成",rptUrl)
            result=UpdateTaskRptUrl(batchid, rptUrl)# 完成后调用接口，通知服务已完成
            return result
        else:
            return "请输入检测公司名称"



server.run(host='0.0.0.0', port=80, debug=True)
