# -*- coding: UTF-8 -*-
import functools
import logging
import traceback
from gm_rpcd.all import bind
from libs.es import es_query
import operator
from libs.cache import redis_client
import json

logger = logging.getLogger(__name__)
import time

MAX_LOAD = 200
GROUP_SIZE = 10


@bind('dymas/search/query_principal')
def query_principal(query='', doctor_type=0, offset=0, size=10):
    now = int(time.time())

    """
    医生医院说横划栏专栏
    :param query:
    :return:
    """
    try:
        """
        先获取该医生或医院下边的直播，直播预告，视频贴
        """
        # 先获取视频
        all_video_list = []
        is_online_video, unline_video = get_live_by_doctor_id(query, offset, size)

        # 获取预告和视频贴
        video_list = get_one_page_tractate(query, offset, size)

        for item in is_online_video:
            all_video_list.append(item)
        for item in video_list:
            if len(is_online_video) > 0:
                if item["principal_type"] != 3:
                    all_video_list.append(item)
            else:
                all_video_list.append(item)

        for item in unline_video:
            all_video_list.append(item)

        """
         再获取该医生或者机构的文本贴、免费招募
        """
        tractate_list = get_tractate_by_doctor_id(query, offset, size, doctor_type=doctor_type)

        return {"video_list": all_video_list, "tractate_list": tractate_list}

    except:

        logging.error("catch exception,logins:%s" % traceback.format_exc())

        return {'video_list': [], "tractate_list": []}


@bind('dymas/search/query_principal_sort')
def query_principal_sort(query='', doctor_type=0, offset=0, size=10):
    """
    医生医院二级页面混排
    :param query:
    :return:
    """
    try:
        tractate_video_list = get_two_page_data(query, doctor_type)

        return {"tractate_video_list": tractate_video_list[offset:offset + size]}
    except:

        logging.error("catch exception,logins:%s" % traceback.format_exc())

        return {"tractate_video_list": []}


def get_live_by_doctor_id(query, offset, size):
    """
    先获取直播中的视频和直播回放
    :param query:
    :param offset:
    :param size:
    :return:
    """
    video_list_online = []
    video_list_unonline = []
    q = {}

    q["query"] = {
        "bool": {
            "must": [{
                "term": {
                    "doctor_id": query
                }
            }, {
                "term": {
                    "principal_type": 1
                }

            }, {
                "term": {
                    "live_status": True
                }
            }, {
                "term": {
                    "is_online": False
                }
            }
            ]
        }
    }
    q["sort"] = {
        "start_time": {
            "order": "desc"
        }
    }
    res = es_query("principal", q, offset=offset, size=size)
    res_hit = res["hits"]["hits"]
    for item in res_hit:
        if '_source' in item:
            id = item["_source"]["id"]
            principal_type = item["_source"]["principal_type"]
            is_online = item["_source"]["is_online"]
            video_list_online.append({"id": id, "principal_type": principal_type})

    # 回放
    q["query"] = {
        "bool": {
            "must": [{
                "term": {
                    "doctor_id": query
                }
            }, {
                "term": {
                    "principal_type": 1
                }

            }, {
                "term": {
                    "topic_is_online": True
                }
            }, {
                "term": {
                    "is_online": True
                }
            }, {
                "term": {
                    "topic_isnull": True
                }
            }
            ]
        }
    }
    q["sort"] = {
        "start_time": {
            "order": "desc"
        }
    }
    res = es_query("principal", q, offset=offset, size=size)
    res_hit = res["hits"]["hits"]
    for item in res_hit:
        if '_source' in item:
            id = item["_source"]["id"]
            principal_type = item["_source"]["principal_type"]
            video_list_unonline.append({"id": id, "principal_type": principal_type})

    return video_list_online, video_list_unonline


def get_tractate_by_doctor_id(query, offset, size, doctor_type):
    """
    获取视频贴 文本贴 招募
    :param query:
    :param offset:
    :param size:
    :param doctor_type:
    :return:
    """
    now = int(time.time())

    if doctor_type == 1:
        q = {}
        q["query"] = {
            "bool": {
                "must": [{
                    "term": {
                        "doctor_id": query
                    }
                }, {
                    "term": {
                        "principal_type": 5
                    }

                }, {
                    "term": {
                        "is_online": True
                    }
                }, {
                    "term": {
                        "article_type": 1
                    }
                }, {
                    "term": {
                        "status": 3
                    }
                }
                ]
            }
        }

        q["sort"] = {
            "show_order": {
                "order": "asc"
            },
            "start_time": {
                "order": "desc"
            }
        }
    else:

        q = {}
        q["query"] = {
            "bool": {
                "must": [{
                    "term": {
                        "doctor_id": query
                    }
                }, {
                    "term": {
                        "is_online": True
                    }
                }
                ],
                "minimum_should_match": 1,
                "should": [
                    {
                        "bool": {
                            "filter": [
                                {
                                    "term": {
                                        "principal_type": 2
                                    }
                                }, {
                                    "range": {
                                        "start_time": {
                                            "lte": now
                                        }
                                    }
                                }, {
                                    "range": {
                                        "end_time": {
                                            "gte": now
                                        }
                                    }
                                }
                            ]
                        }},
                    {
                        "bool": {
                            "filter": [
                                {
                                    "term": {
                                        "principal_type": 5
                                    }
                                }, {
                                    "term": {
                                        "article_type": 1
                                    }
                                }, {
                                    "term": {
                                        "status": 3
                                    }
                                }
                            ]
                        }}
                ]
            }
        }

        q["sort"] = {
            "principal_type": {
                "order": "asc"
            },
            "show_order": {
                "order": "asc"
            },
            "start_time": {
                "order": "desc"
            }
        }

    tractate_video_list = []
    res = es_query("principal", q, offset=offset, size=size)
    res_hit = res["hits"]["hits"]
    for item in res_hit:
        if '_source' in item:
            id = item["_source"]["id"]
            principal_type = item["_source"]["principal_type"]
            tractate_video_list.append({"id": id, "principal_type": principal_type})

    return tractate_video_list


def get_notice_by_doctor_id(query, offset, size):
    """
    获取预告
    :param query:
    :return:
    """
    now = int(time.time())
    q = {}

    yugao_list = []

    q["query"] = {
        "bool": {
            "must": [{
                "term": {
                    "doctor_id": query
                }
            }, {
                "term": {
                    "principal_type": 3
                }

            }, {
                "range": {
                    "start_time": {
                        "lte": now
                    }
                }
            }, {
                "range": {
                    "end_time": {
                        "gte": now
                    }
                }
            }, {
                "range": {
                    "zhibo_time": {
                        "gte": now
                    }
                }
            }
            ]
        }
    }
    q["sort"] = {
        "start_time": {
            "order": "desc"
        }
    }
    res = es_query("principal", q, offset=offset, size=size)
    res_hit = res["hits"]["hits"]
    for item in res_hit:
        if '_source' in item:
            id = item["_source"]["id"]
            principal_type = item["_source"]["principal_type"]
            yugao_list.append({"id": id, "principal_type": principal_type})

    return yugao_list


def get_one_page_tractate(query, offset, size):
    """
    获取一级页面的文本栏数据
    :param query:
    :param offset:
    :param size:
    :return:
    """
    video_list = []
    now = int(time.time())
    q = {}
    q["query"] = {
        "bool": {
            "must": [{
                "term": {
                    "doctor_id": query
                }
            }, {
                "term": {
                    "is_online": True
                }
            }
            ],
            "minimum_should_match": 1,
            "should": [
                {
                    "bool": {
                        "filter": [
                            {
                                "term": {
                                    "principal_type": 3
                                }
                            }, {
                                "range": {
                                    "start_time": {
                                        "lte": now
                                    }
                                }
                            }, {
                                "range": {
                                    "end_time": {
                                        "gte": now
                                    }
                                }
                            }, {
                                "range": {
                                    "zhibo_time": {
                                        "gte": now
                                    }
                                }
                            }
                        ]
                    }
                },
                {
                    "bool": {
                        "filter": [
                            {
                                "term": {
                                    "principal_type": 4
                                }
                            }, {
                                "term": {
                                    "article_type": 2
                                }
                            }, {
                                "term": {
                                    "status": 3
                                }
                            }
                        ]
                    }
                }

            ]
        }
    }
    q["sort"] = {
        "principal_type": {
            "order": "asc"
        },
        "show_order": {
            "order": "asc"
        },
        "start_time": {
            "order": "desc"
        }
    }

    res = es_query("principal", q, offset=offset, size=size)
    res_hit = res["hits"]["hits"]

    logging.info("get video_list:%s" % video_list)

    for item in res_hit:
        if '_source' in item:
            id = item["_source"]["id"]
            principal_type = item["_source"]["principal_type"]
            video_list.append({"id": id, "principal_type": principal_type})

    return video_list


def get_two_page_data(query, doctor_type):
    """
    获取一级页面的文本栏数据
    :param query:
    :param offset:
    :param size:
    :return:
    """
    video_list = []
    now = int(time.time())

    q = {}
    q["query"] = {
        "bool": {
            "must": [{
                "term": {
                    "doctor_id": query
                }
            }
            ],
            "minimum_should_match": 1,
            "should": [
                {
                    "bool": {
                        "filter": [
                            {
                                "term": {
                                    "principal_type": 3
                                }
                            }, {
                                "range": {
                                    "start_time": {
                                        "lte": now
                                    }
                                }
                            }, {
                                "range": {
                                    "end_time": {
                                        "gte": now
                                    }
                                }
                            }, {
                                "range": {
                                    "zhibo_time": {
                                        "gte": now
                                    }
                                }
                            }, {
                                "term": {
                                    "is_online": True
                                }
                            }
                        ]
                    }
                },
                {
                    "bool": {
                        "filter": [
                            {
                                "terms": {
                                    "principal_type": [4, 5]
                                }
                            }, {
                                "term": {
                                    "is_online": True
                                }
                            }
                        ]
                    }

                },
                {
                    "bool": {
                        "filter": [
                            {
                                "term": {
                                    "principal_type": 1
                                }
                            }, {
                                "term": {
                                    "live_status": True
                                }
                            }, {
                                "term": {
                                    "is_online": False
                                }
                            }
                        ]
                    }
                },
                {
                    "bool": {
                        "filter": [
                            {
                                "term": {
                                    "principal_type": 1
                                }
                            }, {
                                "term": {
                                    "topic_is_online": True
                                }
                            }, {
                                "term": {
                                    "is_online": True
                                }
                            }, {
                                "term": {
                                    "topic_isnull": True
                                }
                            }
                        ]
                    }
                },
            ]
        }
    }
    q["sort"] = {
        "principal_type": {
            "order": "asc"
        },
        "show_order": {
            "order": "asc"
        },
        "start_time": {
            "order": "desc"
        }
    }

    ##预告的召回条件
    if doctor_type == 0:
        activate = {
            "bool": {
                "filter": [
                    {
                        "terms": {
                            "principal_type": [2]
                        }
                    }, {
                        "range": {
                            "start_time": {
                                "lte": now
                            }
                        }
                    }, {
                        "range": {
                            "end_time": {
                                "gte": now
                            }
                        }
                    }, {
                        "term": {
                            "is_online": True
                        }
                    }
                ]
            }
        }
        q["query"]["bool"]["should"].append(activate)

    logging.info("get q:%s" % q)

    res = es_query("principal", q, offset=0, size=1000)
    res_hit = res["hits"]["hits"]
    for item in res_hit:
        if '_source' in item:
            id = item["_source"]["id"]
            principal_type = item["_source"]["principal_type"]
            is_online = item["_source"]["is_online"]
            show_order = item["_source"]["show_order"]
            start_time = item["_source"]["start_time"]
            video_list.append(
                {"id": id, "principal_type": principal_type, "is_online": is_online, "show_order": show_order,
                 "start_time": start_time})

    logging.info("get video_list:%s" % video_list)
    try:
        all_id_list = []
        is_online_live = []  # 正在直播的
        unonline_live = []  # 回放
        live_notice_list = []  # 预告
        activity_list = []  # 招募
        video_tractate_list = []  # 视频贴

        # tractate_video_order.sort(key=operator.itemgetter(2))
        # tractate_video_time.sort(key=operator.itemgetter(3), reverse=True)

        for item in video_list:

            if item["principal_type"] == 1 and item["is_online"] == False:
                is_online_live.append({"id": item["id"], "principal_type": item["principal_type"]})

            elif item["principal_type"] == 1 and item["is_online"] == True:
                unonline_live.append([item["id"], item["principal_type"], item["start_time"]])

            elif item["principal_type"] == 2:
                activity_list.append({"id": item["id"], "principal_type": item["principal_type"]})

            elif item["principal_type"] == 3:
                live_notice_list.append({"id": item["id"], "principal_type": item["principal_type"]})

            elif (item["principal_type"] == 4 or item["principal_type"] == 5) and item["show_order"] != 999:
                video_tractate_list.append([item["id"], item["principal_type"], item["show_order"]])

            elif (item["principal_type"] == 4 or item["principal_type"] == 5) and item["show_order"] == 999:
                unonline_live.append([item["id"], item["principal_type"], item["start_time"]])

            else:
                pass

        video_tractate_list.sort(key=operator.itemgetter(2))
        unonline_live.sort(key=operator.itemgetter(2), reverse=True)

        for item in is_online_live:
            all_id_list.append(item)

        for item in activity_list:
            all_id_list.append(item)

        for item in live_notice_list:
            if len(is_online_live) > 0:
                if item["principal_type"] != 3:
                    all_id_list.append(item)
            else:
                all_id_list.append(item)

        for item in video_tractate_list:
            all_id_list.append({"id": item[0], "principal_type": item[1]})

        for item in unonline_live:
            all_id_list.append({"id": item[0], "principal_type": item[1]})

        return all_id_list


    except:

        logging.error("catch exception,logins:%s" % traceback.format_exc())

        return []


@bind("dymas/search/user_principal")
def user_principal(query=0, offset=0, size=10, show_type=[]):
    try:
        channel_type = 0
        if len(show_type) < 4:
            channel_type = 1
        all_id_list = list()

        """
        用户主页的改版
        根据日记本 1 ，问题 2 ，帖子 3 ，直播的时间倒序 4

        """
        # 先获取日记本的数据
        video_list_online = []
        q = {}

        q["query"] = {
            "bool": {
                "must": [{
                    "term": {
                        "user.id": query
                    }
                }, {
                    "term": {
                        "is_online": True
                    }
                },{

                    "range": {
                        "normal_topic_count": {
                            "gt": 0
                        }
                    }
                }]
            }
        }
        q["_source"] = {
            "include": ["id", "last_topic_add_time"]
        }
        res = es_query("diary", q, offset=0, size=1000)
        res_hit = res["hits"]["hits"]
        for item in res_hit:
            if '_source' in item:
                id = item["_source"]["id"]
                created_time = item["_source"]["last_topic_add_time"]
                if not created_time:
                    created_time = "0000-00-00 00:00:00"

                all_id_list.append({"id": id, "created_time": created_time, "type": 1})

        # 获取问题的数据
        video_list_online = []
        q = {}

        q["query"] = {
            "bool": {
                "must": [{
                    "term": {
                        "user.id": query
                    }
                }, {
                    "term": {
                        "is_online": True
                    }
                }
                ]
            }
        }
        q["_source"] = {
            "include": ["id", "create_time"]
        }
        res = es_query("question", q, offset=0, size=1000)
        res_hit = res["hits"]["hits"]
        for item in res_hit:
            if '_source' in item:
                id = item["_source"]["id"]
                create_time = item["_source"]["create_time"]
                if not create_time:
                    create_time = "0000-00-00 00:00:00"

                all_id_list.append({"id": id, "created_time": create_time, "type": 2})

        # 获取贴子的数据
        video_list_online = []
        q = {}

        q["query"] = {
            "bool": {
                "must": [{
                    "term": {
                        "user_id": query
                    }
                }, {
                    "term": {
                        "is_online": True
                    }
                }
                ]
            }
        }
        q["_source"] = {
            "include": ["id", "create_time"]
        }
        res = es_query("tractate", q, offset=0, size=1000)
        res_hit = res["hits"]["hits"]
        for item in res_hit:
            if '_source' in item:
                id = item["_source"]["id"]
                create_time = item["_source"]["create_time"]
                if not create_time:
                    create_time = "0000-00-00 00:00:00"

                all_id_list.append({"id": id, "created_time": create_time, "type": 3})

        if channel_type == 0:

            # 获取直播的数据
            video_list_online = []
            video_list_unonline = []
            q = {}

            q["query"] = {
                "bool": {
                    "must": [{
                        "term": {
                            "user_id": query
                        }
                    }, {
                        "term": {
                            "principal_type": 1
                        }

                    }, {
                        "term": {
                            "live_status": True
                        }
                    }, {
                        "term": {
                            "is_online": False
                        }
                    }
                    ]
                }
            }
            q["_source"] = {
                "include": ["id", "start_time"]
            }

            res = es_query("principal", q, offset=0, size=1000)
            res_hit = res["hits"]["hits"]
            for item in res_hit:
                if '_source' in item:
                    id = item["_source"]["id"]
                    start_time = item["_source"]["start_time"]
                    otherStyleTimes = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(start_time))
                    if not otherStyleTimes:
                        otherStyleTimes = "0000-00-00 00:00:00"

                    all_id_list.append({"id": id, "created_time": otherStyleTimes, "type": 4})

            # 回放
            q["query"] = {
                "bool": {
                    "must": [{
                        "term": {
                            "user_id": query
                        }
                    }, {
                        "term": {
                            "principal_type": 1
                        }

                    }, {
                        "term": {
                            "topic_is_online": True
                        }
                    }, {
                        "term": {
                            "is_online": True
                        }
                    }, {
                        "term": {
                            "topic_isnull": True
                        }
                    }
                    ]
                }
            }
            q["_source"] = {
                "include": ["id", "start_time"]
            }
            res = es_query("principal", q, offset=0, size=1000)
            res_hit = res["hits"]["hits"]
            for item in res_hit:
                if '_source' in item:
                    id = item["_source"]["id"]
                    start_time = item["_source"]["start_time"]
                    otherStyleTimes = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(start_time))
                    if not otherStyleTimes:
                        otherStyleTimes = "0000-00-00 00:00:00"

                    all_id_list.append({"id": id, "created_time": otherStyleTimes, "type": 4})

        logging.info("get all_id_list:%s" % all_id_list)

        all_id_list.sort(key=lambda k: (k.get('created_time', None)), reverse=True)

        all_id_list_time = list()

        for item in all_id_list:
            all_id_list_time.append({"id": item["id"], "type": item["type"]})

        return {"user_principal_sort": all_id_list_time[offset:offset + size]}


    except:
        logging.error("catch exception,logins:%s" % traceback.format_exc())

        return {'user_principal_sort': []}


@bind("dymas/search/user_photoalbum_sort")
def get_user_album(user_id=-1, offset=0, size=10):
    """
    用户主页下的相册的排序  日记问答帖子的排序
    :param user_id:
    :param offset:
    :param size:
    :return:
    """
    try:
        """
        根据ID去查看相应的内容
        """
        if not isinstance(user_id, int):
            user_id = -1

        q = {
            "query": {
                "bool": {
                    "must": {
                        "term": {
                            "id": user_id
                        }
                    }
                }
            }
        }
        res = es_query('user_album', q, 0, 1)

        hits = res["hits"]["hits"]

        album = dict()

        for item in hits:
            if '_source' in item:
                album = item["_source"]["album"]
        item_lists = sorted(album, key=lambda e: e.__getitem__('create_time'), reverse=True)

        return {"user_photo_sort": item_lists[offset:offset + size], "count": len(item_lists)}

    except:

        logging.error("catch exception,logins:%s" % traceback.format_exc())

        return {"user_photo_sort": [], "count": 0}
