"""子客服读取商家模板：按 merchant_id 查 ShangjiaMoban（与老板同一批数据）。"""
from decimal import Decimal, InvalidOperation

from django.core.paginator import Paginator
from django.db.models import Q

from config.models import ShangjiaMoban
from rank.models import Chenghao


def _format_moban(moban):
    texiao_json = ''
    label_name = ''
    if moban.TitleID:
        try:
            ch = Chenghao.query.get(id=moban.TitleID)
            label_name = ch.mingcheng
            texiao_json = ch.texiao_miaoshu or ''
        except Chenghao.DoesNotExist:
            pass
    return {
        'mobanId': moban.id,
        'shangpinTypeId': moban.ProductTypeID,
        'jieshao': moban.TemplateDesc,
        'jiage': str(moban.Price),
        'fabushuliang': moban.PublishedCount,
        'commissionEnabled': moban.CommissionGrabEnabled,
        'commissionValue': str(moban.CommissionPrice) if moban.CommissionPrice is not None else None,
        'labelId': moban.TitleID,
        'labelName': label_name,
        'texiaoJson': texiao_json,
        'createTime': moban.CreateTime.strftime('%Y-%m-%d %H:%M:%S') if moban.CreateTime else '',
    }


def list_merchant_templates(merchant_id, data):
    """
    查询某商家全部模板（UserID=merchant_id）。
    返回 (payload_dict, http_status) 与 /peizhi/sjddmblb 一致，code=200。
    """
    leixing_id = data.get('shangpinTypeId')
    if not leixing_id:
        return {'code': 400, 'msg': '商品类型ID不能为空', 'data': {}}, 400

    get_type = int(data.get('getType', 2))
    page = int(data.get('page', 1))
    page_size = int(data.get('pageSize', 50))
    keyword = data.get('keyword', '')
    min_price = data.get('minPrice', '')
    label_id = data.get('labelId', None)
    if label_id is not None:
        try:
            label_id = int(label_id)
        except (ValueError, TypeError):
            label_id = None

    query = Q(UserID=merchant_id, ProductTypeID=leixing_id)

    if get_type == 1:
        if keyword:
            keyword = str(keyword).strip()
            try:
                mid = int(keyword)
                query &= Q(id=mid) | Q(TemplateDesc__icontains=keyword)
            except ValueError:
                query &= Q(TemplateDesc__icontains=keyword)
        if min_price:
            try:
                query &= Q(Price__gte=Decimal(str(min_price)))
            except (InvalidOperation, ValueError, TypeError):
                pass
        if label_id:
            query &= Q(TitleID=label_id)
        mobans = ShangjiaMoban.query.filter(query).order_by('-id')
        formatted = [_format_moban(m) for m in mobans]
        return {
            'code': 200,
            'msg': '搜索成功',
            'data': {'list': formatted, 'total': len(formatted), 'hasMore': False},
        }, 200

    queryset = ShangjiaMoban.query.filter(query).order_by('-id')
    paginator = Paginator(queryset, page_size)
    if page < 1 or page > max(paginator.num_pages, 1):
        return {'code': 400, 'msg': '页码超出范围', 'data': {}}, 400

    current_page = paginator.page(page)
    formatted = [_format_moban(m) for m in current_page.object_list]
    has_more = current_page.has_next()
    if len(formatted) < page_size:
        has_more = False

    return {
        'code': 200,
        'msg': '获取成功',
        'data': {
            'list': formatted,
            'total': paginator.count,
            'hasMore': has_more,
            'currentPage': page,
            'pageSize': page_size,
            'totalPages': paginator.num_pages,
        },
    }, 200
