#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
#   Author  :   RobertDing
#   E-mail  :   robertdingx@gmail.com
#   Date    :   18/01/31 11:03:49
#   Desc    :   项目相关逻辑
#

from gm_types.wiki import DIRECTORY_TYPE, PRODUCT_TYPE, PRODUCT_PARAMS

from wiki.models.directory import Directory
from wiki.models.product import Product
from wiki.models.item import Item

from wiki.logices.product import product_cover_image


def item_cover_image(item):
    pass


def similar_collect(collect):
    """ 同级collect 去掉自己
    """
    collect_cells = Directory.objects.filter(collect=collect, is_online=True)
    types = set([x.model_type for x in collect_cells])
    cells = Directory.objects.filter(model_type__in=types, is_online=True).exclude(collect=collect).order_by('rank')
    return [x.collect for x in cells if x.collect]


def get_item_related_product_id_by_type(item_id, type):
    """
    获取项目关联相关type物品ID
    """
    item = Item.objects.filter(id=item_id).first()
    return [i.id for i in item.related_product.filter(product_type=type)] if item else []


def similar_product(item, product_type):
    return [{
        'id': x.id, 'name': x.name, 'image_url': product_cover_image(x), 'description': x.description
    } for x in item.related_product.filter(product_type=product_type, is_online=True)]


class ContrastData(object):
    item_contrast = [
        'name', 'fit_people', 'advantage', 'disadvantage', 'treatment_method',
        'anesthesia_method', 'ache_level', 'price', 'treatment_time',
        'maintain_time', 'recover_time', 'treatment_num'
    ]

    drug_contrast = [
        'name', 'origin', 'company', 'application_range', 'attestation', 1, 2, 3, 4, 5, 6,
        'anesthesia_method', 'price', 'maintain_time'
    ]

    instrument_contrast = [
        'name', 'brand_name', 'origin', 'application_range', 'attestation', 7, 8, 9, 10, 11, 12, 13,
        'maintain_time'
    ]

    material_contrast = [
        'name', 'brand_name', 'origin', 'attestation', 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
        'anesthesia_method', 'price', 'treatment_time', 'maintain_time',
        'recover_time', 'treatment_num'
    ]

    def __init__(self, directory_type, item_ids):
        self.directory_type = directory_type
        self.item_ids = item_ids
        self.contrast_method = {
            DIRECTORY_TYPE.ITEM: self.item_data,
            DIRECTORY_TYPE.DRUG: self.drug_data,
            DIRECTORY_TYPE.MACHINE: self.instrument_data,
            DIRECTORY_TYPE.MATERIAL: self.material_data
        }[directory_type]

    def data(self):
        return self.contrast_method()

    def item_data(self):
        queryset = Item.objects.filter(id__in=self.item_ids, is_online=True)
        return self.contrast_data(queryset, self.item_contrast)

    def drug_data(self):
        queryset = self.product_queryset(PRODUCT_TYPE.DRUG)
        return self.contrast_data(queryset, self.drug_contrast)

    def instrument_data(self):
        queryset = self.product_queryset(PRODUCT_TYPE.INSTRUMENT)
        return self.contrast_data(queryset, self.instrument_contrast)

    def material_data(self):
        queryset = self.product_queryset(PRODUCT_TYPE.MATERIALS)
        return self.contrast_data(queryset, self.material_contrast)

    def contrast_data(self, queryset, contrasts):
        head_map = {x.attname: x.verbose_name for x in queryset.model._meta.fields}
        heads = []
        extra_head = {
            'company': u'公司/厂商',
            'attestation': u'所获认证',
            'brand_name': u'品牌'
        }
        for field in contrasts:
            if isinstance(field, int):
                heads.append(PRODUCT_PARAMS.getDesc(str(field)))
            elif field in extra_head:
                heads.append(extra_head[field])
            else:
                heads.append(head_map[field])
        data = []
        meta = queryset.model._meta
        for i in queryset:
            row = []
            for field in contrasts:
                params = {}
                if meta.model_name == 'product':
                    params = {x.params_type: x.params_message for x in i.params.all()}
                if isinstance(field, int):
                    row.append(params.get(str(field), '-'))
                elif field == 'company':
                    row.append(i.brand.company if i.brand else '-')
                elif field == 'brand_name':
                    row.append(i.brand.name if i.brand else '-')
                elif field == 'attestation':
                    row.append(','.join([x.attestation_type for x in i.attestations.all()]))
                else:
                    item = getattr(i, field)
                    choices = meta.get_field_by_name(field)[0].choices
                    if choices:
                        item = choices.getDesc(item)
                    row.append(item)
            data.append(row)
        return {'head': heads, 'data': data}

    def product_queryset(self, product_type):
        return Product.objects.filter(
            is_online=True, id__in=self.item_ids, product_type=product_type
        )


def format_item_info(item):
    """
    格式化输出 百科详情信息
    :param item: 百科 objects
    :return: {}
    """
    data = {}
    if item:
        data = {
            'id': item.id,
            'name': item.name,
            'image_url': item.icon,

            'other_name': item.other_name,
            'description': item.description,
            'effect': item.effect,
            'use_result': item.use_result,

            'fit_people': item.fit_people,
            'avoid_people': item.avoid_people,
            'advantage': item.advantage,
            'disadvantage': item.disadvantage,

            'treatment_method': item.treatment_method,
            'anesthesia_method': item.anesthesia_method,
            'ache_level': item.ache_level,

            'price': item.price,
            'hospitalized': item.hospitalized,
            'treatment_time': item.treatment_time,
            'recover_time': item.recover_time,
            'maintain_time': item.maintain_time,
            'treatment_num': item.treatment_num,
            'treatment_doctor': item.treatment_doctor,

            'pre_know': item.pre_know,
            'is_hot': item.is_hot,
            'is_online': item.is_online,

            'after_know': [{
                'title': x.title,
                'rank': x.rank,
                'recover_tips': x.recover_tips,
                'care_method': x.care_method
            } for x in item.after_know.filter(is_online=True).order_by('rank')],

            'similar_item': [{
                'id': x.id, 'name': x.name, 'description': x.description
            } for x in item.similar_item.filter(is_online=True) if x.id != item.id],

            'similar_drug': similar_product(item, PRODUCT_TYPE.DRUG),
            'similar_machine': similar_product(item, PRODUCT_TYPE.INSTRUMENT),
            'similar_material': similar_product(item, PRODUCT_TYPE.MATERIALS),
        }
    return data
