# -*- coding: UTF-8 -*-

from api.models.user import User
from api.models.service import Service
from api.models.recommend_doctor import RecommendDoctor
from api.models.recommend_doctor import StockAlert
from api.tasks.push_task import allocate_push_task_stock_alert

from rpc.decorators import bind_context, bind
from rpc.tool.dict_mixin import to_dict
from ..datatables import RecommendDoctorDT
from ..datatables import StockAlertDT
from ..queries.recommenddoctor import RecommendDoctorDQ, StockAlertDQ


uri_pre = 'hera/recommenddoctor'


@bind_context(uri_pre+'/list')
def topicreply_datatable(ctx, req_data):
    dtobj = RecommendDoctorDT(RecommendDoctor)
    return dtobj.process(req_data)


@bind_context(uri_pre + '/query')
def recommenddoctor_query(ctx, options):
    dqobj = RecommendDoctorDQ()
    return dqobj.process(**options)


@bind_context('hera/stockalert/query')
def stockalert_query(ctx, options):
    dqobj = StockAlertDQ()
    return dqobj.process(**options)


@bind_context('hera/stockalert/list')
def stockalert_datatable(ctx, req_data):
    dtobj = StockAlertDT(StockAlert)
    return dtobj.process(req_data)


@bind('hera/stockalert/get')
def stockalert_get(diary_id):
    item = StockAlert.objects.get(diary_id=diary_id)
    d_item = to_dict(item)
    service_id = item.diary.service.id if item.diary.service else ""
    d_item['service'] = service_id
    return d_item


@bind('hera/stockalert/edit')
def stockalert_edit(req_data):
    diary_id = req_data.pop('diary')
    stockalert = StockAlert.objects.get(diary_id=diary_id)

    business_partener = req_data.pop('business_partener')
    if business_partener:
        partener = User.objects.get(id=business_partener)
        stockalert.business_partener = partener

    service = req_data.pop('service')
    if service:
        item = Service.objects.get(id=service)
        stockalert.diary.service = item
        stockalert.diary.save()
        push_task(stockalert, service)

    for k, v in req_data.items():
        v and setattr(stockalert, k, v)
    stockalert.save()
    return to_dict(stockalert)


def push_task(stockalert, service):
    title = u"美购上架通知"
    push_tpl = u"你关注的{}专家的{}项目在更美上架啦，快去看看吧"
    sms_tpl = u"你关注的{}专家的{}项目在更美上架啦，快去看看吧，更美APP下载地址: http://dwz.cn/2e23Hq 【更美】"
    content = (stockalert.doctor, stockalert.item_name)
    sms_data = [{'name': stockalert.doctor}, {'service': stockalert.item_name}]
    kwargs = {
        'title': title,
        'text': content,
        'diary_id': stockalert.diary_id,
        'push_content': push_tpl.format(*content),
        'sms_content': sms_tpl.format(*content),
        'sms_data': sms_data,
    }
    allocate_push_task_stock_alert.delay(**kwargs)
