from flask import request
import json
from dao.tf_member_dao import tf_member_Dao
from dao.tf_member_es import tf_member_Es
from db.mod_db import DataBase

def getdbdata_gg(input_name):
    tf_memberInfo = tf_member_Dao()
    gaoguan = tf_memberInfo.select_sql_1(input_name)
    # DataInfo = DataBase()
    # DataInfo.close()
    return gaoguan


def record2jsion_gg(query_data):
    jsonData = []
    output = []
    for row in query_data:
        data = {}
        data['company_name'] = str(row[0])
        data['member_name'] = str(row[1])
        data['member_position'] = str(row[2])
        jsonData.append(data)
        jsondatar = json.dumps(jsonData, ensure_ascii=False)
        output = jsondatar
    return output


def getdbdata_gd(input_name):
    tf_memberInfo = tf_member_Dao()
    gudong = tf_memberInfo.select_sql_2(input_name)
    # DataInfo = DataBase()
    # DataInfo.close()
    return gudong


def record2jsion_gd(query_data):
    jsonData = []
    output = []
    for row in query_data:
        data = {}
        data['company_name'] = str(row[0])
        data['shareholder_name'] = str(row[1])
        data['subscription_funds'] = str(row[2])
        data['turn_funds'] = str(row[3])
        data['subscript_type'] = str(row[4])
        data['subscrip_time'] = str(row[5])
        jsonData.append(data)
        jsondatar = json.dumps(jsonData, ensure_ascii=False)
        output = jsondatar
    return output

def Get_Data_By_Body(index_name,company_name):
    tf_memberInfo = tf_member_Es()
    # doc = {"query":{"match": {"companyName":"北京华泰丽成智能科技有限公司"}}}
    temp = []
    _searched = tf_memberInfo.Get_Data_By_Body_1(index_name,company_name)
    for hit in _searched['hits']['hits']:
        print("Got %d Hits:" % _searched['hits']['total'])
        # print (hit['_source'])
        # print (hit['_source']['companyName'])
        t = hit['_source']
        temp.append(t)
        # tt=es_records[0]['_source']
        # print(tt)
        # print(json.dumps(es_records,ensure_ascii=False))
    tt = temp
    return tt  # [tt]

def Get_Data_By_Body_Input( index_name,match_field, field_cotent):
    # doc = {"query": {"match": {match_field: field_cotent}}}
    # doc = {"query":{"match": {"companyName":"北京华泰丽成智能科技有限公司"}}}
    # _searched = es.search(index=index_name, body=doc)
    tf_memberInfo = tf_member_Es()
    _searched = tf_memberInfo.Get_Data_By_Body_2(index_name,match_field, field_cotent)
    temp = []
    for hit in _searched['hits']['hits']:
        # print("Got %d Hits:" % _searched['hits']['total'])
        # print (hit['_source'])
        # print (hit['_source']['companyName'])
        t = hit['_source']
        temp.append(t)
        # tt=es_records[0]['_source']
        # print(tt)
        # print(json.dumps(es_records,ensure_ascii=False))
    tt = temp
    return tt  # [tt]

def Get_Data_Return_Body_ID(index_name,match_field, field_cotent):
    tf_memberInfo = tf_member_Es()
    _searched = tf_memberInfo.Get_Data_By_Body_2(index_name,match_field, field_cotent)
    temp = []
    for hit in _searched['hits']['hits']:
        t = hit['_id']
        temp.append(t)
    tt = temp
    return tt


def search_gaoguan(input_company_name):
    match_field_0 = 'company_name'
    field_cotent_0 = input_company_name
    # field_cotent_0='北京非常满意科技有限公司'
    # field_cotent1='83468156'
    company_id = Get_Data_Return_Body_ID("bigdata_ic_gsb_company_04",match_field_0, field_cotent_0)  # 返回查询结果
    # print('OK--company_info->\n')
    # print(company_id)

    if company_id:
        match_field1 = 'company_id'
        # field_cotent1='83468156'
        field_cotent1 = company_id[0]
        staff_info = Get_Data_By_Body_Input("bigdata_ic_gsb_staff", match_field1, field_cotent1)  # 返回查询结果
        for num in staff_info:
            # print(num['branch_id'])
            pass

        for i in range(0, len(staff_info)):
            if staff_info[i]:
                ss = Get_Data_By_Body_Input("bigdata_ic_gsb_human",'id', staff_info[i]['staff_id'])  # 返回子查询结果
                if ss[0]['name']:  # 返回值不为空
                    staff_info[i]['staff_id'] = ss[0]['name']  # 替换相应的值
            else:
                print('no data!')
        finall_key = {'company_id', 'staff_id', 'staff_type_name'}
        finall_info = []
        for j in range(0, len(staff_info)):
            staff_info[j]['company_id'] = field_cotent_0
            finall_info.append({key: value for key, value in staff_info[j].items() if key in finall_key})
            finall_info[j].update({'company_name': finall_info[j].pop('company_id')})  # 修改键名
            finall_info[j].update({'member_name': finall_info[j].pop('staff_id')})
            finall_info[j].update({'member_position': finall_info[j].pop('staff_type_name')})
    return finall_info


def search_gudong(input_company_name):
    match_field_0 = 'company_name'
    field_cotent_0 = input_company_name
    annual_id = Get_Data_Return_Body_ID("bigdata_ic_gsb_annualreport",match_field_0, field_cotent_0)  # 返回查询结果
    match_field1 = 'annual_report_id'


    for i in range(0, len(annual_id)):
        order_annual_id = sorted(annual_id, reverse=True)
        field_cotent1 = order_annual_id[i]
        company_shareholder = Get_Data_By_Body_Input("bigdata_ic_gsb_shareholder_1",match_field1, field_cotent1)  # 返回查询结果
        if company_shareholder:
            break


    finall_key = {'gsb_company_name', 'investor_name', 'subscribe_amount', 'subscribe_time', 'subscribe_type',
                  'paid_amount', 'paid_time', 'paid_type'}
    finall_info = []
    for j in range(0, len(company_shareholder)):
        company_shareholder[j]['gsb_company_name'] = field_cotent_0
        finall_info.append({key: value for key, value in company_shareholder[j].items() if key in finall_key})
        finall_info[j].update({'company_name': finall_info[j].pop('gsb_company_name')})
        finall_info[j].update({'shareholder_name': finall_info[j].pop('investor_name')})
        finall_info[j].update({'subscription_funds': finall_info[j].pop('subscribe_amount')})
        finall_info[j].update({'turn_funds': finall_info[j].pop('paid_amount')})
        finall_info[j].update({'subscript_type': finall_info[j].pop('subscribe_type')})
        finall_info[j].update({'subscrip_time': finall_info[j].pop('subscribe_time')})
        finall_info[j].update({'ture_subscrpt_time': finall_info[j].pop('paid_time')})
        finall_info[j].update({'ture_subscript_type': finall_info[j].pop('paid_type')})
    return finall_info  # json.dumps(finall_info,ensure_ascii=False)

def search_annual_report(input_company_name):
    match_field_0='company_name'
    field_cotent_0=input_company_name
    #field_cotent1='83468156'  2914053007
    annual_id = Get_Data_By_Body_Input("bigdata_ic_gsb_annualreport", match_field_0, field_cotent_0)  # 返回查询结果
    #print('OK--company_info->\n')
    #print(annual_id[0])
    finall_key={'company_id','report_year','company_name','usc_code','reg_number','phone_number','post_code', 'post_address','email','manage_state','employee_number'}
    finall_info=[]
    for j in range(0,len(annual_id)):
        finall_info.append({key: value for key, value in annual_id[j].items()  if key in finall_key})
    #print('\n')
    #print(finall_info[0])
    report_year_unique=[]
    for kk in range(0,len(finall_info)):
        if finall_info[kk]['report_year'] not in report_year_unique:
            report_year_unique.append(finall_info[kk]['report_year'])
    report_year_unique=sorted(report_year_unique,reverse=True)
    #print(report_year_unique)
    finall_info_unique=[]
    for ll in report_year_unique:
        #print(ll)
        for mm in range(0,len(finall_info)):
            if finall_info[mm]['report_year']==ll:
                finall_info_unique.append(finall_info[mm])
                break
    #print(finall_info_unique)
    #print('OK--final_info->\n')
    return finall_info_unique#json.dumps(finall_info_unique,ensure_ascii=False)



def gaoguan(server):
    @server.route('/api/gaoguan', methods=['POST'])
    def index():
        if request.method == 'POST':
            request_data = request.json
            inputs = request_data.get('company_name')
            # gaoguan=getdbdata_gg(inputs)
            annual_report = search_gaoguan(inputs)
            # json.dumps(annual_report, ensure_ascii=False)
            # outputs=record2jsion_gg(gaoguan)
            return json.dumps(annual_report, ensure_ascii=False)  # gaoguan #outputs


'''def index():
    if request.method=='POST':
        request_data=request.json
        inputs=request_data.get('company_name')
        gaoguan=getdbdata_gg(inputs)
        outputs=record2jsion_gg(gaoguan)
        return outputs'''

def gudong(server):
    @server.route('/api/gudong', methods=['POST'])
    def indexx():
        if request.method == 'POST':
            request_data = request.json
            inputs = request_data.get('company_name')
            gudong = search_gudong(inputs)
            return json.dumps(gudong, ensure_ascii=False)

def nianbao(server):
    @server.route('/api/nianbao', methods=['POST'])
    def indexxx():
        if request.method == 'POST':
            request_data = request.json
            inputs = request_data.get('company_name')
            gudong = search_annual_report(inputs)
            return json.dumps(gudong, ensure_ascii=False)


'''def indexx():
    if request.method=='POST':
        request_data=request.json
        inputs=request_data.get('company_name')
        gaoguan=getdbdata_gd(inputs)
        outputs_gd=record2jsion_gd(gaoguan)
        return outputs_gd '''

'''
def index():
    gaoguan=getdbdata(input_name)
    output=record2jsion(gaoguan)
    return output'''





