from django.shortcuts import render

# Create your views here.
from django.db import connection
from utils.views import time_key_check
from company.models import User
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse

from wx.views import sK
import json 
from .models import *

from django.views.decorators.csrf import csrf_exempt


@csrf_exempt
def PostLabels(request):
    data={
        'e':'',
        'cnt_total':0,
        'cnt_ok':0,
    }
    e=time_key_check(request,sK)
    if e:
        data['e']=e
        return JsonResponse(data)

    r = json.loads(request.body)
    
    if 'user_id' not in r:
        data['e']='user id missing'
        return JsonResponse(data)
    if 'codes' not in r:
        data['e']='label codes missing'
        return jsonResponse(data)
    codes=r['codes']
    data['cnt_total']=len(codes)
    title=None
    remark=None
    if 'title' in r:
        title=r['title']
    if 'remark' in r:
        remark=r['remark']   
        
    us=User.objects.filter(id=int(r['user_id']))
    if not us:
        data['e']='user id error'
        return JsonResponse(data)   
    cur=connection.cursor()
    u=us[0]    
    b=LabelsBatch(company_id=u.company_id,user_id=u.id,title=title,remark=remark)
    b.save()
    id=str(b.id)
    a=[]
    for c in codes: 
        rmk='null'        
        if c['remark']:
            rmk="'"+c['remark']+"'"            
        if c['label']:
            a.append("('"+c['label']+"',"+rmk+","+id+")")
    if a:
        s="INSERT INTO extra_labelsdetail(label,remark,batch_id) values "+ ",".join(a)
        cur.execute(s)
        data['cnt_ok']=cur.rowcount
    return JsonResponse(data)

