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

from rest_framework import serializers
from rest_framework_jwt.settings import api_settings
from django.db.models import Q, F

from common.accounts.models import UserEnterprise
from common.accounts.models import Enterprise
from common.accounts.models import UserTags
from common.accounts.models import UserRoles
from console.customer.models import Customer
from common.utils.perms_conf import union_perms_to_json_v2, CONFIG
from console.team.models import Team

logger = logging.getLogger('')
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER


class AccountSerializer(serializers.Serializer):
    id = serializers.IntegerField(help_text="账号id")
    certification_status = serializers.BooleanField(help_text="认证状态")
    account_type = serializers.CharField(max_length=32, help_text="账户类型")
    username = serializers.CharField(max_length=32, help_text="唯一名称")
    head_img = serializers.CharField(max_length=256,
                                     help_text="头像",
                                     allow_null=True)

    class Meta:
        ref_name = "config_account"


class UserSerializer(serializers.Serializer):
    account = AccountSerializer()
    nickname = serializers.CharField(max_length=32, help_text="昵称")
    wechat = serializers.CharField(max_length=32,
                                   required=False,
                                   allow_null=True,
                                   allow_blank=True,
                                   help_text="微信号")
    phone = serializers.CharField(max_length=32,
                                  required=False,
                                  allow_null=True,
                                  allow_blank=True,
                                  help_text="手机号")
    email = serializers.CharField(max_length=32,
                                  required=False,
                                  allow_null=True,
                                  allow_blank=True,
                                  help_text="邮箱")
    id = serializers.IntegerField(help_text="用户id")
    order_rec_setting = serializers.NullBooleanField(help_text="接单设置")
    order_rec_status = serializers.NullBooleanField(help_text="接单状态")

    class Meta:
        ref_name = "config_user"


class EnterprisesSerializer(serializers.Serializer):
    id = serializers.IntegerField(help_text="公司id")
    enterprise_id = serializers.CharField(max_length=32,
                                          help_text="公司id",
                                          allow_null=True)
    name = serializers.CharField(max_length=32,
                                 help_text="公司名称",
                                 allow_null=True)
    logo = serializers.CharField(max_length=255,
                                 allow_null=True,
                                 allow_blank=True,
                                 help_text="公司logo")
    address = serializers.CharField(max_length=1024,
                                    allow_null=True,
                                    allow_blank=True,
                                    help_text="公司地址")
    adcode = serializers.CharField(max_length=16,
                                   allow_null=True,
                                   allow_blank=True,
                                   help_text="区域编码")
    longitude = serializers.CharField(max_length=32,
                                      allow_null=True,
                                      allow_blank=True,
                                      help_text="经度")
    latitude = serializers.CharField(max_length=32,
                                     allow_null=True,
                                     allow_blank=True,
                                     help_text="纬度")
    is_admin = serializers.BooleanField(help_text="是否为管理员公司")

    class Meta:
        ref_name = "config_enterprise"


class RolesSerializer(serializers.Serializer):
    id = serializers.IntegerField(help_text="角色id")
    name = serializers.CharField(max_length=32, help_text="角色名称")

    class Meta:
        ref_name = "config_role"


class TeamSerializer(serializers.Serializer):
    id = serializers.IntegerField(help_text="角色id")
    name = serializers.CharField(max_length=32, help_text="组名称")
    headman_id = serializers.IntegerField(help_text="组长id")
    headman_name = serializers.CharField(max_length=32, help_text="组长")
    type = serializers.CharField(max_length=16,
                                 allow_blank=True,
                                 help_text="组类型")
    car_number = serializers.CharField(allow_null=True,
                                       max_length=32,
                                       help_text="车牌号")
    leader_id = serializers.IntegerField(allow_null=True, help_text="区块链经理id")
    leader_name = serializers.CharField(allow_null=True,
                                        max_length=32,
                                        help_text="区块链经理")

    class Meta:
        ref_name = "config_team"


class InitializationSerializer(serializers.Serializer):
    user = UserSerializer()
    enterprises = serializers.SerializerMethodField(read_only=True)
    joined_team = serializers.SerializerMethodField(read_only=True)
    leader_teams = serializers.SerializerMethodField(read_only=True)
    tags = serializers.SerializerMethodField(read_only=True)
    roles = serializers.SerializerMethodField(read_only=True)
    perms = serializers.SerializerMethodField(read_only=True)

    class Meta:
        fields = ("user", "enterprises", "joined_team", "leader_teams", "tags")

    def get_enterprises(self, instance):
        enterprises = self.context.get("enterprises")
        is_customer = self.context.get("is_customer")
        customer = self.context.get("customer")
        ents = []
        for i in enterprises:
            dt = {
                "id": i.id,
                "name": i.name,
                "adcode": i.adcode,
                "address": i.address,
                "enterprise_id": i.enterprise_id,
                "is_admin": i.is_admin,
                "latitude": i.latitude,
                "logo": i.logo,
                "longitude": i.longitude,
            }
            if is_customer:
                dt.update({"customers": [{"id":customer.id, "name": customer.name}]})
            ents.append(dt)
        return ents

    def get_joined_team(self, instance):
        data = {}
        is_manager = self.context.get("is_manager")
        if is_manager:
            teams_relate = Team.objects.filter(deleted=False).filter(
                Q(member__id=instance["user"]["id"])
                | Q(team_headman_id=instance["user"]["id"])).values(
                    leader_name=F("leader__nickname"),
                    headman_name=F("team_headman__nickname"),
                    headman_id=F("team_headman_id"))
            teams_relate_data = list(teams_relate.values())
            if teams_relate_data:
                teams_relate_data = teams_relate_data[0]
                serializer = TeamSerializer(data=teams_relate_data)
                serializer.is_valid(raise_exception=True)
                data = serializer.data
        return data

    def get_leader_teams(self, instance):
        data = []
        is_manager = self.context.get("is_manager")
        if is_manager:
            teams_relate = Team.objects.filter(
                leader_id=instance["user"]["id"]).values(
                    leader_name=F("leader__nickname"),
                    headman_name=F("team_headman__nickname"),
                    headman_id=F("team_headman_id"))
            serializer = TeamSerializer(data=list(teams_relate.values()),
                                        many=True)
            serializer.is_valid(raise_exception=True)
            data = serializer.data
        return data

    def get_tags(self, instance):
        is_manager = self.context.get("is_manager")
        if is_manager:
            user_tags = UserTags.objects.filter(
                user_id=instance["user"]["id"]).values("tag_id",
                                                       tag_name=F("tag__name"))
            return list(user_tags.values("tag_id", "tag_name"))
        return []

    def user_role(self, instance):
        return UserRoles.objects.filter(user_id=instance["user"]["id"]).values(
            "role_id", role_name=F("role__name"))

    def get_roles(self, instance):
        is_manager = self.context.get("is_manager")
        if is_manager:
            user_roles = self.user_role(instance)
            return list(user_roles.values("role_id", "role_name"))
        return []

    def get_perms(self, instance):
        perms_codes = self.context.get("perms_codes")
        rst = union_perms_to_json_v2(CONFIG, perms_codes)
        return rst
