# coding=utf-8

import json
from django.db import transaction
from rest_framework.views import APIView
from rest_framework.decorators import action

from utils.custom_modelviewset import CustomModelViewSet
from utils.permission import isLogin
from utils import response_ok
from apps.log.models import BizLog
# from apps.admin import admin_log

from .serializers import WechatAppletSerializer, MsgTemplateSerializer
from apps.WechatApplet.filters import WechatAppletFilter, MsgTemplateFilter
from apps.WechatApplet.models import WechatApplet, MessageTemplate
from apps.WechatTp.models import WechatTp
from django.contrib.auth import get_user_model

User = get_user_model()
from apps.account.models import CustomerWechat


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

    def get(self, request):
        tp = WechatTp.getDefault()
        ret = tp.getTemplateList()
        return response_ok(ret)

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

    def get(self, request):
        tp = WechatTp.getDefault()
        ret = tp.getDraftTemplateList()
        return response_ok(ret)


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

    def get(self, request):
        data = {
            'temp_types': [],
            'wechat_apps': [],
        }

        for type in MessageTemplate.TYPE_CHOICE:
            item = {
                'id': type[0],
                'name': type[1],
            }
            data['temp_types'].append(item)

        rows = WechatApplet.objects.filter(is_authorize=True)
        for row in rows:
            item = {
                'id': row.id,
                'name': row.nick_name,
            }
            data['wechat_apps'].append(item)

        return response_ok(data)


class WxMsgTempView(APIView):

    def get(self, request):
        appid = request.GET.get('appid')
        data = []
        if request.user and request.user.is_authenticated:
            wechat = CustomerWechat.objects.filter(customer=request.user, wechat_app__authorizer_appid=appid).first()
            if not wechat:
                return response_ok(data)
            rows = MessageTemplate.objects.filter(wechat_app=wechat.wechat_app)
            if request.user.type == User.EMPLOYEE:
                rows = rows.filter(type__in=[MessageTemplate.CREATE_ORDER, MessageTemplate.PAY_ORDER])
            elif request.user.type == User.AGENT:
                rows = rows.filter(
                    type__in=[MessageTemplate.CONFIRM_ORDER, MessageTemplate.DELIVER, MessageTemplate.CREATE_ORDER])
            else:
                rows = rows.filter(type=MessageTemplate.CREATE_ORDER)

            rows = rows.values_list('template', flat=True)
            return response_ok(rows)
        return response_ok(data)


class WechatAppletViewSet(CustomModelViewSet):
    permission_classes = [isLogin, ]
    queryset = WechatApplet.objects.filter(is_admin=False)
    serializer_class = WechatAppletSerializer

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

    @action(methods=['post'], detail=True)
    def upload_code(self, request, pk):
        # 上传代码
        template_id = request.POST.get('template_id')
        user_version = request.POST.get('user_version')
        user_desc = request.POST.get('user_desc')
        app = WechatApplet.getById(pk)
        with transaction.atomic():
            app.uploadCode(template_id, user_version, user_desc)
            BizLog.objects.addnew(self.request.user, BizLog.INSERT, u'小程序上传审核代码，id=%d' % app.id, request.POST.dict())
        return response_ok()

    @action(methods=['post'], detail=False)
    def batch_upload_code(self, request):
        # 批量上传代码
        template_id = request.POST.get('template_id')
        user_version = request.POST.get('user_version')
        user_desc = request.POST.get('user_desc')
        app_ids = json.loads(request.POST.get('ids'))

        apps = WechatApplet.objects.filter(id__in=app_ids)
        for app in apps:
            try:
                with transaction.atomic():
                    app.uploadCode(template_id, user_version, user_desc)
            except:
                pass
        # admin_log(request.user, BizLog.INSERT, u'小程序批量上传审核代码', request.POST.dict())

        return response_ok()

    @action(methods=['post'], detail=False)
    def add_to_temp(self, request):
        # 上传草稿箱模板到标准模板
        draft_id = request.POST.get('draft_id')
        tp = WechatTp.getDefault()
        tp.addToemplate(draft_id)
        with transaction.atomic():
            BizLog.objects.addnew(self.request.user, BizLog.INSERT, u'小程序上传草稿到标准模板，draft_id=%s' % draft_id)
        return response_ok()

    @action(methods=['post'], detail=False)
    def refresh_audit_status(self, request):
        # 查询最新一次提交代码的审核状态  多选更新 审核状态
        app_ids = json.loads(request.POST.get('ids'))
        for app_id in app_ids:
            app = WechatApplet.getById(app_id)
            app.refreshAuditStatus()
        return response_ok()

    @action(methods=['post'], detail=True)
    def set_secret(self, request, pk):
        secret = request.POST.get('secret')
        app = WechatApplet.getById(pk)
        with transaction.atomic():
            app.secret = secret
            app.save()
            # admin_log(request.user, BizLog.INSERT, u'设置小程序秘钥, id=%d' % app.id, secret)
        return response_ok()

    @action(methods=['post'], detail=True)
    def set_merchant(self, request, pk):
        agent_num = request.POST.get('agent_num')
        agent_key = request.POST.get('agent_key')
        app = WechatApplet.getById(pk)
        with transaction.atomic():
            app.agent_num = agent_num
            app.agent_key = agent_key
            app.save()
            # admin_log(request.user, BizLog.INSERT, u'设置小程序商户号和商户秘钥, id=%d' % app.id)
        return response_ok()

    @action(methods=['post'], detail=False)
    def add_plugin(self, request):
        app_ids = json.loads(request.POST.get('ids'))
        for app_id in app_ids:
            apps = WechatApplet.getById(app_id)
            apps.addPlugin()
        return response_ok()

    @action(methods=['post'], detail=False)
    def release(self, request):
        app_ids = json.loads(request.POST.get('ids'))
        for app_id in app_ids:
            app = WechatApplet.getById(app_id)
            app.releaseApplet()
        return response_ok()

    @action(methods=['post'], detail=True)
    def upload_cert(self, request, pk):
        file = request.FILES.get('file', None)
        app = WechatApplet.getById(pk)
        with transaction.atomic():
            app.upload_cert_file(file)
            # admin_log(request.user, BizLog.INSERT, u'设置小程序企业支付api证书, id=%d' % app.id)
        return response_ok()


class MsgTemplateViewSet(CustomModelViewSet):
    permission_classes = [isLogin, ]
    queryset = MessageTemplate.objects.filter()
    serializer_class = MsgTemplateSerializer

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

    def perform_create(self, serializer):
        super(MsgTemplateViewSet, 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.wechat_app.principal_name, instance.id), validated_data)

    def perform_update(self, serializer):
        super(MsgTemplateViewSet, 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.wechat_app.principal_name, instance.id), validated_data)

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        BizLog.objects.addnew(self.request.user, BizLog.DELETE,
                              u'删除模板[%s]，id=%d' % (instance.wechat_app.principal_name, instance.id))
        super(MsgTemplateViewSet, self).perform_destroy(instance)
        return response_ok()
