# coding=utf-8
from __future__ import absolute_import, unicode_literals, print_function

import urllib
from datetime import datetime

import requests
from gm_types.gaia import (
    CHANNEL_CALLBACK_TYPE,
    CHANNEL_STATUS,
)
from rpc.tool.log_tool import channel_logger, logging_exception

_VERIFIED = False


def xinyouxingkong_active_record(record):
    """信游星空回调"""

    update_fields = ['active_time', 'update_time']
    time_now = datetime.now()
    record.active_time = time_now
    record.update_time = time_now

    code = 1
    msg = CHANNEL_STATUS.ACT_FAIL_GENERAL

    channel_logger.info("信游星空 调用回调函数---")
    callback = record.callback or None

    if callback and callback.startswith(
            ("http", "HTTP", "https", "HTTPS")
    ) and record.callback_type == CHANNEL_CALLBACK_TYPE.GET_CALLBACK:

        callback_url = urllib.unquote(callback)
        try:
            res = requests.get(callback_url)

            if res.status_code == requests.codes.ok:
                code = 0
                msg = CHANNEL_STATUS.ACT_OK
                record.callback_response = res.text or ''
                _response_info_str = record.callback_response
                update_fields.append('callback_response')
            else:
                _response_info_str = ''

            channel_logger.info("信游星空 回调地址:{0}, 回调状态:{1},回调结果:{2}".format(
                callback_url, res.status_code, _response_info_str)
            )
        except:
            logging_exception()
            channel_logger.info("信游星空 回调失败。记录id:{}".format(record.id))
    else:
        channel_logger.info("信游星空 无回调。记录id:{}".format(record.id))

    record.save(update_fields=update_fields)
    return {'error': code, 'msg': msg}
