# coding: utf-8
from __future__ import absolute_import, print_function, unicode_literals

import time
from gm_types.gaia import IMAGE_TYPE, FILTER_WORD_TYPE

from api.models import Order, ServiceComment, ServiceCommentOption, service_comment_manager
from api.tool.log_tool import logging_exception
from api.tool.user_tool import get_user_from_context
from api.tool.filterword_tool import filterword_by_custom
from rpc.decorators import bind, bind_context, list_interface
from rpc.tool.error_code import gen, CODES



@bind_context('api/service/comment_info', login_required=True)
def get_comment_info(ctx, order_id):
    user = get_user_from_context(ctx)

    try:
        order = Order.objects.get(pk=order_id, user_id=user.id)
    except:
        pass
        # return gen(CODES.ORDER_NOT_FOUND)

    if order.servicecomment_exists():
        return gen(CODES.SERVICE_COMMENT_CREATED)

    service = order.simple_data()
    service_image = service['service']['image_header']
    comment_options = ServiceCommentOption.all_level_options

    return {
        'service_image': service_image,
        'comment_options': comment_options,
    }


@bind_context('api/service/comment_create', login_required=True)
def create_service_comment(ctx, order_id, rating, operation_effect, doctor_attitude, hospital_env,
                           comment_content=None, comment_options=None, images=None, create_diary=True,
                           update_diary_version=False):
    user = get_user_from_context(ctx)
    try:
        order = Order.objects.get(pk=order_id, user_id=user.id)
    except:
        return gen(CODES.ORDER_NOT_FOUND)

    if order.servicecomment_exists():
        return gen(CODES.SERVICE_COMMENT_CREATED)

    #美购评价敏感词过滤。以前的代码没有对数字的过滤，本次沿用
    filterword_by_custom(filter_type=FILTER_WORD_TYPE.TOPIC_REPLY, content=comment_content, isfilternum=False)

    diary_id = order.diary_id()
    if not diary_id:
        # 7.6.35 后评论默认生成日记帖
        result_diary = order.create_diary()
        diary_id = result_diary['diary_id']

    if diary_id and create_diary:
        try:
            diary_image = []
            for image in images:
                diary_image.append({
                    "image": image,
                    "type": IMAGE_TYPE.POST_OPERATION_IMAGE,
                    "timestamp": int(time.time()),
                    "modified_image_url": image,
                    "is_cover": False
                })
            cover_image = None
            if len(diary_image) > 0:
                diary_image[0]['is_cover'] = True
                cover_image = diary_image[0]['image']

            _kw = {
                "content": comment_content,
                "images": diary_image,
            }

            if update_diary_version:
                rpc_params = {
                    "diary_id": diary_id,
                    "topic_list": [_kw, ],
                }
                rpc_url = 'diary/update_v2'
            else:
                rpc_params = _kw
                rpc_params.update({
                    "diary_id": diary_id,
                    "cover": cover_image,
                })
                rpc_url = 'diary/update'

            ctx.rpc_remote[rpc_url](**rpc_params).unwrap()
        except:
            logging_exception()

    create_kwargs = {
        'service': order.service,
        'order': order,
        'rating': rating,
        'images': images if images else [],
        'operation_effect': operation_effect,
        'doctor_attitude': doctor_attitude,
        'hospital_env': hospital_env,
        'content': comment_content or '',
        'comment_options': comment_options,
    }

    try:
        comment = ServiceComment.create_comment(**create_kwargs)

        # 解决订单小红点问题, 冗余
        order.order_has_service_comment = bool(comment)
        order.save()
    except:
        logging_exception()
        return gen(CODES.CREATE_SERVICE_COMMENT_FAILED)

    return {'comment_id': comment.id, 'diary_id': diary_id}


@bind('api/service/comment_detail')
def get_comment_detail(service_id, option_count_min=0, need_default_praise=False):
    data = service_comment_manager.get_comment_detail(service_id=service_id, option_count_min=option_count_min)

    count_dic = service_comment_manager.get_comment_count(service_id=service_id, need_default_praise=need_default_praise)
    data['evaluate_count'] = count_dic.get("all_count", 0)
    data['all_comments_count'] = data['evaluate_count']
    if need_default_praise:
        data["default_rating_count"] = count_dic.get("default_rating_count", 0)
    return data


@bind('api/service/comment_detail_with_comment')
def get_comment_detail_with_comment(service_id, option_count_min=0):
    data = service_comment_manager.get_comment_detail_with_comment(service_id=service_id, option_count_min=option_count_min)
    return data


@bind('api/service/comment_list')
@list_interface(offset_name='start_num', limit_name='count')
def get_comment_list(service_id, comment_option=None, start_num=0, count=10,
                     order_ids=None, rate=None):
    data = service_comment_manager.get_comment_list(
        service_id=service_id, comment_option=comment_option, start_num=start_num,
        count=count, rate=rate, order_ids=order_ids
    )
    return data


@bind_context('api/service/comment_detail_by_id', login_required=True)
def get_comment_detail_by_id(ctx, order_id):
    user = get_user_from_context(ctx)
    order = Order.objects.get(id=order_id, user_id=user.id)
    comment = order.servicecomment_set.all().first()
    return comment.comment_detail()


@bind('api/service/service_default_comment_list')
def get_service_default_comment_list(service_id, start_num=0, count=10):
    """
    获取美购默认评价列表
    :param service_id:
    :param start_num:
    :param count:
    :return:
    """
    default_comment_list = ServiceComment.objects.filter(
        service_id=service_id, is_online=True, is_effect=True, default_rating=True
    ).order_by('-rating', '-id')[start_num: start_num + count]

    return {
        "default_comments": [comment.comment_info_for_list() for comment in default_comment_list]
    }
