#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pymysql
import json
from flask import Flask, render_template, request
from flask_cors import CORS

def getName(recommendId):
    connection = pymysql.connect(host='47.95.76.74', port=3306, user='root', passwd='Gongsibao2018', db='ent_data')
    cur = connection.cursor()
    sql='select company_name from tj_recommend_do_status where recommend_id = "%s"' %recommendId
    cur.execute(sql)
    s=cur.fetchone()
    print(s)
    cur.close()
    connection.close()
    return s

def getSource(name):
    connection = pymysql.connect(host='47.95.76.74', port=3306, user='root', passwd='Gongsibao2018', db='ent_data')
    cur = connection.cursor()
    sql='select preference_label from tj_label_depth_all where company_name = "%s"'%name
    print(name)
    cur.execute(sql)
    s=cur.fetchall()
    x= ''
    for ss in s:
        aa=ss[0]
        aaa=aa.replace(']','').replace('[','')
        x=json.loads(aaa)['来源偏好']

    print(x)
    cur.close()
    connection.close()
    return x



def talk(recommendId,source):
    connection = pymysql.connect(host='47.95.76.74', port=3306, user='root', passwd='Gongsibao2018', db='ent_data')
    cur = connection.cursor()
    try:
        list_test=[]
        select_name_sql='SELECT product_name FROM `tj_recommend_do_status` where recommend_id ="%s"'%(recommendId)
        #update_sql='UPDATE tj_talking t1 ,tj_recommend_do_status t2 set t1.recommend_id=t2.recommend_id where t1.recommend_product=t2.product_name'
        cur.execute(select_name_sql)
        name=cur.fetchone()
        print(name)
        name=name[0]
        print(name)
        #connection.commit()
        print(source ,'------------------')
        sa=list(source)
        print(sa)
        if source == '钉钉' and sa [0] =='阿' and sa[1] == '里' :
            select_sql='select start_text,res_text,mq_text,end_text from tj_talking where recommend_product="%s" and id<6000'%(name)
            # select_sql='select mq_text from tj_talking where  id>6000'
            cur.execute(select_sql)
            print(select_sql)
            s=cur.fetchone()
            if s:
                for i in range(0,len(s)):
                    list_test.append(s[i])
                print(list_test)
            else:
                start_text="老板，您好，我是公司宝XXX"
                list_test.append(start_text)
                res_text="我们公司宝主体是汉唐信通（北京）咨询股份有限公司拥有13年丰富企服行业经验致力于企业全生命周期的一站式服务平台。"
                list_test.append(res_text)
                list_test.append('暂无话术，敬请期待')
                end_text="好的，老板，公司宝有公司注册、财税代理、知识产权、行业资质认证、薪 税服务、公司交易多达三百余项产品，贵公司在业务开展过程中，如果有其他上述的服务需求，随时欢迎找我们。感谢您的支持。（也可以继续推荐其他套餐）"
                list_test.append(end_text)
        else:
            select_sql='select start_text,res_text,mq_text,end_text from tj_talking where recommend_product="%s" and id>6000'%name
            cur.execute(select_sql)
            print(select_sql)
            s=cur.fetchone()
            if s:
                for i in range(0,len(s)):
                    list_test.append(s[i])
                print(list_test)
            else:
                start_text="老板，您好，我是公司宝XXX"
                list_test.append(start_text)
                res_text="我们公司宝主体是汉唐信通（北京）咨询股份有限公司拥有13年丰富企服行业经验致力于企业全生命周期的一站式服务平台。"
                list_test.append(res_text)
                list_test.append('暂无话术，敬请期待')
                end_text="好的，老板，公司宝有公司注册、财税代理、知识产权、行业资质认证、薪 税服务、公司交易多达三百余项产品，贵公司在业务开展过程中，如果有其他上述的服务需求，随时欢迎找我们。感谢您的支持。（也可以继续推荐其他套餐）"
                list_test.append(end_text)
        cur.close()
        connection.close()
        return True,list_test
    except:
        cur.close()
        connection.close()
        return False,{}

def talkName(recommend_product):
    connection = pymysql.connect(host='47.95.76.74', port=3306, user='root', passwd='Gongsibao2018', db='ent_data')
    cur = connection.cursor()
    try:
        list_test=[]
        select_sql='select start_text,res_text,mq_text,end_text from tj_talking where commerce_product="%s"'%(recommend_product)
        cur.execute(select_sql)
        s=cur.fetchone()
        for i in range(0,len(s)):
            list_test.append(s[i])
        print(list_test)
        cur.close()
        connection.close()
        return True,list_test
    except:
        cur.close()
        connection.close()
        return False,{}

# 服务器接口API

def talking(server):
    @server.route('/api/talking', methods = ['POST'])
    def SingleLogoApi1():
        try:
            recommendId = request.get_json().get("recommendId")
            name = getName(recommendId)
            # name = 'tttt'
            source = getSource(name)
            print('source',source)
            isSuss, talkings = talk(recommendId, source)
            if isSuss:
                return json.dumps({"status": 0, "msg": "成功", "data": talkings}, ensure_ascii=False)
            else:
                return json.dumps({"status": -1, "msg": "返回数据为空", "data": {}}, ensure_ascii=False)
        except:
            return json.dumps({"status": -1, "msg": "调用服务出错", "data": {}}, ensure_ascii=False)






# 服务器接口API  根据推荐名字
def talking_product(server):
    @server.route('/api/talkingName', methods=['POST'])
    def SingleLogoApi():
        try:
            recommend_product = request.get_json().get("recommend_product")
            isSuss, talkings = talkName(recommend_product)
            if isSuss:
                return json.dumps({"status": 0, "msg": "成功", "data": talkings}, ensure_ascii=False)
            else:
                return json.dumps({"status": -1, "msg": "返回数据为空", "data": {}}, ensure_ascii=False)
        except:
            return json.dumps({"status": -1, "msg":"调用服务出错","data": {}}, ensure_ascii=False)


# talk("商标注册")