# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import json
import os
import uuid

from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, render_to_response
from django.core import serializers
# Create your views here.
from django.views.decorators.csrf import csrf_exempt
from requests import Response

from web.models import Loginuser, Pestinfo, Pestdic
from web.uploadpic import upload


def Main(request):
    return render(request, 'top.html')


def Map(request):
    research = Loginuser.objects.all()
    id = Pestinfo.objects.all()
    pestname = Pestdic.objects.all()
    rec = {"researchname": research, "areaid": id, "pestname": pestname}
    return render(request, 'amap/pestmap.html', rec)


def Index(request):
    return render(request, 'ahpests/pestindex.html')


def PestDic(request, id):
    ret = {}
    try:
        pests = Pestdic.objects.filter(parent__contains=id)
        ret['data'] = json.loads(serializers.serialize('json', pests))
        ret['status'] = 'success'
        ret['error_num'] = 0
    except Exception as e:
        ret['status'] = str(e)
        ret['error_num'] = 1
    return JsonResponse(ret, safe=False)


def ResearchPeople(request, id):
    ret = {}
    try:
        pests = Loginuser.objects.all()
        ret['data'] = json.loads(serializers.serialize('json', pests))
        ret['status'] = 'success'
        ret['error_num'] = 0
    except Exception as e:
        ret['status'] = str(e)
        ret['error_num'] = 1
    return JsonResponse(ret, safe=False)


def List(request):
    ret = {}
    try:
        pests = Pestinfo.objects.all()
        ret['data'] = json.loads(serializers.serialize('json', pests))
        ret['status'] = 'success'
        ret['error_num'] = 0
    except Exception as e:
        ret['status'] = str(e)
        ret['error_num'] = 1
    return JsonResponse(ret, safe=False)


def PestList(request, Id):
    ret = {}
    try:
        pests = Pestinfo.objects.filter(id=Id)
        ret['data'] = json.loads(serializers.serialize('json', pests))
        ret['status'] = 'success'
        ret['error_num'] = 0
    except Exception as e:
        ret['status'] = str(e)
        ret['error_num'] = 1
    return JsonResponse(ret, safe=False)


@csrf_exempt
def Cre_pest(request):
    response = {'status': True, 'message': None}
    try:
        date = request.POST.get('date')
        adressid = request.POST.get('adressid')
        pestname = request.POST.get('pestname')
        pestfirstgrade = request.POST.get('pestfirstgrade')
        pestsecondgrade = request.POST.get('pestsecondgrade')
        researchperson = request.POST.get('researchperson')
        longitude = request.POST.get('longitude')
        latitude = request.POST.get('latitude')
        remark = request.POST.get('remark')
        pestpicurl1 = request.POST.get('pestpicurl1')
        pestpicurl2 = request.POST.get('pestpicurl2')
        Pestinfo.objects.create(
            date=date,
            adressid=adressid,
            pestname=pestname,
            pestfirstgrade=pestfirstgrade,
            pestsecondgrade=pestsecondgrade,
            researchpeople=researchperson,
            remark=remark,
            pestpicurl1=pestpicurl1,
            pestpicurl2=pestpicurl2,
            longitude=longitude,
            latitude=latitude,
        )
    except Exception as e:
        response['status'] = False
        response['message'] = e

    return HttpResponse(response)


@csrf_exempt
def Up_pest(request):
    response = {'code': 1000, 'message': None}
    try:
        nid = request.POST.get("id", None)
        # print nid
        date = request.POST.get("date", None)
        # print date
        adressid = request.POST.get('adressid', None)
        # print adressid
        pestname = request.POST.get('pestname', None)
        pestfirstgrade = request.POST.get('pestfirstgrade', None)
        pestsecondgrade = request.POST.get('pestsecondgrade', None)
        researchperson = request.POST.get('researchperson', None)
        longitude = request.POST.get('longitude', None)
        latitude = request.POST.get('latitude', None)
        remark = request.POST.get('remark', None)
        # print remark
        pestpicurl1 = request.POST.get('pestpicurl1', None)
        pestpicurl2 = request.POST.get('pestpicurl2', None)
        Pestinfo.objects.filter(id=nid).update(
            date=date,
            adressid=adressid,
            pestname=pestname,
            pestfirstgrade=pestfirstgrade,
            pestsecondgrade=pestsecondgrade,
            researchpeople=researchperson,
            remark=remark,
            pestpicurl1=pestpicurl1,
            pestpicurl2=pestpicurl2,
            longitude=longitude,
            latitude=latitude,
        )
    except Exception as e:
        response['code'] = 1001
        response['message'] = str(e)
    return HttpResponse(json.dumps(response))


def Del_pest(request, id):
    ret = {'status': True}
    try:
        Pestinfo.objects.filter(id=id).delete()
    except Exception as e:
        ret['status'] = False
    import json
    return HttpResponse(json.dumps(ret))


def showForm(request, id):
    pestinfo = Pestinfo.objects.filter(id=id)
    return render(request, 'ahpests/pestdetailForm.html', {"pestinfo": pestinfo})


def Login(request):
    return render(request, 'userlogin.html')

@csrf_exempt
def uploadpic(request):
    img = request.FILES['file']
    url = upload(img)  # upload方法在下面写
    # print url
    return HttpResponse(url)

    # file = request.FILES.values()[0]
    # localfile = os.path.join("static", file.name)
    # print localfile
    # # ACCESS_KEY = "QQiUHtzzECnxapoHwo40RcIayl4YntiObCoDh4T7"
    # # SECRET_KEY = "vUPjp3kkkZlXY35_9i35MxB1DHgc921jK-bESQgh"
    # # bucketname = "test"
    # key = str(uuid.uuid1()).replace('-', '')
    # # prefixurl = "http://7u2iif.com1.z0.glb.clouddn.com/"
    # # auth = qiniu.Auth(ACCESS_KEY, SECRET_KEY)
    # # policy = {
    # #     'callbackUrl': 'http://your.domain.com/callback.php',
    # #     'callbackBody': 'filename=$(fname)&filesize=$(fsize)'
    # # }
    # # # localfile = './sync/bbb.jpg'
    # # getUpToken = auth.upload_token(bucketname, key, 3600)
    # # print getUpToken
    # # ret, info = qiniu.put_file(getUpToken, key, localfile)
    # # print ret,info
    # # info1 = '{0}{1}'.format(prefixurl, ret['key'])
    # ret = qiniu_upload(key, localfile)
    # print ret
    # # assert ret['key'] == key
    # # assert ret['hash'] == etag(localfile)
    # return HttpResponse(ret)