# coding=utf-8
import traceback
import datetime
import time
from django.db import transaction
from django.conf import settings
from rest_framework.decorators import action
from rest_framework_jwt.views import ObtainJSONWebToken,VerifyJSONWebToken,RefreshJSONWebToken
from rest_framework.serializers import ValidationError
from utils.custom_modelviewset import CustomModelViewSet
from utils import response_error, response_ok
from .serializers import TenantJWTSerializer
from utils.permission import IsTenantUser, IsAdministratorUser
from .models import Tenant, Pay
from apps.admin.tenant.serializers import TenantSerializer
from apps.admin.tenant.filters import TenantFilter
from apps.log.models import BizLog
from apps.tenant.config.models import Config
from utils.exceptions import CustomError
from apps.base import Formater
from apps.WechatApplet.models import WechatApplet

class TenantLoginView(ObtainJSONWebToken):
    serializer_class = TenantJWTSerializer

    def post(self, request, *args, **kwargs):
        try:
            ser = self.serializer_class(data=request.data)
            ser.request = request
            if ser.is_valid(raise_exception=True):
                return response_ok(ser.validated_data)
        except ValidationError as e:
            return response_error(e.detail['error'][0])


class TenantVerifyTokenView(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 TenantRefreshTokenView(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 CompanyViewSet(CustomModelViewSet):
    permission_classes = [IsAdministratorUser,]
    queryset = Tenant.objects.filter(delete=False)
    serializer_class = TenantSerializer

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

    @action(methods=['post'], detail=True)
    def update_company(self,request,pk):
        name = request.POST.get('name')
        tel = request.POST.get('tel')
        Tenant.objects.filter(id=pk).update(name=name,tel=tel)
        BizLog.objects.addnew(self.request.user.employee.tenant, self.request.user, BizLog.INSERT, u'修改企业联系人，id=%s' % pk, request.POST)
        return response_ok()

    @action(methods=['get'], detail=True)
    def get_code(self, request, pk):
        pay_channel = request.GET.get('pay_channel')
        config = Config.objects.filter(property=Config.KEY_RENEW_AMOUNT_1).first()
        year = Config.objects.filter(property=Config.KEY_RENEW_YEAR_1).first()
        if config:
            amount = Formater.formatAmount(config.value)
            year = year.value
        else:
            raise CustomError('续费金额错误')

        try:
            tenant = Tenant.objects.filter(id=pk).first()
            if 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)
                if diff >= 0:
                    start_date = tenant.end_date
                    renew_date = (tenant.end_date + datetime.timedelta(days=365*int(year))).strftime('%Y-%m-%d')
                else:
                    start_date  = today
                    renew_date = (datetime.datetime.now() + datetime.timedelta(days=365 * int(year))).strftime('%Y-%m-%d')
            else:
                raise CustomError('获取企业信息失败，请刷新重试！')
            with transaction.atomic():
                if int(pay_channel) == Pay.WECHAT:
                    line_data = Pay.wechatPay(request.user, pk ,amount)
                elif int(pay_channel) == Pay.ALIPAY:
                    line_data = Pay.alipayPay(request.user, pk ,amount)
                else:
                    raise CustomError('请选择正确的支付方式')
                data = {
                    'renew_date': '{} — {}'.format(start_date,renew_date),
                    'year': year,
                    'amount': Formater.formatAmountShow(amount),
                    'id': line_data.id,
                    'qrcode': line_data.qrcode
                }
            return response_ok(data)
        except CustomError as e:
            return response_error(str(e))
        except Exception as e:
            traceback.print_exc()
            return response_error(u'支付失败', request)

    @action(methods=['get'], detail=True)
    def get_wxapp_code(self, request, pk):
        try:
            tenant = Tenant.objects.filter(id=pk).first()
            if tenant:
                company_no = tenant.company_no
            else:
                raise CustomError('获取企业信息失败，请刷新重试！')
            if not tenant.wxapp_img:
                applet = WechatApplet.objects.filter(authorizer_appid=settings.WEAPP['appid']).first()
                filename = applet.getWXAppCode(company_no)
                tenant.wxapp_img = "{0}{1}".format(settings.MEDIA_URL,filename)
                tenant.save()

            return response_ok(tenant.wxapp_img)
        except CustomError as e:
            return response_error(str(e))
        except Exception as e:
            traceback.print_exc()
            return response_error(u'支付失败', request)

    @action(methods=['get'], detail=True)
    def confirm_pay(self, request, pk):
        pay_id = request.GET.get('pay_id')
        try:
            with transaction.atomic():
                payment = Pay.objects.filter(id=int(pay_id)).first()
                if not payment:
                    raise CustomError(u'无法找到付款单')
                if payment.status == Pay.WAIT:
                    raise CustomError(u'暂无付款信息，请付款')
                if payment.status == Pay.CONFIRM:
                    raise CustomError(u'已确认付款')
                payment.payConfirm(payment.pay_no)

        except CustomError as e:
            return response_error(str(e))
        except Exception as e:
            traceback.print_exc()
            return response_error(u'验证失败', request)
        return response_ok()
