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

from api.models import BannerFreeRecruitment, transaction
from api.models.freerecruitment import FreeRecruitment, FreeRecruitmentDiary, FreeRecruitmentDoctor, \
    FreeRecruitmentImage
from rpc.decorators import bind_context

from rpc.exceptions import RPCNotFoundException

uri_pre = 'hera/freerecruitment'

@bind_context(uri_pre + '/get_banner')
def get_button_sideslip(ctx):
    return BannerFreeRecruitment.get_banners(page_type=0)


@bind_context(uri_pre + '/set_banner')
def set_button_sideslip(ctx, banner_info):
    BannerFreeRecruitment.set_banners(
        page_type=0,
        banner_info=banner_info
    )

@bind_context(uri_pre + '/edit')
@transaction.atomic
def article_edit(ctx, freerecruitment_id=None, freerecruitment_info=None):
    freerecruitment_info['service_id'] = freerecruitment_info['service_id']
    diary_id = freerecruitment_info.pop('diary_id', [])
    doctor_id = freerecruitment_info.pop('doctor_id', [])
    banner_image = freerecruitment_info.pop('banner_image', [])
    freerecruitment_info['end_time'] = freerecruitment_info['end_time'][:10] + ' 23:59:59'
    if freerecruitment_id is None:
        try:
            freerecruitment = FreeRecruitment.objects.create(**freerecruitment_info)
            for i in diary_id:
                FreeRecruitmentDiary.objects.create(freerecruitment_id=freerecruitment.id, diary_id=i)
            for i in doctor_id:
                FreeRecruitmentDoctor.objects.create(freerecruitment_id=freerecruitment.id, doctor_id=i)
            for i in banner_image:
                FreeRecruitmentImage.objects.create(freerecruitment_id=freerecruitment.id, image=i)
        except Exception as e:
            print ('%%%%%%%%%%%%',e)
    else:
        try:
            freerecruitment = FreeRecruitment.objects.get(id=freerecruitment_id)
        except:
            raise RPCNotFoundException
        for k, v in freerecruitment_info.iteritems():
            setattr(freerecruitment, k, v)
        freerecruitment.save()
        FreeRecruitmentDiary.objects.filter(freerecruitment_id=freerecruitment_id).delete()
        FreeRecruitmentDoctor.objects.filter(freerecruitment_id=freerecruitment_id).delete()
        FreeRecruitmentImage.objects.filter(freerecruitment_id=freerecruitment_id).delete()
        for i in diary_id:
            FreeRecruitmentDiary.objects.create(freerecruitment_id=freerecruitment.id, diary_id=i)
        for i in doctor_id:
            FreeRecruitmentDoctor.objects.create(freerecruitment_id=freerecruitment.id, doctor_id=i)
        for i in banner_image:
            FreeRecruitmentImage.objects.create(freerecruitment_id=freerecruitment.id, image=i)

    return {
        'id': freerecruitment.id,
    }
