# coding=utf-8
import datetime
import json

from rpc.decorators import bind_context, bind
from api.models.sign_v2 import SignBigPrizeV2, ExchangedRecordV2, SignConfigV2


@bind('hera/sign/upload_check/express_no')
def upload_check_data(data):
    error_result = []
    for index, item in enumerate(data):
        try:
            prize_id, express_no, user_id = int(item.get("prize_id")), str(item.get("express_no")), int(item.get("user_id"))
            exchanged = ExchangedRecordV2.objects.filter(user_id=user_id, prize_id=prize_id).first()
            if not exchanged:
                error_result.append(index)
                continue

            exchanged.express_no = express_no
            exchanged.updated_time = datetime.datetime.now()
            exchanged.save(update_fields=['express_no'])
        except:
            error_result.append(index)

    return error_result


@bind("hera/sign/prize_is_online")
def prize_is_online(prize_id, is_online):
    prize = SignBigPrizeV2.objects.filter(id=prize_id).first()
    prize.is_online = True if int(is_online) else False
    prize.online_time = datetime.date.today()
    prize.save()
    return {"online_time": datetime.date.today().strftime("%Y-%m-%d")}


@bind("hera/sign/submit_config")
def submit_config(rule, sign_cycle, blind_rule, operate_config, stay_seconds, assist_img_url):
    """hera后台专用"""
    s_config = SignConfigV2.objects.first()
    from api.models import Special
    for item in operate_config:
        if item.get("special_type") == "1" and item.get("gm_url"):
            """1是美购专题（包括新老）"""
            special = Special.objects.filter(id=int(item.get("gm_url"))).first()
            if not special:
                continue
            item['new_special'] = special.is_new_special

    operate_config = json.dumps(operate_config)
    if s_config:
        s_config.rule = rule
        s_config.cycle = sign_cycle
        s_config.prize = blind_rule
        s_config.operate_config = operate_config
        s_config.browse_add_points = stay_seconds
        s_config.friend_assist_img_url = assist_img_url
        s_config.save()
    else:
        SignConfigV2.objects.create(cycle=sign_cycle, rule=rule, prize=blind_rule, operate_config=operate_config,
                                    browse_add_points=stay_seconds, friend_assist_img_url=assist_img_url)

    return {"status": 1}


@bind("hera/sign/get_config")
def get_config():
    """hera后台专用"""
    s_config = SignConfigV2.objects.first()
    return {
        "rule": s_config.rule,
        "sign_cycle": s_config.cycle,
        "blind_rule": s_config.prize,
        "operate_config": json.loads(s_config.operate_config),
        "stay_seconds": s_config.browse_add_points,
        "assist_img_url": s_config.friend_assist_img_url,
    }