# coding=utf-8

import time
import httpConn
import dbConn
import json
from multiprocessing.dummy import Pool as ThreadPool
from SendEmail import Email
from wxSend import WX


lines = []

def getA000001():
    url = 'http://push2his.eastmoney.com/api/qt/stock/trends2/get?secid=1.000001&ut=&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5%2Cf6%2Cf7%2Cf8%2Cf9%2Cf10%2Cf11&fields2=f51%2Cf53%2Cf56%2Cf58&iscr=0&ndays=1'
    conn = httpConn.HttpConnect()
    data = conn.request_get(url)

    if data == '':
        print('查询A000001失败')

    else:
        ts = data['data']['time']
        at = time.strftime("%Y-%m-%d", time.localtime(ts))
        dt = time.strftime("%Y-%m-%d", time.localtime())
        if at != dt:
            print('非交易日')
            return False
        else:
            hour = int(time.strftime("%H", time.localtime()))
            minute = int(time.strftime("%M", time.localtime()))

            if (hour == 9 and minute >=30):
                return True
            elif (hour ==10):
                return True
            elif (hour == 11 and minute <=30):
                return True
            elif (hour >= 13 and hour < 15):
                return True
            elif (hour == 15 and minute < 5):
                return True
            else:
                print('非交易时段')
                return False

def getAllCode():
    url = 'http://41.push2.eastmoney.com/api/qt/clist/get?pn=1&pz=5000&po=1&np=1&ut=&fltt=2&invt=2&fid=f3&fs=m:0+t:6,m:0+t:13,m:0+t:80,m:1+t:2,m:1+t:23&fields=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f12,f13,f14,f15,f16,f17,f18,f20,f21,f23,f24,f25,f22,f11,f62,f128,f136,f115,f152'
    conn = httpConn.HttpConnect()
    data = conn.request_get(url)
    # print(data)

    if data == '':
        print('查询code失败')

    else:
        db = dbConn.MY_SQL()
        db.save_time_line_table(data['data']['diff'], time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))


def getGeGuZiJInLiu(bkData):
    url = 'http://push2.eastmoney.com/api/qt/clist/get?pn=1&pz=500&po=1&np=1&ut=&fltt=2&invt=2&fid=f62&fs=b:'+bkData[0]+'&stat=1&fields=f12,f14,f2,f3,f62,f184,f66,f69,f72,f75,f78,f81,f84,f87,f204,f205,f124'
    conn = httpConn.HttpConnect()
    data = conn.request_get(url)
    # print(data)

    if data == '':
        print('查询code失败')

    else:
        for i in data['data']['diff']:
            code = str(i['f12'])
            name = str(i['f14'])
            zhangfu = str(i['f3'])
            level_zhuli = str(i['f62'])
            level_zhuli_per = str(i['f184'])
            level_chaoda = str(i['f66'])
            level_chaoda_per = str(i['f69'])
            level_da = str(i['f72'])
            level_da_per = str(i['f75'])
            level_zhong = str(i['f78'])
            level_zhong_per = str(i['f81'])
            level_xiao = str(i['f84'])
            level_xiao_per = str(i['f87'])
            shijian = time.strftime("%Y-%m-%d %H:%M", time.localtime((i['f124'])))

            sql = "REPLACE INTO `t_zijinliu_gegu` " \
                  "(`code`, `name`, `type`, `zhangfu`, `shijian`, `level_zhuli`, `level_zhuli_per`, `level_chaoda`, " \
                  "`level_chaoda_per`, `level_da`, `level_da_per`, `level_zhong`, `level_zhong_per`, `level_xiao`, " \
                  "`level_xiao_per`) VALUES " \
                  "('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')" % \
                  (code, name, bkData[2], zhangfu, shijian, level_zhuli, level_zhuli_per, level_chaoda,
                   level_chaoda_per,
                   level_da, level_da_per, level_zhong, level_zhong_per, level_xiao, level_xiao_per)

            sqlList.append(sql)



def getBanKuaiZiJInLiu(type):
    url = 'http://push2.eastmoney.com/api/qt/clist/get?pn=1&pz=500&po=1&np=1&ut=&fltt=2&invt=2&fid=f62&fs=m:90+t:'+type+'&stat=1&fields=f12,f13,f14,f62,f2,f3,f62,f184,f66,f69,f72,f75,f78,f81,f84,f87,f204,f205,f124'
    conn = httpConn.HttpConnect()
    data = conn.request_get(url)
    # print(data)

    if data == '':
        print('查询code失败')

    else:
        db = dbConn.MY_SQL()
        list = db.save_zijinliu_bankuai_table(data['data']['diff'], type)

        bkList.extend(list)


# 检查监控点是否需要发通知
def checkNotify():
    db = dbConn.MY_SQL()
    list = db.getNotifyList()
    allMsg = ''
    for i in list:
        msg = ''
        price = db.getLastPrice(i[1])
        if float(i[3]) != 0 and float(price[1]) >= float(i[3]) and float(i[5]) == 0:
            # 更新上限状态
            db.updateNotifyType(i[0], 1, i[6], i[7])
            msg += '上限 》 %s[<font color="#ff0000">%s</font>]， 当前价： %s， %s%% <br>' % \
                   (i[2], i[1], price[1], price[2])

        if float(i[4]) != 0 and float(price[1]) <= float(i[4]) and float(i[6]) == 0:
            # 更新下限状态
            db.updateNotifyType(i[0], i[5], 1, i[7])
            msg += '下限 》 %s[<font color="#00ff00">%s</font>]， 当前价： %s， %s%% <br>' % \
                   (i[2], i[1], price[1], price[2])

        # 判断今天的涨跌幅度, (2, 5, 7, 9.9)
        if msg == '':
            p1 = abs(float(price[2]))    # 当前幅度
            p2 = abs(float(i[7]))        # 记录幅度
            if p1 >= 9.9 and p2 != 9.9:
                db.updateNotifyType(i[0], i[5], i[6], 9.9)
            elif 9.9 > p1 >= 7 and p2 != 7:
                db.updateNotifyType(i[0], i[5], i[6], 7)
            elif 7 > p1 >= 5 and p2 != 5:
                db.updateNotifyType(i[0], i[5], i[6], 5)
            elif 5 > p1 >= 2 and p2 != 2:
                db.updateNotifyType(i[0], i[5], i[6], 2)
            else:
                continue

            msg = '波动 ~ %s[<font color="#0000ff">%s</font>]， 当前价： %s， %s%% <br>' % \
                  (i[2], i[1], price[1], price[2])

        allMsg += msg

    if allMsg != '':
        Email.sendNofity(allMsg)
        WX.send('STK', allMsg)

# 检查资金流监控点是否需要发通知
def checkZiJinLiuNotify():
    day = (time.strftime('%Y-%m-%d', time.localtime()))

    list = dbConn.MY_SQL().getYanZheng1Code()
    result = []
    for code in list:
        # print(code[1])
        tlist = dbConn.MY_SQL().getLastZiJinGeGu(code[1], day)
        # print(tlist)
        if tlist is not None and tlist[4] != '-' and float(tlist[4]) > 10 and '09:3' not in tlist[2]:
            result.append(tlist)
            dbConn.MY_SQL().updateYanZheng1Code(code[0])
            dbConn.MY_SQL().saveYanZheng1History(tlist)

    # print(result)
    if len(result) > 0:
        Email.sendNofity(json.dumps(result, ensure_ascii=False))


bkList = []
sqlList = []

try:
    if getA000001():
        s = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        startTime = (time.time())
    
        getAllCode()
    
        getBanKuaiZiJInLiu('1')
        getBanKuaiZiJInLiu('2')
        getBanKuaiZiJInLiu('3')
    
        pool = ThreadPool(10)
        pool.map(getGeGuZiJInLiu, bkList)
        pool.close()
        pool.join()
    
        if len(sqlList) > 0:
            db = dbConn.MY_SQL()
            db.save_zijinliu_gegu_table(sqlList)

        checkNotify()

        checkZiJinLiuNotify()

        print(s + ' 用时： ' + str(time.time() - startTime))

except Exception as e:
    Email.sendErr()
