# _*_coding:utf-8_*_

from django.core.paginator import Paginator, EmptyPage
from django.db.models import Q, F

from ..models import ExtendField, DetailInfo, BaseInfo
from ..utils.custom_tool import format_params_handle
from ..utils.j_join_list import JJoinList

class UserListService:
    # 显式列出 BaseInfo 模型的字段
    base_fields = [
        "id", "uuid", "user_no", "username", "nickname", "fullname", "phone", "email",
        "avatar", "user_type", "user_vip", "user_level", "user_info", "register_time",
        "register_ip", "privacies", "is_auth", "is_delete", "is_using"
    ]

    # 显式列出 DetailInfo 模型的字段
    detail_fields = [
        "user_id", "real_name", "sex", "birth", "tags", "signature", "avatar", "cover",
        "id_card_type", "id_card_no", "language", "region_code", "more",
        "field_1", "field_2", "field_3", "field_4", "field_5", "field_6",
        "field_7", "field_8", "field_9", "field_10", "field_11", "field_12",
        "field_13", "field_14", "field_15"
    ]

    @classmethod
    def user_list(cls, params=None, page=1, size=20, sort="-id"):
        """
        用户基础信息列表服务（优化版）
        改进点：去除未映射的字段
        :param params: 搜索字典参数 dict
        :param page: 当前页码，默认为1
        :param size: 每页大小，默认为20
        :param sort: 排序字段，默认为"-id"
        :return:  data,err
        """
        if params is None:
            params = {}

        # 1. 初始化排序和字段映射
        sort = sort if sort in ["id", "-id", "register_time", "-register_time"] else "-id"

        # 获取有效的拓展字段映射
        field_map_list = list(ExtendField.objects.all().values("field", 'field_index'))
        valid_field_indices = {item['field_index'] for item in field_map_list}

        # 2. 处理搜索参数
        # 创建详情字段别名映射
        detail_alias_dict = {
            field: f'user_detail_info__{field}'
            for field in cls.detail_fields
            if field in valid_field_indices or not field.startswith('field_')
        }

        # 处理参数中的拓展字段
        new_params = {
            item['field_index']: params[item['field']]
            for item in field_map_list
            if item['field'] in params
        }

        # 3. 构建查询条件
        search_params = format_params_handle(
            param_dict={**params, **new_params},
            filter_filed_list=[
                                  "username", "email", "phone", "nickname",
                                  "fullname", "is_using", "user_level"
                              ] + [f for f in cls.detail_fields if
                                   f in valid_field_indices or not f.startswith('field_')],
            alias_dict={
                "username": "username__contains",
                "email": "email__contains",
                "phone": "phone__contains",
                "nickname": "nickname__contains",
                "fullname": "fullname__contains",
                **detail_alias_dict
            },
            is_remove_empty=True,
        )

        # 4. 构建基础查询集
        user_base_set = BaseInfo.objects.filter(is_delete=0)
        user_base_set = user_base_set.extra(
            select={'register_time': 'DATE_FORMAT(register_time, "%%Y-%%m-%%d %%H:%%i:%%s")'}
        ).order_by(sort).annotate(
            user_id=F("id"),
            user_uuid=F("uuid")
        )

        # 5. 应用搜索条件
        if search_params:
            search_filters = [Q(**{key: value}) for key, value in search_params.items()]
            if search_filters:
                combined_filter = search_filters[0]
                for f in search_filters[1:]:
                    combined_filter |= f
                user_base_set = user_base_set.select_related('user_detail_info').filter(combined_filter)

        # 6. 分页处理
        paginator = Paginator(user_base_set, size)
        try:
            page_set = paginator.page(page)
        except EmptyPage:
            page_set = paginator.page(paginator.num_pages)

        # 7. 构建结果数据
        # 7.1 基础信息
        base_list = [{k: getattr(user, k) for k in cls.base_fields} for user in page_set.object_list]

        # 7.2 详情信息（只包含有效字段）
        valid_detail_fields = [
            f for f in cls.detail_fields
            if f in valid_field_indices or not f.startswith('field_')
        ]

        detail_dict = [
            {
                k: getattr(user.user_detail_info, k)
                if hasattr(user, 'user_detail_info') and hasattr(user.user_detail_info, k)
                else None
                for k in valid_detail_fields
            }
            for user in page_set.object_list
        ]

        # 7.3 映射字段名
        field_mapping = {item['field_index']: item['field'] for item in field_map_list}
        detail_list = [
            {field_mapping.get(k, k): v for k, v in detail.items()}
            for detail in detail_dict
        ]

        # 8. 合并结果
        base_join_detail = JJoinList.join(base_list, detail_list, 'id', "user_id")

        return {
            'size': int(size),
            'page': int(page),
            'count': paginator.count,
            'list': base_join_detail
        }, None