from django.db.models import Q
from ..models import ExtendField
from ..utils.custom_tool import format_params_handle

class ExtendFieldService:
    # 显式列出 ExtendField 模型的字段
    base_fields = [
        "id", "field_index", "field", "label", "type", "unit", "default", "config", "sort", "description"
    ]

    @classmethod
    def extend_field_list(cls, params=None):
        """
        扩展字段列表服务
        :param params: 搜索字典参数 dict
        :return: data, err
        """
        if params is None:
            params = {}

        # 处理搜索参数
        search_params = format_params_handle(
            param_dict=params,
            filter_filed_list=["field_index", "field", "label", "type", "unit", "default", "config", "sort", "description"],
            alias_dict={
                "field_index": "field_index__contains",
                "field": "field__contains",
                "label": "label__contains",
                "type": "type__contains",
                "unit": "unit__contains",
                "default": "default__contains",
                "config": "config__contains",
                "sort": "sort__contains",
                "description": "description__contains"
            },
            is_remove_empty=True,
        )

        # 获取未删除的扩展字段
        extend_field_set = ExtendField.objects.filter()

        # 根据搜索参数进行过滤
        if search_params:
            search_filters = [Q(**{key: value}) for key, value in search_params.items()]
            combined_filter = search_filters[0]
            for filter in search_filters[1:]:
                combined_filter |= filter
            extend_field_set = extend_field_set.filter(combined_filter)

        # 获取基础信息列表
        base_list = [{k: getattr(extend_field, k) for k in cls.base_fields} for extend_field in extend_field_set]

        return {'list': base_list}, None

    @classmethod
    def extend_field_add(cls, params):
        """
        添加扩展字段
        :param params: 添加参数
        :return: data, err
        """
        try:
            # 检查 field_index 是否已经存在
            if ExtendField.objects.filter(field_index=params.get("field_index")).exists():
                return None, "field_index 已存在"

            extend_field = ExtendField.objects.create(**params)
            return extend_field.to_json(), None
        except Exception as e:
            return None, str(e)

    @classmethod
    def extend_field_edit(cls, params, extend_field_id):
        """
        修改扩展字段
        :param params: 修改参数
        :param extend_field_id: 扩展字段ID
        :return: data, err
        """
        try:
            extend_field = ExtendField.objects.filter(id=extend_field_id).first()
            if not extend_field:
                return None, "扩展字段不存在"

            for key, value in params.items():
                setattr(extend_field, key, value)
            extend_field.save()

            return extend_field.to_json(), None
        except Exception as e:
            return None, str(e)

    @classmethod
    def extend_field_delete(cls, extend_field_id):
        """
        删除扩展字段
        :param extend_field_id: 扩展字段ID
        :return: data, err
        """
        try:
            extend_field = ExtendField.objects.filter(id=extend_field_id).first()
            if not extend_field:
                return None, "扩展字段不存在"

            extend_field.delete()
            return {"id": extend_field_id}, None
        except Exception as e:
            return None, str(e)