# coding=utf-8
from django.conf import settings
import time
import datetime
import traceback

from django.utils import timezone
from rest_framework.views import APIView


from utils.custom_modelviewset import CustomModelViewSet
from utils.permission import IsAdministratorUser,IsTenantUser
from apps.tenant.models import Tenant
from apps.tenant.employee.models import Employee
from apps.admin import admin_log
from apps.log.models import BizLog
from .serializers import TenantSerializer
from django.db import transaction
from utils import response_ok
from utils.exceptions import CustomError
from rest_framework.decorators import action
from utils import response_ok, response_error
from apps.account.models import User
from .filters import TenantFilter
from apps.tenant.option.models import Option
from apps.tenant.notices.models import Notices, NoticesToUser
from apps.WechatApplet.models import WechatApplet
from apps.tenant.config.models import Config


class TenantViewSet(CustomModelViewSet):
    permission_classes = [IsAdministratorUser, ]
    queryset = Tenant.objects.all()
    serializer_class = TenantSerializer

    def filter_queryset(self, queryset):
        f = TenantFilter(self.request.GET, queryset=queryset)
        return f.qs

    def perform_create(self, serializer):
        super(TenantViewSet, self).perform_create(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        admin_log(self.request.user, BizLog.INSERT, u'添加企业[%s] id=%d' % (instance.company_name, instance.id), validated_data)

    def perform_update(self, serializer):
        super(TenantViewSet, self).perform_update(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        admin_log(self.request.user, BizLog.INSERT, u'修改企业[%s] id=%d' % (instance.name, instance.id), validated_data)

    @action(methods=['post'], detail=True)
    def super_tenant(self,  request, pk):
        name = request.POST.get('name')
        username = request.POST.get('username')
        password = request.POST.get('password')
        try:
            with transaction.atomic():
                tenant = Tenant.objects.filter(pk=pk).first()
                if not tenant:
                    raise CustomError('当前企业无效，请刷新！')
                user = User.objects.filter(username=username).first()
                if user:
                    user.type = User.SUPER
                    user.save()
                    Employee.objects.filter(user=user).update(tenant=tenant, type=Employee.SUPER)
                else:
                    user = Employee.create_super_admin(tenant, name, username, password)
                option_data1 = {
                    'tenant': tenant,
                    'type': 1,
                    'name': u'桌椅、板凳',
                    'create_user': user,
                }
                option_data2 = {
                    'tenant': tenant,
                    'type': 2,
                    'name': u'设备老化',
                    'create_user': user,
                }
                Option.objects.create(**option_data1)
                Option.objects.create(**option_data2)
                notice_data = {
                    'title':'企业入驻审核通知，请点击查看！',
                    'content':'''您的企业入驻审核已通过，请牢记一下内容：
                    企业名称：{0}<br>
                    企业编号：{1}<br>
                    超级管理员账号：{2}<br>
                    超级管理员密码：{3}<br>
                    电脑端管理系统网址：https://baoxiu.zzliaoyuan.com/
                    '''.format(tenant.company_name,tenant.company_no,username,password),
                    'create_user':request.user,
                    'tenant':tenant,
                    'type':Notices.MESSAGE,
                    'range':Notices.ADMIN,
                    'end_time':(timezone.now() + datetime.timedelta(days=10)).strftime('%Y-%m-%d'),
                }
                notice = Notices.objects.create(**notice_data)
                NoticesToUser.objects.create(notice=notice,user=user)

                admin_log(request.user, BizLog.INSERT, u'企业[%s]添加超级账号[%s]' % (tenant.company_name,username))
            return response_ok()
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))

    @action(methods=['post'], detail=True)
    def check(self, request, pk):
        # 审核
        status = request.POST.get('status')
        reject_reason = request.POST.get('reason')
        try:
            with transaction.atomic():
                instance = Tenant.getById(pk)
                # 审核
                if instance.status > settings.DEFAULT:
                    raise CustomError('当前企业已审核！')

                instance.status = status
                instance.reject_reason = reject_reason
                if int(status) == settings.PASS:
                    days = Config.getIntValue(Config.FREE_DAYS)
                    instance.end_date = (datetime.datetime.now() + datetime.timedelta(days=int(days))).strftime('%Y-%m-%d')
                    instance.save()

                if not instance.wxapp_img:
                    applet = WechatApplet.objects.filter(authorizer_appid=settings.WEAPP['appid']).first()
                    filename = applet.getWXAppCode(instance.company_no)
                    instance.wxapp_img = "{0}{1}".format(settings.MEDIA_URL, filename)
                instance.save()
                BizLog.objects.addnew(None, request.user, BizLog.INSERT, u'审核企业[%s]状态为[%s],id=%d' % (instance.company_name, status, instance.id))

        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
        return response_ok('审核完成！')

class MemberRemindViewSet(APIView):
    permission_classes = [IsTenantUser, ]

    def get(self, request):
        tenant = request.user.employee.tenant

        today = datetime.datetime.now().strftime('%Y-%m-%d')
        today_stamp = time.mktime(time.strptime(today, "%Y-%m-%d"))
        end_date = time.mktime(time.strptime(tenant.end_date.strftime('%Y-%m-%d'), '%Y-%m-%d'))
        diff = (int(end_date) - int(today_stamp))/86400
        notice = Notices.objects.filter(type=Notices.RENEW, end_time__isnull=True,tenant=tenant)

        if not notice and diff <= 30:
            employee = Employee.objects.filter(tenant=tenant,type=Employee.SUPER).first()
            user = employee.user
            notice_data = {
                'title': '会员到期提醒，请点击查看！',
                'content': '您的会员还有{0}天到期！请及时续费，以免影响您的正常使用！'.format(diff),
                'tenant': tenant,
                'type': Notices.RENEW,
                'range': Notices.ADMIN,
                # 'end_time': (timezone.now() + datetime.timedelta(days=int(diff))).strftime('%Y-%m-%d'),
            }
            notice = Notices.objects.create(**notice_data)
            NoticesToUser.objects.create(notice=notice, user=user)
        return response_ok()
