from django.shortcuts import render

# Create your views here.
from .models import *
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.apps import apps
import datetime
from django.contrib.auth.decorators import login_required

from wx.views import sK
from django.views.decorators.csrf import csrf_exempt

from utils.views import time_key_check
import json


def ent_action(user_id,what,action,id=None,ids=[]):
    data={'e':''}   
    m=apps.get_model('entertainment', what)
    if id:
        objs=m.objects.filter(id=int(id))
        if not objs:
            data['e']=what+" id not exists"
            return data  
        o=objs[0]
    if action=='confirm':  
        o.user_confirmed_id=int(user_id)
        tm=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        o.tm_confirmed=tm
        o.save()
        data['username']=User.objects.get(id=int(user_id)).username
        data['tm']=tm
    #elif action=='delete' and what=='EntWriteoff':
    #    if o.GiftApplication:
    #        if o.GiftApplication.tm_confirmed:
    #            data['e']='GiftApplication been confirmed'
    #        else:        
    #            o.delete()
    #    elif o.ActApplication:
    #        if o.ActApplication.tm_confirmed:
    #            data['e']='ActApplication been confirmed'
    #        else:        
    #            o.delete()
    #    elif o.EntApplication:
    #        if o.EntApplication.tm_confirmed:
    #            data['e']='EntApplication been confirmed'
    #        else:        
    #            o.delete()
    elif action=='delete' and what=='EntWriteoff' :
        cnt=0
        for i in ids:
            objs=m.objects.filter(id=int(i))
            if objs:
                o=objs[0]
                o.delete()
                cnt=cnt+1
        data['cnt']=cnt        
    return data



@login_required
def request_ent_action(request,what,action,id):
    user_id=request.user.id
    data=ent_action(user_id,what,action,id)
    return JsonResponse(data)


@csrf_exempt 
def app_ent_action(request,what,action,id=None):
    data={'e':''}
    e=time_key_check(request,sK)
    if e:
        data['e']=e
        return JsonResponse(data)
    #前端POST JSON
    r = json.loads(request.body)
    if 'user_id' not in r:
        data['e']='user id missing'
        return JsonResponse(data)
    user_id=r['user_id']    
    ids=None    
    if what=='EntWriteoff' and action=='delete':
        if 'ids' not in r:
            data['e']='EntWriteoff ids missing'
            return JsonResponse(data)
        ids=r['ids']
    data=ent_action(user_id,what,action,id,ids)
    return JsonResponse(data)
    
