#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time     : 2020/5/26 14:34
# @Author   : hj
# @File     :hxResult.py
# @software :PyCharm

from dao.business_job_es import hxMessage
from dao.business_job_dao import hxDao
from flask import request
from db.mod_db import DataBase
from common.time_format import timeGmt

hx_mysql = hxDao()
hx_es_info = hxMessage()

def hxCompany(company_hx_es):
    company_hx_list = []
    if (company_hx_es["hits"]["total"] > 0):
        for row in company_hx_es["hits"]["hits"]:
            company_name = row['_source']["companyname"]
            company_hx_list.append(company_name)
        return company_hx_list


def businessApi(server):
    @server.route('/gsb/api/businessJob', methods=['POST'])
    def bussinessJobMain():
        if request.method == 'POST':
            job_info = request.json
            if job_info:
                job_type = '画像任务'
                job_status = '未处理'
                # try:
                if "company_list" in job_info:
                    company_info = job_info.get("company_list")
                    for company_item in company_info:
                        company_name = company_item
                        begin_time = job_info.get("begin_time")
                        begin_time_format = begin_time[0:10]
                        end_time = job_info.get("end_time")
                        end_time_format = end_time[0:10]
                        product = job_info.get("product_name")
                        hx_mysql.jobInsert(company_name, job_type, begin_time_format, end_time_format, product,job_status)
                else:
                    select_filter = job_info.get("select_filter")
                    re_item = {}
                    if select_filter != []:
                        for item in select_filter:
                            name = item['name']
                            list = item['list']
                            re_item[name] = list
                    else:
                        re_item = []
                    company_hx_es = hx_es_info.hxSearch(re_item)
                    company_hx_list = hxCompany(company_hx_es)
                    for company_name in company_hx_list:
                        company_name = company_name
                        begin_time = job_info.get("begin_time")
                        begin_time_format = begin_time[0:10]
                        end_time = job_info.get("end_time")
                        end_time_format = end_time[0:10]
                        product = job_info.get("product_name")
                        hx_mysql.jobInsert(company_name, job_type, begin_time_format, end_time_format, product,job_status)
                        print(777)
                DataInfo = DataBase()
                DataInfo.close()
                return {"status": 200, "msg": "成功"}
                # except Exception as error:
                #     print('job_error:', error)
                #     return {"status": 400, "msg": "失败"}
