import requests
import time
import datetime
import random
import traceback
import logging
import json
import redis
import smtplib
from libs.cache import redis_client
from email.mime.text import MIMEText
from email.utils import formataddr
from physical.settings_local import DATABASES
from physical.settings_local import REDIS_URL

my_sender = 'lixiaofang@igengmei.com'
my_pass = 'tg5AVKBB8jLQGBET'
my_user6 = "lixiaofang@igengmei.com"

# auto_click_url = "http://earth.gmapp.env/api/v1/like"
# auto_reply_url = "http://earth.gmapp.env/api/v1/reply/create"
# auto_follow_url = "http://earth.gmapp.env/api/v1/follow"
# auto_urge_url = "http://earth.gmapp.env/api/v1/user/urge"

# DATABASES = {
#     'default': {
#         'ENGINE': 'django.db.backends.mysql',
#         'NAME': 'alpha',
#         'USER': 'work',
#         'PASSWORD': 'Gengmei123!',
#         'HOST': 'bj-cdb-55ejhsjy.sql.tencentcdb.com',
#         'PORT': '62177',
#         'OPTIONS': {
#             "init_command": "SET foreign_key_checks = 0;",
#             "charset": "utf8mb4",
#         },
#     }
# }

auto_click_url = "http://earth.iyanzhi.com/api/v1/like"
auto_reply_url = "http://earth.iyanzhi.com/api/v1/reply/create"
auto_follow_url = "http://earth.iyanzhi.com/api/v1/follow"
auto_urge_url = "http://earth.iyanzhi.com/api/v1/user/urge"

host = DATABASES['default']['HOST']

user = DATABASES['default']['USER']

port = DATABASES['default']['PORT']

db = DATABASES['default']['NAME']

passwd = DATABASES['default']['PASSWORD']


def get_majia_reply(user_id):
    try:
        data = open("/srv/apps/physical/vest/data/vest_user_email.txt")
        list = []
        for i in data:
            if i != user_id:
                list.append(i.strip('\n').strip(','))

        maj = random.randint(1, len(list))
        user_id = list[maj - 1]
        return user_id

    except:
        logging.error("catch exception,get_majia:%s" % traceback.format_exc())
        return None


def get_majia():
    try:
        data = open("/srv/apps/physical/vest/data/vest_user_email.txt")
        list = []
        for i in data:
            list.append(i.strip('\n').strip(','))
        maj = random.randint(1, len(list))
        user_id = list[maj - 1]
        return user_id

    except:
        logging.error("catch exception,get_majia:%s" % traceback.format_exc())
        return None


def get_cookies(user_id):
    try:
        session_key = "majia_login_session"
        data = redis_client.hget(session_key, user_id)
        logging.info("get data:%s" % data)
        logging.info("get data:%s" % json.loads(data))

        return json.loads(data)

    except:
        logging.error("catch exception,get_majia:%s" % traceback.format_exc())
        return None


def login():
    try:
        user_id = get_majia()
        logging.info("get user_id:%s" % user_id)

        cookies = get_cookies(user_id)
        if cookies is not None:
            return {'sessionid': cookies}

    except:

        logging.error("catch exception,logins:%s" % traceback.format_exc())

        return None


def logins(user_id):
    try:
        cookies = get_cookies(user_id)
        if cookies is not None:
            return {'sessionid': cookies}

    except:

        logging.error("catch exception,logins:%s" % traceback.format_exc())

        return None


def click(cookies_get, id):
    try:
        post_dict = {
            'type': 0,
            'id': id
        }
        response = requests.post(url=auto_click_url,
                                 cookies=cookies_get,
                                 data=post_dict)

        logging.info("response.text:%s" % response.text)

        get_error(response.text, "click", id)
    except:

        logging.error("catch exception,logins:%s" % traceback.format_exc())


def reply(cookies_get, id, content):
    try:
        post_dict = {
            'topic_id': id,
            'content': content,
            "type": 4
        }
        response = requests.post(url=auto_reply_url,
                                 cookies=cookies_get,
                                 data=post_dict)

        logging.info("response.text:%s" % response.text)
        get_error(response.text, "reply", id)
    except:

        logging.error("catch exception,logins:%s" % traceback.format_exc())


def time_conv(minutest, minutest2):
    try:
        now = datetime.datetime.now()
        yes_time = now - datetime.timedelta(minutes=minutest)
        yes_time2 = now - datetime.timedelta(minutes=minutest2)
        return yes_time, yes_time2
    except:
        return None


def time_conv_minute(minutest, minutest2):
    try:
        now = datetime.datetime.now()
        minute = datetime.datetime.now().minute
        yes_time = now - datetime.timedelta(minutes=minutest)
        yes_time2 = now - datetime.timedelta(minutes=minutest2)
        return yes_time, yes_time2, minute
    except:
        return None


def time_now(minutest):
    try:
        now = datetime.datetime.now()
        yes_time = now - datetime.timedelta(hours=minutest)
        return yes_time, now
    except:
        return None


def time_convs(numtime, numtime2):
    try:
        now = datetime.datetime.now()
        yes_time = now - datetime.timedelta(days=numtime)
        yes_time_str = yes_time.strftime('%Y-%m-%d')
        yes_time_str = yes_time_str + ' 23:59:59.000000'

        yes_time2 = now - datetime.timedelta(days=numtime2)
        yes_time_str2 = yes_time2.strftime('%Y-%m-%d')
        yes_time_str2 = yes_time_str2 + ' 00:00:00.000000'

        return yes_time_str, yes_time_str2
    except:
        return None


def get_comment():
    try:
        data = open("/srv/apps/physical/vest/data/guanshui.txt", "r")
        list_guanshui = []
        for i in data:
            list_guanshui.append(i)

        num = random.randint(0, len(list_guanshui))

        comment = list_guanshui[num - 1]

        return comment

    except:

        return None


def get_comments():
    try:
        data = open("/srv/apps/physical/vest/data/guanshui.txt", "r")
        list_guanshui = []
        for i in data:
            list_guanshui.append(i)

        num1 = random.randint(0, 200)
        num2 = random.randint(200, 400)
        num3 = random.randint(400, len(list_guanshui))

        comment1 = list_guanshui[num1 - 1]
        comment2 = list_guanshui[num2 - 1]
        comment3 = list_guanshui[num3 - 1]

        comment_list = [comment1, comment2, comment3]

        return comment_list

    except:

        return None


def follow(cookies_get, id):
    try:
        post_dict = {
            'type': 1,
            'id': id
        }
        response = requests.post(url=auto_follow_url,
                                 cookies=cookies_get,
                                 data=post_dict)

        logging.info("response.text:%s" % response.text)
        get_error(response.text, "follow", id)
    except:

        logging.error("catch exception,logins:%s" % traceback.format_exc())


def Urge(cookies_get, id):
    try:
        post_dict = {
            'id': id
        }
        response = requests.post(url=auto_urge_url,
                                 cookies=cookies_get,
                                 data=post_dict)

        logging.info("response.text:%s" % response.text)
        get_error(response.text, "Urge", id)
    except:

        logging.error("catch exception,logins:%s" % traceback.format_exc())


def get_offline_comment():
    try:
        data = open("/srv/apps/physical/vest/data/offline_comment.txt", "r")

        list_guanshui = []
        for i in data:
            list_guanshui.append(i)
        num1 = random.randint(0, 200)
        num2 = random.randint(200, 300)
        num3 = random.randint(300, 400)
        num4 = random.randint(400, len(list_guanshui))

        comment1 = list_guanshui[num1 - 1]
        comment2 = list_guanshui[num2 - 1]
        comment3 = list_guanshui[num3 - 1]
        comment4 = list_guanshui[num4 - 1]

        comment_list = [comment1, comment2, comment3, comment4]
        return comment_list

    except:

        return None


def get_user_id():
    user_data = open("/srv/apps/physical/vest/data/get_user_id.txt", "r")
    user_list = []

    for i in user_data.readlines():
        user_list.append(int(i.strip()))

    return user_list


def send_email(stat_data):
    ret = True
    now = datetime.datetime.now()
    yes_time = now - datetime.timedelta(days=1)
    yes_time_str = yes_time.strftime('%Y%m%d')
    try:
        msg = MIMEText(stat_data, 'plain', 'utf-8')
        msg['From'] = formataddr(["李小芳", my_sender])
        msg["To"] = formataddr(["李小芳", my_user6])
        msg['Subject'] = str(datetime.date.today()) + "like的测试环境的自动点赞出问题了"
        server = smtplib.SMTP_SSL("smtp.exmail.qq.com", 465)
        server.login(my_sender, my_pass)
        server.sendmail(my_sender, [my_user6], msg.as_string())
        server.quit()
        return ret
    except Exception:
        ret = False
        logging.error("catch exception,main:%s" % traceback.format_exc())


def get_error(line, type, id):
    try:
        if len(line) > 1:
            data_dict = json.loads(line)
            if data_dict["error"] != 0:
                stat_data = str(line) + str(type) + str(id)
                ret = send_email(stat_data)
                if ret:
                    logging.info('like query统计邮件发送成功')
                else:
                    logging.info('like query统计邮件发送失败')
            else:
                pass
    except:
        logging.error("catch exception,err_msg:%s" % traceback.format_exc())


def get_answer_data():
    try:

        # 获取第一条评论
        data = open("/srv/apps/physical/vest/data/reply_answer_data1.txt", "r")

        answer_data1 = []
        for i in data:
            answer_data1.append(i)
        num1 = random.randint(0, len(answer_data1))

        comment1 = answer_data1[num1 - 1]

        # 获取第二条评论
        data = open("/srv/apps/physical/vest/data/reply_answer_data2.txt", "r")

        answer_data2 = []
        for i in data:
            answer_data2.append(i)
        comment2 = answer_data2[num1 - 1]

        logging.info("get comment1:%s" % comment1)
        logging.info("get comment2:%s" % comment2)

        return comment1, comment2

    except:

        return ["", ""]


def reply_answer(cookies_get, id, content):
    try:
        post_dict = {
            'topic_id': id,
            'content': content,
            "type": 4
        }
        response = requests.post(url=auto_reply_url,
                                 cookies=cookies_get,
                                 data=post_dict)

        logging.info("response.text:%s" % response.text)
        get_error(response.text, "reply", id)

        return response.text
    except:

        logging.error("catch exception,logins:%s" % traceback.format_exc())


def set_reply_to_redis():
    try:
        redis_client = redis.StrictRedis.from_url(REDIS_URL)
        return redis_client
    except:
        logging.error("catch exception,logins:%s" % traceback.format_exc())


def reply2(cookies_get, id, content, replied_id):
    try:
        post_dict = {
            'topic_id': id,
            'content': content,
            "type": 4,
            "replied_id": replied_id
        }
        response = requests.post(url=auto_reply_url,
                                 cookies=cookies_get,
                                 data=post_dict)

        logging.info("response.text:%s" % response.text)
        get_error(response.text, "reply2", id)
    except:

        logging.error("catch exception,logins:%s" % traceback.format_exc())


def pictorial_reply(cookies_get, id, content):
    try:
        post_dict = {
            'pictorial_id': id,
            'content': content,
            "type": 4
        }
        response = requests.post(url=auto_reply_url,
                                 cookies=cookies_get,
                                 data=post_dict)

        logging.info("response.text:%s" % response.text)
        get_error(response.text, "pictorial_reply", id)
    except:

        logging.error("catch exception,logins:%s" % traceback.format_exc())


def get_pictorial_comment():
    try:
        data = open("/srv/apps/physical/vest/data/pictorial_reply_data.txt", "r")
        list_guanshui = []
        for i in data:
            list_guanshui.append(i)

        num = random.randint(0, len(list_guanshui))

        comment = list_guanshui[num - 1]

        return comment

    except:

        return None