# -*- coding: utf-8 -*-

import json
from datetime import datetime

from django.http import HttpResponseRedirect, HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.db.models import F
from django.contrib.auth.decorators import login_required

from core import resource
from core import paginator
from core.jsonresponse import create_response,JsonResponse

import models as app_models
import export
from apps import request_util
from modules.member import integral as integral_api
from mall.promotion import utils as mall_api
from mall import export as mall_export
import termite.pagestore as pagestore_manager
from mall.models import WxCertSettings

FIRST_NAV = mall_export.MALL_PROMOTION_AND_APPS_FIRST_NAV
COUNT_PER_PAGE = 20

class Group(resource.Resource):
	app = 'apps/group'
	resource = 'group'



	@login_required
	def api_get(request):
		"""
		响应GET
		"""
		cert_setting = WxCertSettings.objects.filter(owner_id=request.manager.id)
		response = create_response(200)
		if cert_setting.count() > 0:
			response.data = {'flag':True}
		else:

			response.data = {'flag':False}
		return response.get_response()


	@login_required
	def get(request):
		"""
		响应GET
		"""
		cert_setting = WxCertSettings.objects.filter(owner_id=request.manager.id)

		if not cert_setting.count() > 0:
			return HttpResponseRedirect("/mall2/weixin_certificate/")

		if 'id' in request.GET:
			project_id = 'new_app:group:%s' % request.GET.get('related_page_id', 0)
			#处理删除异常
			try:
				group = app_models.Group.objects.get(id=request.GET['id'])
			except:
				c = RequestContext(request, {
					'first_nav_name': FIRST_NAV,
					'second_navs': mall_export.get_promotion_and_apps_second_navs(request),
					'second_nav_name': mall_export.MALL_APPS_SECOND_NAV,
					'third_nav_name': "groups",
					'is_deleted_data': True
				})

				return render_to_response('group/templates/editor/workbench.html', c)

			is_create_new_data = False
		else:
			group = None
			is_create_new_data = True
			project_id = 'new_app:group:0'

		_, app_name, real_project_id = project_id.split(':')
		if real_project_id != '0':
			pagestore = pagestore_manager.get_pagestore('mongo')
			pages = pagestore.get_page_components(real_project_id)
			if not pages:
				c = RequestContext(request, {
					'first_nav_name': FIRST_NAV,
					'second_navs': mall_export.get_promotion_and_apps_second_navs(request),
					'second_nav_name': mall_export.MALL_APPS_SECOND_NAV,
					'third_nav_name': "groups",
					'is_deleted_data': True
				})

				return render_to_response('group/templates/editor/workbench.html', c)

		c = RequestContext(request, {
			'first_nav_name': FIRST_NAV,
			'second_navs': mall_export.get_promotion_and_apps_second_navs(request),
			'second_nav_name': mall_export.MALL_APPS_SECOND_NAV,
			'third_nav_name': "groups",
			'group': group,
			'is_create_new_data': is_create_new_data,
			'project_id': project_id,
		})

		return render_to_response('group/templates/editor/workbench.html', c)

	@login_required
	def api_put(request):
		"""
		响应PUT
		"""
		data = request_util.get_fields_to_be_save(request)
		group = app_models.Group(**data)
		group.save()
		error_msg = None

		data = json.loads(group.to_json())
		data['id'] = data['_id']['$oid']
		if error_msg:
			data['error_msg'] = error_msg
		response = create_response(200)
		response.data = data
		return response.get_response()

	@login_required
	def api_post(request):
		"""
		响应POST
		"""
		data = request_util.get_fields_to_be_save(request)
		# request = request.POST['target']
		update_data = {}
		update_fields = set(['name',
							'start_time',
							'end_time',
							'group_dict',
							'status',
							'product_id',
							'product_img',
							'product_name',
							'product_price',
							'product_socks',
							'product_sales',
							'product_usercode',
							'product_create_at',
							'rules',
							'material_image',
							'share_description'])
		for key, value in data.items():
			# print 'key:',key
			# print 'value:',value
			if key in update_fields:
				update_data['set__'+key] = value
		app_models.Group.objects(id=request.POST['id']).update(**update_data)

		response = create_response(200)
		return response.get_response()

	@login_required
	def api_delete(request):
		"""
		响应DELETE
		"""
		# app_models.Group.objects(id=request.POST['id']).delete()
		app_models.Group.objects(id=request.POST['id']).update(set__is_use=app_models.IS_USE_NO)
		response = create_response(200)
		return response.get_response()

