
import json
import threading
import time

import redis
import requests
from retry import retry
from elasticsearch import Elasticsearch
from base import BaseCore

baseCore = BaseCore.BaseCore()
log = baseCore.getLogger()
baseCore = BaseCore.BaseCore()

cnx_ = baseCore.cnx_
cursor_ = cnx_.cursor()

lock = threading.Lock()
pathType = 'QYNotice/'
taskType = '企业研报/东方财富网'
es = Elasticsearch(['http://114.116.19.92:9700'], http_auth=('elastic', 'zzsn9988'), timeout=300)
index_name = 'researchreportdata'
pool = redis.ConnectionPool(host="114.115.236.206", port=6379, password='clbzzsn', db=6)

def searchATT(title):
    sql = "select id from clb_sys_attachment where type_id=4 and name=%s "
    # lock.acquire()
    cursor_.execute(sql, title+'.pdf')
    selects = cursor_.fetchone()
    # lock.release()
    return selects

def updateaunn(index_name,id,u_attid):
    body = {
        'doc': {
            'attachmentIds': [str(u_attid)]
        }
    }
    result = es.update(index=index_name
                            ,id=id
                            ,body=body)
    log.info('更新结果:%s' % result)

if __name__ == "__main__":
    while True:
        # 从redis中读取数据，去附件表中根据title查询，更新查到的附件id
        item = baseCore.redicPullData('YanBao:id')
        log.info(item)
        title = item.split('|')[1]
        id = item.split('|')[0]
        selects = searchATT(title)
        if selects:
            u_attid = selects[0]

            # 更新es库
            updateaunn(index_name,id,u_attid)
        else:
            # 查询es库，通过链接上传文件到obs
            baseCore.r.lpush('YanBao:up',id)


