# coding=utf-8
from __future__ import unicode_literals

import json
import datetime

from celery import shared_task
from gm_types.gaia import MOMO_STAT_LOG_MESSAGE_TYPE

from pay.models import MomoStatLog

from api.tool.log_tool import logging_exception

_momo_send_log_status_default = 0
_momo_send_log_status_sending = 1
_momo_send_log_status_success = 2


@shared_task
def get_momo_stat_log_from_db_and_send(days=2):
    start_time = datetime.datetime.now() - datetime.timedelta(days=days)

    send_log_ids = list(MomoStatLog.objects.filter(
        created_at__gte=start_time, status=_momo_send_log_status_default
    ).values_list('id', flat=True))

    for lid in send_log_ids:
        send_update_time = datetime.datetime.now()

        row_count = MomoStatLog.objects.filter(
            id=lid, status=_momo_send_log_status_default
        ).update(status=_momo_send_log_status_sending, updated_at=send_update_time)

        if row_count > 0:
            # 成功抢到发送权，准备发送
            try:
                stat_log = MomoStatLog.objects.get(id=lid)
                send_success = _send_stat_log(stat_log)
                if send_success is True:
                    now = datetime.datetime.now()
                    MomoStatLog.objects.filter(id=lid).update(
                        status=_momo_send_log_status_success, updated_at=now
                    )

            except:
                logging_exception()

    retry_update_time = datetime.datetime.now() - datetime.timedelta(minutes=5)

    retry_log_ids = list(MomoStatLog.objects.filter(
        created_at__gte=start_time, status=_momo_send_log_status_sending, updated_at__lte=retry_update_time
    ).values_list('id', flat=True))

    for rlid in retry_log_ids:
        send_update_time = datetime.datetime.now()

        row_count = MomoStatLog.objects.filter(
            id=rlid, status=_momo_send_log_status_sending, updated_at__lte=retry_update_time
        ).update(updated_at=send_update_time)

        if row_count > 0:
            # 成功抢到发送权，准备发送
            try:
                stat_log = MomoStatLog.objects.get(id=rlid)
                send_success = _send_stat_log(stat_log)
                if send_success is True:
                    now = datetime.datetime.now()
                    MomoStatLog.objects.filter(id=rlid).update(
                        status=_momo_send_log_status_success, updated_at=now
                    )

            except:
                logging_exception()


def _send_stat_log(stat_log):
    from gm_types.gaia import MOMO_STAT_LOG_TYPE
    from api.tasks.period_task import momo_stat_log

    try:
        if stat_log.message_type == MOMO_STAT_LOG_MESSAGE_TYPE.ORDER_VERIFIED_SUCCESS:
            stat_log_type = MOMO_STAT_LOG_TYPE.ORDER_VERIFIED_SUCCESS
        elif stat_log.message_type == MOMO_STAT_LOG_MESSAGE_TYPE.CONVERSATION_FIRST_REPLY:
            stat_log_type = MOMO_STAT_LOG_TYPE.CONVERSATION_FIRST_REPLY
        else:
            return False
        success = False

        momo_param_info = json.loads(stat_log.json_text)
        res_log_list = momo_stat_log(
            info_list=[momo_param_info, ],
            stat_log_type=stat_log_type,
        )
        if res_log_list:
            res_log = res_log_list[0]

            if res_log["response_code"] == 200:
                res_info_dict = res_log["response_info"]
                if res_info_dict.get("ec", 0) == 200 and res_info_dict.get("em", "") == "success":
                    success = True

        return success

    except:
        logging_exception()
        return False
