from django.db import transaction
from .repositories import user_repo, user_sql_repo
from common.utils.exceptions import ValidationError
from common.utils.perms_conf import union_perms_to_json_v2, CONFIG


class UserService(object):
    @transaction.atomic()
    def create_user_roles(self, user_id, role_ids):
        if role_ids is None:
            pass
        has_roles = user_repo.get_user_roles(user_id)
        has_role_ids = has_roles.values_list("role_id", flat=True)
        if list(has_role_ids) == role_ids:
            return has_roles
        else:
            has_roles.delete()
            if not role_ids:
                return []
            return user_repo.create_user_roles(user_id, role_ids)

    @transaction.atomic()
    def create_user_tags(self, user_id, tag_ids):
        if tag_ids is None:
            pass
        has_tags = user_repo.get_user_tags(user_id)
        has_tag_ids = has_tags.values_list("tag_id", flat=True)
        if list(has_tag_ids) == tag_ids:
            return has_tags
        else:
            has_tags.delete()
            if not tag_ids:
                return []
            return user_repo.create_user_tags(user_id, tag_ids)

    @transaction.atomic()
    def create_user_organizations(self, user_id, organization_ids):
        if organization_ids is None:
            pass
        has_organizations = user_repo.get_user_organizations(user_id)
        has_organizations_ids = has_organizations.values_list(
            "organization_id", flat=True)
        if list(has_organizations_ids) == organization_ids:
            return has_organizations
        else:
            has_organizations.delete()
            if not organization_ids:
                return []
            return user_repo.create_user_organizations(user_id,
                                                       organization_ids)

    def disabled_account(self, user_id):
        user_repo.disabled_account(user_id)

    def enabled_accounts(self, user_ids):
        user_repo.enabled_accounts(user_ids)

    def clean_orphan_accounts(self):
        user_repo.clean_orphan_accounts()

    @transaction.atomic()
    def delete_user(self, user_id, enterprise_ids):
        # 处理多公司情况
        exit_other_enterprises = user_repo.delete_user_enterprises(
            user_id, enterprise_ids)
        if not exit_other_enterprises:
            user_repo.delete_user(user_id, enterprise_ids)
            user_service.create_user_roles(user_id, [])
            user_service.create_user_tags(user_id, [])
            user_service.create_user_organizations(user_id, [])

    def search_users(self, enterprise_id, organization_id, role_id, tag_id,
                     team_headman, service_staff, value, choices):
        return user_repo.search_users(enterprise_id, organization_id, role_id,
                                      tag_id, team_headman, service_staff,
                                      value, choices)

    def create_user_enterprises(self, user_id, enterprise_id):
        return user_repo.create_user_enterprises(user_id, enterprise_id)

    def create_multi_user_enterprises(self, user_ids, enterprise_id):
        return user_repo.create_multi_user_enterprises(user_ids, enterprise_id)

    def get_tag_users(self, tag_id, enterprise_id):
        data = {}
        tag = user_repo.get_tag(tag_id)
        if not tag:
            raise ValidationError("标签不存在")
        data["id"] = tag.id
        data["name"] = tag.name
        data["users"] = user_repo.get_tag_users(tag_id, enterprise_id)
        return data

    def get_role_perms(self, role_id):
        perms = user_repo.get_role_perms(role_id)
        perms_codes = perms.values_list("perms__code", flat=True)
        return perms_codes

    def get_union_role_perms(self, role_ids):
        perms = user_repo.get_union_roles_perms(role_ids)
        perms_codes = perms.values_list("perms__code", flat=True)
        return list(set(perms_codes))

    def get_role_perms_tree(self, role_id):
        perms_codes = self.get_role_perms(role_id)
        rst = union_perms_to_json_v2(CONFIG, perms_codes)
        return rst

    def get_union_roles_perms_tree(self, role_ids):
        perms_codes = self.get_union_role_perms(role_ids)
        rst = union_perms_to_json_v2(CONFIG, perms_codes)
        return rst

    @transaction.atomic()
    def create_role_perms(self, role_id, perms_codes):
        perms_codes = user_repo.create_role_perms(role_id, perms_codes)
        rst = union_perms_to_json_v2(CONFIG, perms_codes)
        return rst

    def delete_role_perms(self, role_id):
        user_repo.delete_role_perms(role_id)

    def get_user_perms(self, user_id):
        perms_codes = []
        user_roles = user_repo.get_user_roles(user_id)
        if user_roles:
            role_ids = user_roles.values_list("role_id", flat=True)
            perms_codes = self.get_union_role_perms(role_ids)
        return perms_codes

    def user_info_validate(self,
                           username,
                           email,
                           phone,
                           user_id=None,
                           account_id=None):
        if username:
            if username.isdigit():
                raise ValidationError("账号名不能为纯数字")
            if "@" in username:
                raise ValidationError("账号名不能包含@")
            if user_repo.get_account_by_name(username, account_id):
                raise ValidationError("账号名重复")
        if email:
            if user_repo.get_user_by_email(email, user_id):
                raise ValidationError("邮箱重复")
        if phone:
            if not phone.isdigit():
                raise ValidationError("手机号不合法")
            if user_repo.get_user_by_phone(phone, user_id):
                raise ValidationError("手机号重复")

    def get_users_info(self):
        user_repo.get_users_info()

    def get_user(self, enterprise_id, **kwargs):
        return user_sql_repo.get_user(enterprise_id, **kwargs)

    def get_user_info(self, enterprise_id, user_id):
        return user_sql_repo.get_user_info(enterprise_id, user_id)

    def get_user_center_info(self, enterprise_id, user_id):
        return user_sql_repo.get_user_center_info(enterprise_id, user_id)

    @transaction.atomic()
    def create_user(self, enterprise, login_user, payload):
        return user_sql_repo.create_user(enterprise, login_user, payload)

    @transaction.atomic()
    def update_user(self, enterprise, user_id, payload):
        return user_sql_repo.update_user(enterprise, user_id, payload)

    def set_password(self, user_id, password):
        return user_sql_repo.set_password(user_id, password)

    @transaction.atomic()
    def del_user(self, user_id, enterprise_id):
        return user_sql_repo.del_user(user_id, enterprise_id)


user_service = UserService()
