# coding=utf-8
import traceback
import json
import datetime
from django.db.models import Q
from rest_framework.decorators import action
from django.db import transaction
from rest_framework.views import APIView
from rest_framework.serializers import ValidationError
from utils.permission import permission_required, isLogin, check_permission
from django.contrib.auth.models import Group, Permission
from rest_framework_jwt.views import ObtainJSONWebToken, RefreshJSONWebToken
from utils import response_error, response_ok
from django.contrib.auth import get_user_model
from django.utils import timezone

User = get_user_model()
from apps.account.serializers import JWTSerializer, EmployeeSerializer, GroupDictSerializer, GroupSerializer
from utils.custom_modelviewset import CustomModelViewSet
from apps.account.filters import UserFilter, GroupFilter
from apps.account.models import ManageStoreUser,OfficeStoreUser
from apps.log.models import BizLog
from apps.account.consts import PermissionMenu
from collections import OrderedDict
from apps.agent.models import Store, Agent,GeneralAgent
from utils.exceptions import CustomError
from apps.customer.models import ReportCustomer, NewCustomerRemind, NewCustomer

class LoginView(ObtainJSONWebToken):
    serializer_class = JWTSerializer

    def post(self, request, *args, **kwargs):
        try:
            ser = self.serializer_class(data=request.data)
            ser.request = request
            # 判断门店是否在用、在有效期内
            if ser.is_valid(raise_exception=True):
                user = User.objects.filter(id=ser.validated_data['user_id']).first()
                store = Store.objects.filter(id=user.store_id).first()
                if store and (store.enable == False or (store.end_date.strftime('%Y-%m-%d')) < (timezone.now().strftime('%Y-%m-%d')) ):
                    raise CustomError(u'当前店面不可用，请联系管理员！')
                return response_ok(ser.validated_data)
        except ValidationError as e:
            return response_error(e.detail['error'][0])
        except CustomError as e:
            return response_error(str(e))

class RefreshTokenView(RefreshJSONWebToken):

    def post(self, request, *args, **kwargs):
        try:
            ser = self.serializer_class(data=request.data)
            if ser.is_valid(raise_exception=True):
                user = ser.validated_data['user']
                store = Store.objects.filter(id=user.store_id).first()
                if store and (store.enable == False or (store.end_date.strftime('%Y-%m-%d')) < (
                timezone.now().strftime('%Y-%m-%d')) ):
                    raise CustomError(u'当前店面不可用，请联系管理员！')
                return response_ok({'token': ser.validated_data['token']})
        except ValidationError as e:
            return response_ok({'error':True})
        except CustomError as e:
            return response_error(str(e))

class ChangePassword(APIView):

    def post(self, request, *args, **kwargs):
        id = request.GET.get('id')
        data = json.loads(request.body)
        try:
            with transaction.atomic():
                user = User.objects.filter(id=id).first()
                if not user:
                    raise CustomError(u'用户信息错误，请刷新重试！')
                user.change_password(data['new_password'], data['confirm_password'], data['old_password'])
                BizLog.objects.addnew(request.user, BizLog.UPDATE, u"修改密码[%s],id=%d" % (user.username, user.id))
        except CustomError as e:
            return response_error(str(e))
        except Exception as e:
            traceback.print_exc()
            return response_error(u'保存失败！')
        return response_ok()


class EmployeeViewSet(CustomModelViewSet):
    permission_classes = [isLogin, ]
    queryset = User.objects.filter()
    serializer_class = EmployeeSerializer

    @permission_required('account.browse_user')
    def filter_queryset(self, queryset):
        queryset = queryset.filter()
        user = self.request.user
        queryset = queryset.filter(
            Q(store_id__in=self.request.user.get_manager_range()) |
            Q(id=user.id) |
            Q(create_user=user) |

            Q(agent__create_user=user) |
            Q(general_agent__create_user=user)
        )

        f = UserFilter(self.request.GET, queryset=queryset)
        return f.qs

    @permission_required('account.add_user')
    def perform_create(self, serializer):
        super(EmployeeViewSet, self).perform_create(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        BizLog.objects.addnew(self.request.user, BizLog.INSERT,
                              u'添加用户[%s]，id=%d' % (instance.name, instance.id), validated_data)

    @permission_required('account.add_user')
    def perform_update(self, serializer):
        super(EmployeeViewSet, self).perform_update(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        BizLog.objects.addnew(self.request.user, BizLog.UPDATE,
                              u'修改用户[%s]，id=%d' % (instance.name, instance.id), validated_data)

    @permission_required('account.delete_user')
    def perform_destroy(self, instance):
        ManageStoreUser.objects.filter(manage_user=instance).delete()
        BizLog.objects.filter(user=instance).delete()
        BizLog.objects.addnew(self.request.user, BizLog.DELETE,
                              u'删除账号[%s]，id=%d' % (instance.username, instance.id))
        super(EmployeeViewSet, self).perform_destroy(instance)

    @action(methods=['post'], detail=True)
    def join(self, request, pk):
        check_permission(request, 'account.check_user')
        try:
            with transaction.atomic():
                instance = self.get_object()
                instance.check_user = request.user
                instance.status = User.INSERVICE
                instance.save()
                BizLog.objects.addnew(self.request.user, BizLog.INSERT,
                                      u'员工[%s]入职，id=%d' % (instance.name, instance.id))
            return response_ok()
        except Exception as e:
            traceback.print_exc()
            return response_error(u'入职失败')

    @action(methods=['post'], detail=True)
    def branch(self, request, pk):
        check_permission(request, 'account.manager_store')
        data = json.loads(request.POST.get('stores'))
        try:
            with transaction.atomic():
                instance = self.get_object()
                ManageStoreUser.objects.filter(manage_user_id=pk).delete()
                for row in data:
                    ManageStoreUser.objects.create(store_id=row, manage_user_id=pk)

                # 给员工设置管理门店，把已取消管理门店下面的客户提醒删除
                user = User.objects.filter(id=pk).first()
                data.extend(user.get_office_stores())
                # 删除不管理的门店提醒
                NewCustomerRemind.objects.filter(remind_user=user).exclude(store__in=data).delete()
                # 根据选择的人员所管理店面，创建内部跟踪提醒
                #  把next_time用当前日期加上5天
                if user.has_perm('customer.inner_review'):
                    next_time = (timezone.now() + datetime.timedelta(days=5)).strftime('%Y-%m-%d')
                    for store in data:
                        customers = NewCustomer.objects.filter(store_id=store, status=NewCustomer.NORMAL).values('id')
                        for customer in customers:
                            remind = NewCustomerRemind.objects.filter(customer_id=customer['id'],remind_user_id=pk,store_id=store).first()
                            if not remind:
                                NewCustomerRemind.objects.create(customer_id=customer['id'], next_time=next_time, remind_user_id=pk,
                                                         is_employee=False, store_id=store)

                BizLog.objects.addnew(self.request.user, BizLog.INSERT,
                                      u'设置账号[%s]管理门店，id=%d' % (instance.username, instance.id), data)
            return response_ok()
        except Exception as e:
            traceback.print_exc()
            return response_error(u'保存失败')

    @action(methods=['post'], detail=True)
    def office(self, request, pk):
        check_permission(request, 'account.manager_store')
        data = json.loads(request.POST.get('stores'))
        try:
            with transaction.atomic():
                instance = self.get_object()
                OfficeStoreUser.objects.filter(office_user_id=pk).delete()
                for row in data:
                    OfficeStoreUser.objects.create(store_id=row, office_user_id=pk)
                # 删除不任职门店提醒
                data.extend(instance.get_office_stores())
                NewCustomerRemind.objects.filter(remind_user=instance).exclude(store__in=data).delete()
                BizLog.objects.addnew(self.request.user, BizLog.INSERT,
                                      u'设置账号[%s]任职门店，id=%d' % (instance.username, instance.id), data)
            return response_ok()
        except Exception as e:
            traceback.print_exc()
            return response_error(u'保存失败')


class GroupsViewSet(CustomModelViewSet):
    permission_classes = [isLogin, ]
    queryset = Group.objects.filter()
    serializer_class = GroupSerializer

    @permission_required('account.manager_permissions')
    def filter_queryset(self, queryset):
        if not self.request.user.is_superuser:
            groups = self.request.user.groups.all()
            queryset = queryset.filter(id__in=[g.id for g in groups])
        f = GroupFilter(self.request.GET, queryset=queryset)
        return f.qs

    @permission_required('account.manager_permissions')
    def perform_create(self, serializer):
        super(GroupsViewSet, self).perform_create(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        BizLog.objects.addnew(self.request.user, BizLog.INSERT,
                              u'添加权限组[%s]，id=%d' % (instance.name, instance.id), validated_data)

    @permission_required('account.manager_permissions')
    def perform_update(self, serializer):
        super(GroupsViewSet, self).perform_update(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        BizLog.objects.addnew(self.request.user, BizLog.UPDATE,
                              u'修改权限组[%s]，id=%d' % (instance.name, instance.id), validated_data)

    @permission_required('account.manager_permissions')
    def destroy(self, request, *args, **kwargs):
        with transaction.atomic():
            instance = self.get_object()
            # user_count = instance.user_set.all().count()
            # if user_count:
            #     raise CustomError(u'该权限组已分配给用户，禁止删除！')

            BizLog.objects.addnew(self.request.user, BizLog.DELETE,
                                  u'删除权限组[%s]，id=%d' % (instance.name, instance.id))
            instance.delete()
        return response_ok()


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

    @permission_required('account.manager_permissions')
    def get(self, request):
        rows = Permission.objects.all().exclude(name__startswith='Can')
        perms_menus = PermissionMenu()
        rows = perms_menus.sort_perms(rows)
        menus = OrderedDict()
        for row in rows:
            item = {'id': row.id, 'name': row.name}
            mn = perms_menus.get_menuname_of_contenttype(row.content_type.app_label, row.content_type.model)
            if mn in menus:
                permissions = menus[mn]
            else:
                permissions = menus[mn] = OrderedDict()
            if row.content_type.name in permissions:
                if not item in permissions[row.content_type.name]:
                    permissions[row.content_type.name].append(item)
            else:
                permissions[row.content_type.name] = [item, ]
        return response_ok(menus)


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

    @permission_required('account.add_user')
    def get(self, request):
        rows = Group.objects.filter()
        if not request.user.is_superuser:
            groups = request.user.groups.all()
            rows = rows.filter(id__in=[g.id for g in groups])
        serializer = GroupDictSerializer(rows, many=True)
        return response_ok(serializer.data)


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

    @permission_required('account.manager_store')
    def get(self, request):
        id = request.GET.get('id')
        store_data = []
        # 查询当前用户的代理商和管理的门店
        general_agents = GeneralAgent.objects.filter()
        if not request.user.is_superuser:
            general_agents = GeneralAgent.objects.filter(id=request.user.general_agent_id)
        general_agents = general_agents.values('id', 'name')
        for general_agent in general_agents:
            general_agent_item = {
                'title': general_agent['name'],
                'id': general_agent['id'],
                'field': 'general_agent',
                'children': [],
            }
            agents = Agent.objects.filter(general_agent_id=general_agent['id'])
            if request.user.agent:
                agents = agents.filter(id=request.user.agent_id)
            agents = agents.values('id', 'name')
            for agent in agents:
                agent_item= {
                    'title': agent['name'],
                    'id': agent['id'],
                    'field': 'agent',
                    'children': [],
                }
                general_agent_item['children'].append(agent_item)
                stores = Store.objects.filter(agent_id=agent['id'], id__in=request.user.get_manager_range(),
                                              check_user__isnull=False, enable=True).values('id', 'name')
                for store in stores:
                    manage_store = ManageStoreUser.objects.filter(manage_user_id=id, store_id=store['id']).first()
                    checked = manage_store and True or False
                    store_item = {
                        'title': store['name'],
                        'id': store['id'],
                        'checked': checked,
                        'field': 'store_{}'.format(store['id']),
                    }
                    agent_item['children'].append(store_item)
            store_data.append(general_agent_item)

        return response_ok(store_data)


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

    def get(self, request):
        # 查询当前用户管理门店树形结构
        agent_dict = {}
        general_agent_dict = {}
        data = []

        exist_agents = []
        manage_storess = request.user.get_manager_range()
        for store_id in manage_storess:
            store = Store.objects.filter(id=store_id, check_user__isnull=False, enable=True).values('name','agent_id')
            if not store:
                continue
            store_item = {
                'title': store[0]['name'],
                'id': store_id,
                'field': 'store',
                'children': [],
            }
            office_user_id = OfficeStoreUser.objects.filter(store_id=store_id).values('office_user_id')
            employees = User.objects.filter(Q(store_id=store_id) | Q(id__in=office_user_id), is_active=True).values('id', 'name')
            for employee in employees:
                user_item = {
                    'title': employee['name'],
                    'id': '{0}_{1}'.format(store_id, employee['id']),# 门店_人员
                    'field': 'user',
                }
                store_item['children'].append(user_item)

            try:
                agent_dict[store[0]['agent_id']].append(store_item)
            except:
                agent_dict[store[0]['agent_id']] = [store_item]

            exist_agents.append(store[0]['agent_id'])
        ######## 代理
        exist_agents = list(set(exist_agents))
        exist_general_agents = []
        agents = Agent.objects.filter(id__in=exist_agents).values('id', 'name', 'general_agent_id')
        for agent in agents:
            agent_item = {
                'title': agent['name'],
                'id': agent['id'],
                'field': 'agent',
                'children': agent_dict[agent['id']] ,
            }

            if not request.user.agent:
                # 当前用户有代理商。此时加载和总代理平行的账号
                agent_users = User.objects.filter(agent__isnull=False, is_active=True, store__isnull=True)
            elif not request.user.store:
                # 当前用户有门店。此时加载和代理商平行的账号
                agent_users = User.objects.filter(agent_id=agent['id'], is_active=True, store__isnull=True)
            else:
                # 有门店和代理商，这是店内人员。不需要在加载任何账号
                agent_users = []
            for agent_user in agent_users:
                if agent_user.has_perm('customer.inner_review'):
                    agent_user_item = {
                        'title': agent_user.name,
                        'id': agent_user.id,
                        'field': 'user',
                    }
                    agent_item['children'].insert(0,agent_user_item)

            try:
                general_agent_dict[agent['general_agent_id']].append(agent_item)
            except:
                general_agent_dict[agent['general_agent_id']] = [agent_item]

            exist_general_agents.append(agent['general_agent_id'])
        ###### 总代理
        exist_general_agents = list(set(exist_general_agents))
        general_agents = GeneralAgent.objects.filter(id__in=exist_general_agents).values('id', 'name')
        for general_agent in general_agents:
            general_agent_item = {
                'title': general_agent['name'],
                'id': general_agent['id'],
                'field': 'general_agent',
                'children': general_agent_dict[general_agent['id']],
            }
            # 当前用户没有代理商，则是总代理账号。此时加载和总代理平行的账号
            if not request.user.agent:
                general_agent_users = User.objects.filter(general_agent_id=general_agent['id'], agent__isnull=True, store__isnull=True, is_active=True)
                for general_agent_user in general_agent_users:
                    if general_agent_user.has_perm('customer.inner_review'):
                        general_agent_user_item = {
                            'title': general_agent_user.name,
                            'id': general_agent_user.id,
                            'field': 'user',
                        }
                        general_agent_item['children'].insert(0, general_agent_user_item)
            data.append(general_agent_item)
        # 总代理只有一级，去掉总代理
        # if len(data) == 1:
        #     data = data[0]['children']
        # 代理只有一级，去掉代理
        # if len(data) == 1:
        #     data = data[0]['children']
        return response_ok(data)


class HomeStatisticsView(APIView):
    # 首页统计
    permission_classes = [isLogin, ]

    def get(self, request):
        statistics = {
            'today_report': 0,  # 本日新增报备
            'mouth_report': 0,  # 本月新增报备
            'general_report': 0,  # 总报备
        }
        if request.user or request.user.is_authenticated:
            today = timezone.now().date()
            reports = ReportCustomer.objects.filter(store__in=request.user.get_manager_range(),
                                                    report_status=ReportCustomer.CHECKED)
            statistics['today_report'] = reports.filter(check_time__gte=str(today) + ' 00:00:00').count()
            statistics['mouth_report'] = reports.filter(check_time__year=today.year, check_time__month=today.month).count()
            statistics['general_report'] = reports.count()
            return response_ok(statistics)
        else:
            return response_ok(statistics)


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

    @permission_required('account.manager_store')
    def get(self, request):
        id = request.GET.get('id')
        store_data = []
        # 查询当前用户的代理商和管理的门店
        general_agents = GeneralAgent.objects.filter()
        if not request.user.is_superuser:
            general_agents = GeneralAgent.objects.filter(id=request.user.general_agent_id)
        general_agents = general_agents.values('id', 'name')
        for general_agent in general_agents:
            general_agent_item = {
                'title': general_agent['name'],
                'id': general_agent['id'],
                'field': 'general_agent',
                'children': [],
            }
            agents = Agent.objects.filter(general_agent_id=general_agent['id'])
            if request.user.agent:
                agents = agents.filter(id=request.user.agent_id)
            agents = agents.values('id', 'name')
            for agent in agents:
                agent_item = {
                    'title': agent['name'],
                    'id': agent['id'],
                    'field': 'agent',
                    'children': [],
                }
                general_agent_item['children'].append(agent_item)
                stores = Store.objects.filter(agent_id=agent['id'], id__in=request.user.get_manager_range(),
                                              check_user__isnull=False, enable=True).values('id', 'name')
                for store in stores:
                    office_store = OfficeStoreUser.objects.filter(office_user_id=id, store_id=store['id']).first()
                    checked = office_store and True or False
                    store_item = {
                        'title': store['name'],
                        'id': store['id'],
                        'checked': checked,
                        'field': 'store_{}'.format(store['id']),
                    }
                    agent_item['children'].append(store_item)
            store_data.append(general_agent_item)

        return response_ok(store_data)
