#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging

from django.views.decorators.gzip import gzip_page
from django.utils.decorators import method_decorator
from drf_yasg.utils import swagger_auto_schema
from rest_framework.response import Response

from common.utils.views import BaseApiView
from common.utils.models import model_to_dict
from common.utils.serializers import serializer_assembly
from common.utils.return_structure import general_message

from common.configs.serializers import InitializationSerializer
from common.third_party_api.amap.openapi import AmapApi

logger = logging.getLogger('')


@method_decorator(gzip_page, name='dispatch')
class InitializationView(BaseApiView):
    serializer_class = InitializationSerializer

    @swagger_auto_schema(
        operation_description="登录",
        responses={200: serializer_assembly(InitializationSerializer)},
        tags=['account'],
    )
    def get(self, request, *args, **kwargs):
        user = self.user.to_dict()
        user["account"] = model_to_dict(self.account)
        serializer = InitializationSerializer(
            data={"user": user}, context={"perms_codes": self.perms,
                                          "enterprises": self.enterprises,
                                          "is_manager": self.is_manager,
                                          "is_customer": self.is_customer,
                                          "customer": self.customer})
        serializer.is_valid(raise_exception=True)
        data = general_message(msg="success",
                               msg_show="获取成功",
                               bean=serializer.data)
        return Response(data, status=200)


@method_decorator(gzip_page, name='dispatch')
class RegionView(BaseApiView):
    def get(self, request, *args, **kwargs):
        kv = request.GET
        data = AmapApi().district(**kv)
        dt = []
        districts = data.get("districts")
        if isinstance(districts, list):
            districts = districts[0]
            dt = districts.get("districts", [])
        data = general_message(msg="success", msg_show="获取成功", list=dt)
        return Response(data, status=200)


class GeoView(BaseApiView):
    def get(self, request, *args, **kwargs):
        kv = request.GET
        data = AmapApi().geo(**kv)
        location = None
        rst = None
        geocodes = data.get("geocodes")
        if isinstance(geocodes, list):
            if geocodes:
                location = geocodes[0].get("location")
        if location:
            dt = location.split(",")
            rst = {"longitude": dt[0], "latitude": dt[-1]}
        data = general_message(msg="success", msg_show="获取成功", data=rst)
        return Response(data, status=200)
