# coding=utf-8

import pymysql

# db = pymysql.connect(host='192.168.1.102', port=3309, user='root', password='eagle', db='db_east_money', charset='utf8')
db = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='eagle', db='db_east_money', charset='utf8')
cursor = db.cursor()
sql = 'SELECT `code` FROM `t_code` ORDER BY `id`;'
cursor.execute(sql)
results = cursor.fetchall()
print(len(results))

# 找最近3天
sql1 = '''
            SELECT
                date_format(`shijian`, '%Y-%m%-%d') `sj`
            FROM
                `t_time_line`
            WHERE
                `code` = '000001'
            GROUP BY date_format(`shijian`, '%Y-%m-%d')
            ORDER BY `shijian` DESC
            LIMIT 3;
'''
cursor.execute(sql1)
days = cursor.fetchall()


for codes in results:
    if codes[0].startswith('00') or codes[0].startswith('60'):
        t = []
        for d in days:
            sql2 = '''
                SELECT `code`, `name`, `shijian`, `percent`, `huanshoulv` FROM `t_time_line` WHERE `code` = '%s' AND `shijian` LIKE concat('%s', '%%') ORDER BY `shijian` DESC LIMIT 1;
            ''' % (codes[0], d[0])

            cursor.execute(sql2)
            res = cursor.fetchone()
            if res is not None:
              t.append(res)

        if len(t) == 3:
            p1 = float(t[0][3])
            h1 = float(t[0][4])
            h2 = float(t[1][4])
            h3 = float(t[2][4])
            if p1 > 0 and h1 <= h2 <= h3 and (h1>=3 or h2>=3 or h3>=3):
                print(t)
                sql3 = '''
                    REPLACE INTO t_notify_huanshoulv (`code`, `name`, `shijian`, `percent`, `huanshoulv`) VALUES ('%s', '%s', '%s', '%s', '%s');
                ''' % (t[0][0], t[0][1], t[0][2], t[0][3], t[0][4])
                cursor.execute(sql3)
                db.commit()