#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020-05-16 17:30
# @Author  : hj
# @File    : zhengce-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.esip = "43.247.184.94"
        self.esport = 9200
        self.index_name = "bigdata_ic_gsb_label"
        self.index_type = "_doc"
        self.esuser = "admines"
        self.espassword = "adminGSBes."
        self.es = Elasticsearch([self.esip], http_auth=(self.esuser, self.espassword), port=self.esport)
        # self.es = Elasticsearch([self.esip], port=self.esport)

    def hxsearch(self,re_item):
        querybody = {
            "query": {
                "bool": {
                    "must": [
                    ]
                }
            },
            "size": 2000,
        }

        if "qiyeguimo" in re_item:
            dsl = {
                "terms": {
                    "qiyeguimo.raw": re_item['qiyeguimo']
                }
            }
            querybody["query"]["bool"]["must"].append(dsl)
        # print(querybody, 111)

        if 'qiyeleixing' in re_item:
            dsl = {
                "terms": {
                    "qiyeleixing.raw": 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)
            # print(re_years_value_list, 111)
            dsl = {
                "terms": {
                    "chenglinianxian.raw": re_years_value_list

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


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

        if 'jingyingdiqu' in re_item:
            dsl = {
                "terms": {
                    "jingyingdiqu.raw": 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.raw": re_branches_list
                }
            }
            querybody['query']['bool']['must'].append(dsl)

        if 'zhengzhao' in re_item:
            dsl = {
                "terms": {
                    "zhengzhao.raw": re_item['zhengzhao']
                }
            }

            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.raw': "*" + 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.raw": "*" + 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.raw": "*" + 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.raw": "*" + 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.raw": "*" + soft_label + "*"
                    }
                }
                querybody['query']['bool']['must'].append(dsl)

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


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

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


        if 'fengxian' in re_item:
            fengxian_label = re_item['fengxian']
            dsl = {
                "terms": {
                    "risk_label.keyword": 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, request_timeout=1000)
        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)
        return company_hx_list

    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)
                base_result['logo'] = logo_url
                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, 1121212)
            base_result = ""
            re_item = {}
            # try:
            for item in requestdata:
                name = item['name']
                list = item['list']
                re_item[name] = list
                company_hx_list = hx.hxsearch(re_item)
                base_result_list = []
                for company_name in company_hx_list:
                    base_result = companybase.companyinfo(company_name)
                    logo_url = hx.select_url(company_name)
                    base_result['logo'] = logo_url
                    base_result_list.append(base_result)
                    print("len_result",len(base_result_list))
            # except:
            #     base_result = [{
            #         "company_name": "北京晟软在线科技有限公司",
            #         "business_scope": "技术开发、技术转让、技术咨询、技术服务;计算机系统服务;应用软件服务;软件开发。(企业依法自主选择经营项目,开展经营活动;依法须经批准的项目,经相关部门批准后依批准的内容开展经营活动;不得从事本市产业政策禁止和限制类项目的经营活动。)",
            #         "reg_unit": "100.000",
            #         "establish_time": "2010-11-03",
            #         "legal_person_name": "赵学军",
            #         "reg_location": "北京市海淀区中关村软件园11号楼3层330",
            #         "logo": "https://gsb-zc.oss-cn-beijing.aliyuncs.com/北京晟软在线科技有限公司.png"
            #     }, {
            #         "company_name": "北京游逗科技有限公司",
            #         "business_scope": "技术推广服务;票务代理(不含航空机票销售代理);旅游信息咨询(不含中介服务);酒店管理;风景名胜区规划;企业形象策划;企业管理咨询(不含中介服务);应用软件服务(不含医用软件服务);销售计算机、软件及辅助设备、电子产品、通讯设备;计算机系统服务。(企业依法自主选择经营项目,开展经营活动;依法须经批准的项目,经相关部门批准后依批准的内容开展经营活动;不得从事本市产业政策禁止和限制类项目的经营活动。)",
            #         "reg_unit": "200.000",
            #         "establish_time": "2017-11-27",
            #         "legal_person_name": "王京",
            #         "reg_location": "北京市丰台区程庄北里13号楼二层207室",
            #         "logo": "暂无logo"
            #     }, {
            #         "company_name": "北京码农村科技有限公司",
            #         "business_scope": "技术开发、技术转让、技术咨询、技术推广、技术服务;计算机系统服务;软件开发;电脑动画设计;经济贸易咨询;企业策划;企业管理咨询;销售自行开发后的产品。(企业依法自主选择经营项目,开展经营活动;依法须经批准的项目,经相关部门批准后依批准的内容开展经营活动;不得从事本市产业政策禁止和限制类项目的经营活动。)",
            #         "reg_unit": "100.000",
            #         "establish_time": "2016-07-06",
            #         "legal_person_name": "白冰",
            #         "reg_location": "北京市海淀区高里掌路1号院6号楼104-165",
            #         "logo": "暂无logo"
            #     }]
            print(base_result_list, 111)
            return {"status": 200, "msg": "成功", "data": base_result_list}
