#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020-05-16 17:30
# @Author  : hj
# @File    : select_es_result.py
# @Software: PyCharm


from flask import request, jsonify
from elasticsearch import Elasticsearch
from service.company_basic import CompanyBase
from dao.select_hx_logo import hx_logo_Dao
from db.mod_db import DataBase


companybase = CompanyBase()


class HX:
    def __init__(self):
        self.esip = "43.247.184.94"
        self.esport = 9200
        self.index_name = "bigdata_ic_gsb_label_op"
        self.index_type = "_doc"
        self.esuser = "admines"
        self.espassword = "adminGSBes."
        self.es = Elasticsearch([self.esip], http_auth=(self.esuser, self.espassword), port=self.esport)

    def hxsearch(self,re_item,pagesize,currentpage):
        print('re_item',re_item)
        if currentpage:
            start = (currentpage - 1) * pagesize
        else:
            start = 0
        if pagesize:
            size = pagesize
        else:
            size = 4

        if re_item == []:
            querybody =  {
                "query": {
                    "bool": {
                        "must": [
                            {
                                "match_all": {}
                            }
                        ]
                    }
                },
                "from": start,
                "size": size
            }
        else:
            querybody = {
                "query": {
                    "bool": {
                        "must": [
                        ]
                    }
                },
                "from": start,
                "size": size
            }
            if "qiyeguimo" in re_item:
                dsl = {
                    "terms": {
                        "qiyeguimo": re_item['qiyeguimo']
                    }
                }
                querybody["query"]["bool"]["must"].append(dsl)

            if 'qiyeleixing' in re_item:
                dsl = {
                    "terms": {
                        "qiyeleixing": re_item['qiyeleixing']
                    }}
                querybody['query']['bool']['must'].append(dsl)

            if 'chenglinianxian' in re_item:
                years_value = re_item['chenglinianxian']
                re_years_value_list = []
                for years in years_value:
                    if years[0:4] in ['青年公司', '长青公司', '成熟公司', '长寿公司']:
                        re_years_value = years[0:4]
                    else:
                        re_years_value = years[0:3]
                    re_years_value_list.append(re_years_value)
                dsl = {
                    "terms": {
                        "chenglinianxian": re_years_value_list

                    }
                }
                querybody['query']['bool']['must'].append(dsl)

            if 'hangyeleibie' in re_item:
                dsl = {
                    "terms": {
                        "hangyeleibie": re_item['hangyeleibie']
                    }
                }
                querybody['query']['bool']['must'].append(dsl)

            if 'jingyingzhuangtai' in re_item:
                dsl = {
                    "terms": {
                        "jingyingzhuangtai": re_item['jingyingzhuangtai']
                    }
                }
                querybody['query']['bool']['must'].append(dsl)

            if 'jingyinghangye' in re_item:
                dsl = {
                    "terms": {
                        "jingyinghangye": re_item['jingyinghangye']
                    }
                }
                querybody['query']['bool']['must'].append(dsl)

            if 'jingyingdiqu' in re_item:
                dsl = {
                    "terms": {
                        "jingyingdiqu": re_item['jingyingdiqu']
                    }
                }
                querybody['query']['bool']['must'].append(dsl)

            if 'fengongsishuliang' in re_item:
                branches = re_item['fengongsishuliang']
                re_branches_list = []
                for branch_item in branches:
                    if branch_item[0:4] in ['枝繁叶茂', '草木稀疏', '一枝独秀']:
                        re_branches = branch_item[0:4]
                    else:
                        re_branches = branch_item
                    re_branches_list.append(re_branches)
                dsl = {
                    "terms": {
                        "fengongsishuliang": re_branches_list
                    }
                }
                querybody['query']['bool']['must'].append(dsl)


            if 'zhuanli' in re_item:
                patent_nu = re_item['zhuanli']
                for zhuanli_item in patent_nu:
                    if zhuanli_item[0:2] == '专利':
                        re_patent_nu = zhuanli_item[0:4]
                    else:
                        re_patent_nu = zhuanli_item[0:4]
                    dsl = {
                        "wildcard": {
                            'zhuanli': "*" + re_patent_nu + "*"
                        }
                    }
                    querybody['query']['bool']['must'].append(dsl)

            if 'shangbiao' in re_item:
                trademark = re_item['shangbiao']
                for trademark_item in trademark:
                    if trademark_item[0:2] == '商标':
                        re_trademark = trademark_item[0:2]
                    else:
                        re_trademark = trademark_item[0:2]
                    dsl = {
                        "wildcard": {
                            "shangbiao": "*" + re_trademark + "*"
                        }
                    }
                    querybody['query']['bool']['must'].append(dsl)

            if 'zuopinzhuzuoquan' in re_item:
                work_nu = re_item['zuopinzhuzuoquan']
                for work_item in work_nu:
                    if work_item[0:4] == '作品著作':
                        re_work_nu = work_item[0:4]
                    else:
                        re_work_nu = work_item[0:4]
                    dsl = {
                        "wildcard": {
                            "zuopinzhuzuoquan": "*" + re_work_nu + "*"
                        }
                    }
                    querybody['query']['bool']['must'].append(dsl)

            if 'suozaidiqu' in re_item:
                address_nu = re_item['suozaidiqu']
                for address_item in address_nu:
                    dsl = {
                        "wildcard": {
                            "suozaidiqu": "*" + address_item + "*"
                        }
                    }
                    querybody['query']['bool']['must'].append(dsl)

            if 'ruanjianzhuzuoquan' in re_item:
                soft_nu = re_item['ruanjianzhuzuoquan']
                for soft_item in soft_nu:
                    soft_label = soft_item[0:4]
                    dsl = {
                        "wildcard": {
                            "ruanjianzhuzuoquan": "*" + soft_label + "*"
                        }
                    }
                    querybody['query']['bool']['must'].append(dsl)

            if 'zhengzhao' in re_item:
                cliense_nu = re_item['zhengzhao']
                dsl = {
                    "terms": {
                        "zhengzhao": cliense_nu
                    }
                }
                querybody['query']['bool']['must'].append(dsl)

            if 'chanpindalei' in re_item:
                product_cateory = re_item['chanpindalei']
                dsl = {
                    "terms": {
                        "chanpindalei": product_cateory
                    }
                }
                querybody['query']['bool']['must'].append(dsl)


            if 'fengxian' in re_item:
                fengxian_label = re_item['fengxian']
                dsl = {
                    "terms": {
                        "risk_label": fengxian_label
                    }
                }
                querybody['query']['bool']['must'].append(dsl)

        print('查询语法：', querybody)
        searched = self.es.search(index=self.index_name, doc_type=self.index_type, body=querybody)
        es_company_info = {}
        company_hx_list = []
        if (searched["hits"]["total"] > 0):
            for row in searched["hits"]["hits"]:
                company_name = row['_source']["companyname"]
                company_hx_list.append(company_name)
                total = searched["hits"]["total"]
                es_company_info['company_hx_list'] = company_hx_list
                es_company_info['total'] = total

        return es_company_info

    def select_url(self,company_name):
        hx_logo_address = '暂无logo'
        try:
            logo_url = hx_logo_Dao()
            logo_info = logo_url.select_hx_logo(company_name)
            for row in logo_info:
                print(logo_info,"oooo")
                id = row['id']
                company_name = row['company_name']
                hx_logo_address = row['company_logo_url']
        finally:
            DataInfo = DataBase()
            DataInfo.close()
        return hx_logo_address

hx = HX()


# 画像检索接口
def hx_company_dict(server):
    @server.route('/gsb/api/hx_dict', methods=['POST'])
    def hx_dict_select():
        print(22)
        if request.method == 'POST':
            requestdata = request.json
            company_name = requestdata.get('company_name')
            print(type(company_name), 0000)
            try:
                base_result = companybase.companyinfo(company_name)
                logo_url = hx.select_url(company_name)
                if base_result:
                    base_result['logo'] = logo_url
                else:
                    base_result = "暂无符合条件的商机，请您修改条件进行检索！"
                return {"status": 200, "msg": "成功", "data": base_result}
            except:
                return {"status": 404, "msg": "成功", "data": "暂无符合条件的商机，请您修改条件进行检索！"}





def hx_company_list(server):
    @server.route('/gsb/api/hx_list', methods=['POST'])
    def hx_select_main():
        if request.method == 'POST':
            requestdata = request.json
            print('requestdata',requestdata)
            total = ""
            select_filter = requestdata.get('select_filter')
            pagesize = requestdata.get('pagesize')
            currentpage = requestdata.get('currentpage')
            try:
                base_result_list = []
                re_item = {}
                if requestdata != []:
                    for item in select_filter:
                        name = item['name']
                        list = item['list']
                        re_item[name] = list
                    es_company_info = hx.hxsearch(re_item,pagesize,currentpage)
                    for company_name in es_company_info['company_hx_list']:
                        base_result = companybase.companyinfo(company_name)
                        logo_url = hx.select_url(company_name)
                        if base_result:
                            base_result['logo'] = logo_url
                            base_result_list.append(base_result)
                            total = es_company_info['total']
                            print("len_result",len(base_result_list))
                        else:
                            base_result_list = "暂无该检索信息，请您修改条件进行检索！"

                else:
                    es_company_info = hx.hxsearch(select_filter,pagesize,currentpage)
                    for company_name in es_company_info['company_hx_list']:
                        base_result = companybase.companyinfo(company_name)
                        if base_result:
                            logo_url = hx.select_url(company_name)
                            base_result['logo'] = logo_url
                            base_result_list.append(base_result)
                            total = es_company_info['total']
                            print("len_result", len(base_result_list))
                        else:
                            base_result_list = "暂无该检索信息，请您修改条件进行检索！"
            except:
                base_result_list = "暂无该检索信息，请您修改条件进行检索！"
            return {"status": 200, "msg": "成功", "data": base_result_list,"total":total}
