# coding=utf-8

import requests
from rest_framework.exceptions import NotFound
from django.db import transaction
from rest_framework.views import APIView
from rest_framework import generics
import datetime
from django.db.models import Sum,Count
from rest_framework_jwt.views import ObtainJSONWebToken,VerifyJSONWebToken,RefreshJSONWebToken
from rest_framework.serializers import ValidationError
from utils import response_ok, response_error
from apps.tenant.option.serializers import OptionSerializer,Option
from django.utils import timezone
from apps.tenant.notices.models import Notices
from apps.tenant.notices.serializers import NoticesWXSerializer
from apps.tenant.notices.filters import NoticesFilter
from utils.permission import isLogin, IsTenantUser
from utils.wx.WXBizDataCrypt import WXBizDataCrypt
from apps.tenant.poster.serializer import PosterSerializer, Poster
from apps.tenant.device.models import DeviceModel
from apps.tenant.repair_order.models import RepairOrder,RepairOrderComment
from .serializers import *

class CustomerRefreshTokenView(RefreshJSONWebToken):
    def post(self, request, *args, **kwargs):
        try:
            ser = self.serializer_class(data=request.data)
            if ser.is_valid(raise_exception=True):
                return response_ok({'token': ser.validated_data['token']})
        except ValidationError as e:
            return response_error(u'登录状态失效，请重新登录[' + e.detail['error'][0] + ']')


class CustomerVerifyTokenView(VerifyJSONWebToken):
    def post(self, request, *args, **kwargs):
        try:
            ser = self.serializer_class(data=request.data)
            if ser.is_valid(raise_exception=True):
                return response_ok({'token': ser.validated_data['token']})
        except ValidationError as e:
            return response_error(u'登录状态失效，请重新登录[' + e.detail['error'][0] + ']')


class SetUserInfoView(APIView):
    permission_classes = [isLogin, ]

    def post(self, request, *args, **kwargs):
        appid = request.POST.get('appid')
        openid = request.POST.get('openid')
        encryptedData = request.POST.get('encryptedData')
        iv = request.POST.get('iv')

        customer_wechat = CustomerWechat.objects.filter(openid=openid).first()
        if not customer_wechat:
            raise CustomError(u'未找到相应的微信客户！')

        employee = self.request.user.employee
        if customer_wechat.customer and customer_wechat.customer.id != employee.id:
            raise CustomError(u'该微信已同步其他客户！')
        if not customer_wechat.customer:
            customer_wechat.customer = employee
            customer_wechat.save()
        pc = WXBizDataCrypt(appid, customer_wechat.session_key)
        result = pc.decrypt(encryptedData, iv)
        with transaction.atomic():
            if employee.name == employee.tel:
                employee.name = result['nickName']
            employee.gender = result['gender']
            employee.face = result['avatarUrl']
            employee.save()
            customer_log(employee, BizLog.INSERT, u'客户设置信息，id=%d' % employee.id, result)
        return response_ok()


class WxLoginView(APIView):
    serializer_class = WechatLoginSerializer

    def post(self, request, *args, **kwargs):
        ser = self.serializer_class(data=request.data)
        if ser.is_valid():
            return response_ok(ser.validated_data)
        else:
            return response_error('参数错误')


class WxBindView(APIView):
    serializer_class = WechatBindSerializer

    def post(self, request, *args, **kwargs):
        ser = self.serializer_class(data=request.data)
        if ser.is_valid():
            return response_ok(ser.validated_data)
        else:
            return response_error('参数错误')

class HomeStatisticsView(APIView):
    '''小程序首页统计数据'''

    def get(self, request):
        statistics = {
            'total':0, #总报修
            'wait':0, #待维修
            'working':0, #维修中
            'complete':0, #已完工
        }
        if request.user and request.user.is_authenticated:
            tenant = request.user.employee.tenant
            rows = RepairOrder.objects.filter(tenant=tenant)
            statistics['total'] = rows.filter(status__gte=RepairOrder.CHECKED).count()
            statistics['wait'] = rows.filter(status=RepairOrder.CHECKED).count()
            statistics['working'] = rows.filter(status=RepairOrder.DISPATCH).count()
            statistics['complete'] = rows.filter(status__in=[RepairOrder.FINISH,RepairOrder.APPRAISE,]).count()
            return response_ok(statistics)
        else:
            return response_ok(statistics)

class StatisticsRepairView(APIView):
    '''小程序统计数据'''
    permission_classes = [IsTenantUser, ]
    def get(self, request):
        days = int(request.GET.get('days')) # 7 30 365
        data = []# 报修数据
        tenant = request.user.employee.tenant
        now = timezone.now()
        rows = RepairOrder.objects.filter(tenant=tenant,status__gte=RepairOrder.CHECKED)
        if days < 31:
            for d in range(days):
                date = (now + datetime.timedelta(days=-d)).strftime('%Y-%m-%d')
                item = {
                    'title':date[5:],
                    'data':rows.filter(create_time__gte=date,create_time__lte=date+' 23:59:59').count(),
                }
                data.append(item)
            data = data[::-1]
        else:
            # 得到今年的的时间 （年份） 得到的today_year等于2016年
            today_year = now.year
            # 今年的时间减去1，得到去年的时间。last_year等于2015
            last_year = int(now.year) - 1
            # 得到今年的每个月的时间。today_year_months等于1 2 3 4 5 6 7 8 9，
            today_year_months = range(1, now.month + 1)
            # 得到去年的每个月的时间  last_year_months 等于10 11 12
            last_year_months = range(now.month + 1, 13)
            # 定义列表去年的数据
            data_list_lasts = []
            # 通过for循环，得到去年的时间夹月份的列表
            # 先遍历去年每个月的列表
            for last_year_month in last_year_months:
                # 定义date_list 去年加上去年的每个月
                date_list = '%s-%s' % (last_year, last_year_month)
                # 通过函数append，得到去年的列表
                data_list_lasts.append(date_list)

            data_list_todays = []
            # 通过for循环，得到今年的时间夹月份的列表
            # 先遍历今年每个月的列表
            for today_year_month in today_year_months:
                # 定义date_list 去年加上今年的每个月
                data_list = '%s-%s' % (today_year, today_year_month)
                # 通过函数append，得到今年的列表
                data_list_todays.append(data_list)
            # 去年的时间数据加上今年的时间数据得到年月时间列表
            data_year_month = data_list_lasts + data_list_todays
            for year_months in data_year_month:
                year_month = year_months.split('-')
                year = int(year_month[0])
                month = int(year_month[1])
                item = {
                    'title': year_months,
                    'data':rows.filter(create_time__year=year, create_time__month=month).count(),
                }
                data.append(item)
        return response_ok(data)

class StatisticsEvaluateView(APIView):
    '''小程序评价统计数据'''
    permission_classes = [IsTenantUser, ]
    def get(self, request):
        days = int(request.GET.get('days')) # 7 30 365
        data = []# 评价数据
        tenant = request.user.employee.tenant
        now = timezone.now()
        date = (now + datetime.timedelta(days=-days)).strftime('%Y-%m-%d')
        # 分组统计分析
        rows = RepairOrderComment.objects.filter(repair_order__tenant=tenant,create_time__gte=date,) \
            .values('repair_user_id') \
            .annotate(starts=Sum('start'),count=Count('id')) \
            .values('repair_user__employee__name', 'starts', 'count')
        for row in rows:
            item = {
                'title':row['repair_user__employee__name'],
                'data':round(float(row['starts']) / float(row['count']),2),
            }
            data.append(item)
        data.sort(key=lambda d: d['data'], reverse=True)

        return response_ok(data)

class PosterView(generics.ListAPIView):
    '''小程序首页数据'''

    queryset = Poster.objects.filter(enable=True)
    serializer_class = PosterSerializer

    def filter_queryset(self, queryset):
        is_auth = False
        if self.request.user and self.request.user.is_authenticated:
            is_auth = True
        if is_auth:
            queryset = queryset.filter(Q(tenant__isnull=True) | Q(tenant=self.request.user.employee.tenant))
        else:
            queryset = queryset.filter(tenant__isnull=True)
        return queryset

    def list(self, request, *args, **kwargs):
        try:
            data = super(PosterView, self).list(request)
        except NotFound:
            return response_ok([])
        return data

class DictView(APIView):
    permission_classes = [isLogin, ]
    def get(self, request):
        tenant = request.user.employee.tenant
        ret = {
            'repair_type': OptionSerializer(Option.objects.filter(delete=False,type=Option.REPAIRS_TYPE, enable=True, tenant=tenant), many=True).data,
            'fault_cause': OptionSerializer(Option.objects.filter(delete=False,type=Option.FAULT_CAUSE, enable=True, tenant=tenant), many=True).data,
        }
        return response_ok(ret)


class NoticesView(generics.ListAPIView):
    queryset = Notices.objects.filter(type=Notices.NOTICE,end_time__gte=timezone.now().date())
    serializer_class = NoticesWXSerializer

    def filter_queryset(self, queryset):
        if self.request.user and self.request.user.is_authenticated:
            queryset = queryset.filter(tenant=self.request.user.employee.tenant)
            # 查看自己的通知和所有通知
            queryset = queryset.filter(Q(range=self.request.user.type) | Q(range=Notices.ALL))
        else:
            queryset = queryset.filter(tenant=0)
        f = NoticesFilter(self.request.GET, queryset=queryset)
        return f.qs

class NoticesDetailView(generics.RetrieveAPIView):
    permission_classes = [isLogin, ]
    queryset = Notices.objects.filter()
    serializer_class = NoticesWXSerializer

    def get_queryset(self):
        queryset = self.queryset.filter(tenant=self.request.user.employee.tenant)
        return queryset

    def retrieve(self, request, *args, **kwargs):
        return response_ok(NoticesWXSerializer(self.get_object()).data)

class MessageView(generics.ListAPIView):
    queryset = Notices.objects.filter(type=Notices.MESSAGE,end_time__gte=timezone.now().date())
    serializer_class = NoticesWXSerializer

    def filter_queryset(self, queryset):
        if self.request.user and self.request.user.is_authenticated:
            queryset = queryset.filter(tenant=self.request.user.employee.tenant, notice_user__user=self.request.user)
            # 查看自己的通知和所有通知
            # queryset = queryset.filter(Q(range=self.request.user.type) | Q(range=Notices.ALL))
        else:
            queryset = queryset.filter(tenant=0)
        f = NoticesFilter(self.request.GET, queryset=queryset)
        return f.qs

class MessageListView(generics.ListAPIView):
    permission_classes = [IsTenantUser, ]
    queryset = Notices.objects.filter(type=Notices.MESSAGE)
    serializer_class = NoticesWXSerializer

    def filter_queryset(self, queryset):
        queryset = queryset.filter(tenant=self.request.user.employee.tenant, notice_user__user=self.request.user)
        f = NoticesFilter(self.request.GET, queryset=queryset)
        return f.qs

class DeviceView(APIView):
    permission_classes = [isLogin, ]
    def get(self, request):
        param = request.GET.get('param')
        data = []
        rows = DeviceModel.objects.filter(tenant=request.user.employee.tenant)
        if param:
            rows = rows.filter(Q(name=param) | Q(device_no=param) | Q(device_model=param))
        else:
            rows = rows[:10]
        for item in rows:
            build_dict = {
                'id': item.id,
                'name':item.name,
                'device_no':item.device_no,
                'device_model':item.device_model,
                'branch':item.branch,
                'address':item.address,
            }
            data.append(build_dict)

        return response_ok(data)
