from dao.ic_gsb_branch_es import BranchEs
from dao.company_es import CompanyEs
from common import time_trans
import time, datetime

class CompanyBase:
    companyes = CompanyEs()
    branches = BranchEs()

    #企业分支机构
    def companybranch(self,company_name):

        company_branchs = []
        branch_result = self.branches.select_branch(company_name)
        for item in branch_result['hits']['hits']:
            # print(item)
            # print(item['_id'])
            company_branchs.append(item['_source']['branch_name'])

        return company_branchs

    def array_time(self,data):
        print(int(data))
        timeArray = time.localtime(int(data))

        otherStyleTime = time.strftime("%Y-%m-%d ", timeArray)
        return otherStyleTime

    #查询企业基本信息
    def companyinfo(self,company_name):
        company_dict = {}
        company_result = self.companyes.select_baise(company_name)
        if company_result:
            for row in company_result['hits']['hits']:
                company_dict["companyname"] = row['_source']["company_name"]  # 企业名称
                company_dict["gsb_province"] = row['_source']["base"]  # 所属省
                company_dict["gsb_shi"] = row['_source']["gsb_city"]  # 所属城市或者区
                company_dict["legal_persion"] = row['_source']["legal_person"]  # 法定代表人
                company_dict["reg_capital"] = row['_source']["reg_capital"]  # 注册资本
                company_dict["reg_unit"] = row['_source']["reg_unit"]  # 注册资本单位（万人民币）
                company_dict["reg_status"] = row['_source']["reg_status"]  # 营业状态
                company_dict['estiblish_time'] = row['_source']["estiblish_time"]  # 社会统一性代码
                print(row['_source']["estiblish_time"], "====")
                if row['_source']["estiblish_time"] != None and row['_source']["estiblish_time"] != "null":
                    company_dict["estiblish_time"] = row["_source"]["estiblish_time"]  # 成立时间（原本时间戳格式）
                company_dict["company_org_type"] = row['_source']["company_org_type"]  # 企业类型
                company_dict["gsb_company_cate_1"] = row['_source']["gsb_company_cate_1"]  # 所属行业大类
                company_dict["gsb_company_cate_2"] = row['_source']["gsb_company_cate_2"]  # 所属行业中类
                company_dict["gsb_company_cate_3"] = row['_source']["gsb_company_cate_3"]  # 所属行业小类
                company_dict["business_scope"] = row['_source']["business_scope"]  # 企业经营范围

                company_dict['reg_number'] = row['_source']["reg_number"]  # 社会统一性代码
                company_dict['from_time'] = row['_source']["from_time"]  # 社会统一性代码
                company_dict['credit_code'] = row['_source']["credit_code"]  # 社会统一性代码
                if row['_source']["from_time"] != None and row['_source']["from_time"] != "null":
                    company_dict['from_time'] = self.array_time(
                        time_trans.TimestampChange(row['_source']["from_time"], 0)[0])  # 起时间
                company_dict['to_time'] = row['_source']["to_time"]  # 社会统一性代码
                if row['_source']["to_time"] != None and row['_source']["to_time"] != "null":
                    company_dict['to_time'] = self.array_time(
                        time_trans.TimestampChange(row['_source']["to_time"], 0)[0])  # 止时间
                company_dict['reg_institute'] = row['_source']["reg_institute"]  # 注册地址
                company_dict["reg_capital"] = row['_source']["reg_capital"]  # 注册资本单位（万人民币）
                company_dict['reg_location'] = row['_source']["reg_location"]  # 公司地址
                company_dict['company_org_type'] = row['_source']["company_org_type"]  # 公司地址

            return company_dict
    #查找相似企业
    def similar_company(self,cinfo,company_name):
        querybody = self.companyes.select_company_body()
        print(querybody,2222)
        if cinfo["reg_status"]:
            dsl = {"terms": {"reg_status": ['存续', "在业"]}}
            querybody['query']['bool']['must'].append(dsl)
        if cinfo["gsb_company_cate_1"]:
            dsl = {"term": {"gsb_company_cate_1": cinfo["gsb_company_cate_1"]}}
            querybody['query']['bool']['must'].append(dsl)
        if cinfo["company_org_type"]:
            dsl = {"term": {"company_org_type": cinfo["company_org_type"]}}
            querybody['query']['bool']['must'].append(dsl)
        if cinfo["gsb_province"]:
            dsl = {"term": {"base": cinfo["gsb_province"]}}
            querybody['query']['bool']['must'].append(dsl)
        if cinfo["gsb_company_cate_2"]:
            dsl = {"term": {"gsb_company_cate_2": cinfo["gsb_company_cate_2"]}}
            querybody['query']['bool']['must'].append(dsl)
        if cinfo["gsb_company_cate_3"]:
            dsl = {"term": {"gsb_company_cate_3": cinfo["gsb_company_cate_3"]}}
            querybody['query']['bool']['must'].append(dsl)
        if cinfo["gsb_shi"]:
            dsl = {"term": {"gsb_city": cinfo["gsb_shi"]}}
            querybody['query']['bool']['must'].append(dsl)
        if cinfo["estiblish_time"]:
            begin_e_time, end_e_time = time_trans.TimestampChange(cinfo["estiblish_time"],1)
            dsl = {"range": {"estiblish_time": {"gte": begin_e_time, "lte": end_e_time}}}
            querybody['query']['bool']['must'].append(dsl)
        if cinfo["reg_capital"]:
            ori_cap = float(cinfo["reg_capital"])
            new_cap_sub = str(ori_cap * 0.2)
            new_cap_add = str(ori_cap * 1.8)
            dsl = {"range": {"reg_capital": {"gte": new_cap_sub, "lte": new_cap_add}}}
            querybody['query']['bool']['must'].append(dsl)
        if cinfo["reg_unit"]:
            dsl = {"term": {"reg_unit": cinfo["reg_unit"]}}
            querybody['query']['bool']['must'].append(dsl)
        company_list = self.companyes.select_company(querybody)

        namelist = []
        print( len(company_list['hits']['hits']),111)
        if len(company_list['hits']['hits']) > 0:
            for row in company_list['hits']['hits']:
                if row['_source']["company_name"] == company_name:
                    continue
                from_time = ""
                if row['_source']["from_time"] != None and row['_source']["from_time"] != "null" and row['_source'][
                    "from_time"] != 0:
                    from_time = self.array_time(
                        time_trans.TimestampChange(row['_source']["from_time"], 0)[0])  # 起时间
                to_time = ""
                if row['_source']["to_time"] != None and row['_source']["to_time"] != "null" and row['_source'][
                    "to_time"] != 0:
                    to_time = self.array_time(
                        time_trans.TimestampChange(row['_source']["to_time"], 0)[0])  # 止时间
                if row['_source']["credit_code"] == None:
                    row['_source']["credit_code"] = '-'
                if row['_source']["legal_person"] == None:
                    row['_source']["legal_person"] = '-'
                if row['_source']["gsb_company_cate_1"] == None:
                    row['_source']["gsb_company_cate_1"] = '-'
                if row['_source']["company_org_type"] == None:
                    row['_source']["company_org_type"] = '-'
                data = {"company_name":row['_source']["company_name"],  "credit_code":row['_source']["credit_code"],"legal_person":str(row['_source']["legal_person"]),"time_between":str(str(from_time) + '- ' + str(to_time)),"gsb_company_cate_1":str(row['_source']["gsb_company_cate_1"]),"compamy_org_type":str(row['_source']["company_org_type"]) }
                namelist.append(data)
        company_list_result = namelist[:3]
        return company_list_result



