#!/usr/bin/env python
# coding=utf-8
from django.db.models import F

from api.models import Province, MerchantRelevance, StoreClassification, ServiceStoreClassificationRelevance, Service
from hippo.models import SlaveMerchant, MasterMerchant
from rpc.decorators import bind
from django.conf import settings


@bind('api/store/city/all')
def store_all_cities(doctor_id):
    """
        获取当前旗舰店分店所在的所有城市
    """
    # 处理直辖市兼容处理
    directly_city_ids = ['beijing', 'tianjin', 'shanghai', 'chongqing', 'aomen', 'xianggang']
    """
    获取所有关联的子店
    """
    merchant = MerchantRelevance.objects.get(doctor_id=doctor_id).merchant
    master_merchant = MasterMerchant.objects.get(mastermerchant_id=merchant.id)
    all_slavemerchants = SlaveMerchant.objects.filter(mastermerchant_id=master_merchant.id)
    """
    获取子店所在城市集合
    key:city_id,val:provice_id
    """
    city_ids = dict()
    for slavemerchant in all_slavemerchants:
        merchant = slavemerchant.slavemerchant
        city = merchant.doctor.hospital.city
        city_ids[city.id] = city.province_id
    province_list = Province.objects.filter(id__in=city_ids.values())
    provinces = []
    for province in province_list:
        # 防止省里包含深圳
        if province.id == 'shenzhen':
            continue
        item = {
            'id': province.id,
            'name': province.name,
            'is_municipality_city': False,
            'cities': [],
        }
        is_municipality_city = province.id in directly_city_ids  # 该省是否是直辖市
        if is_municipality_city:
            item['is_municipality_city'] = True
        for city in province.cities.all():
            if is_municipality_city and city.id != province.id:
                continue  # 直辖市和省id必须相等，否则继续
            #下属城市必须是关联子店的
            if not city_ids.get(city.id, None):
                continue
            # 标识特别行政区、直辖市
            item['cities'].append({
                'id': city.id,
                'name': city.name,
            })
        provinces.append(item)
    return [{
        'id': settings.COUNTRY_CHINA_ID,
        'provinces': provinces,
    }]


@bind('api/store_classification/edit')
def store_classification_edit(name, id, doctor_id):
    if id:
        obj = StoreClassification.objects.get(id=id, doctor_id=doctor_id)
        obj.name = name
        obj.save()
        return {'name': obj.name, 'id': obj.id, 'rank': obj.rank}
    rank = StoreClassification.objects.filter(doctor_id=doctor_id).count() + 1
    obj = StoreClassification.objects.create(doctor_id=doctor_id, name=name, rank=rank)
    data = {'name': obj.name, 'id': obj.id, 'rank': rank}
    return data


@bind('api/store_classification/list')
def store_classification_query(doctor_id):
    objs = StoreClassification.objects.filter(doctor_id=doctor_id).order_by('rank')
    data = []
    for obj in objs:
        data.append({'id': obj.id, 'rank': obj.rank, 'name': obj.name})
    return {'total': objs.count(), 'group_list': data}


@bind('api/store_classification/delete')
def store_classification_delete(id, doctor_id):
    obj = StoreClassification.objects.get(id=id, doctor_id=doctor_id)
    objs = StoreClassification.objects.filter(doctor_id=doctor_id, rank__gt=obj.rank)
    objs.update(rank=F('rank')-1)
    obj.delete()
    return {'id': id}


@bind('api/store_classification/move')
def store_classification_move(id, is_up, doctor_id):
    obj = StoreClassification.objects.get(id=id, doctor_id=doctor_id)
    if is_up:
        relation_obj = StoreClassification.objects.filter(rank=obj.rank-1, doctor_id=doctor_id).first()
        if relation_obj:
            relation_obj.rank += 1
            obj.rank -= 1
    else:
        relation_obj = StoreClassification.objects.filter(rank=obj.rank + 1, doctor_id=doctor_id).first()
        if relation_obj:
            relation_obj.rank -= 1
            obj.rank += 1
    relation_obj.save()
    obj.save()
    return {'id': id}

@bind('api/store_classification_service/list')
def store_classification_service_query(group_id):
    """
    通过关联表获取当前分类下的所有美购
    :param group_id:
    :param doctor_id:
    :return:
    """
    data = []
    service_relevances = ServiceStoreClassificationRelevance.objects.filter(storeclassification_id=group_id).order_by('rank')
    for obj in service_relevances:
        service = Service.objects.get(id=obj.service_id)
        data.append({'id': service.id, 'name': service.name, 'is_online': service.is_online})
    return {'total': service_relevances.count(), 'service_list': data}


@bind('api/store_classification_service/delete')
def store_classification_service_delete(group_id, id):
    """
    通过关联表获取当前分类下制定美购
    :param group_id:
    :param doctor_id:
    :return:
    """
    service_relevance = ServiceStoreClassificationRelevance.objects.get(storeclassification_id=group_id, service_id=id)
    service_relevances = ServiceStoreClassificationRelevance.objects.filter(storeclassification_id=group_id, rank__gt=service_relevance.rank)
    service_relevances.update(rank=F('rank') - 1)
    service_relevance.delete()
    return {'id': id}


@bind('api/store_classification_service/move')
def store_classification_service_move(group_id, id, is_up):
    """
    通过关联表获取当前分类下制定美购
    :param group_id:
    :param doctor_id:
    :return:
    """
    service_relevance = ServiceStoreClassificationRelevance.objects.get(storeclassification_id=group_id, service_id=id)
    rank =service_relevance.rank
    if is_up:
        relation_obj = ServiceStoreClassificationRelevance.objects.filter(storeclassification_id=group_id, rank=rank - 1).first()
        if relation_obj:
            relation_obj.rank += 1
            service_relevance.rank -= 1
            relation_obj.save()
            service_relevance.save()
    else:
        relation_obj = ServiceStoreClassificationRelevance.objects.filter(storeclassification_id=group_id, rank=rank + 1).first()
        if relation_obj:
            relation_obj.rank -= 1
            service_relevance.rank += 1
            relation_obj.save()
            service_relevance.save()
    return {'id': id}


@bind('api/store_classification_service/add')
def store_classification_service_add(group_id, ids, doctor_id):
    """
    通过关联表获取当前分类下制定美购
    :param group_id:
    :param doctor_id:
    :return:
    """
    data = []
    rank_start = ServiceStoreClassificationRelevance.objects.filter(storeclassification_id=group_id).count() + 1
    for id in ids:
        if not ServiceStoreClassificationRelevance.objects.filter(storeclassification_id=group_id, service_id=id):
            obj = ServiceStoreClassificationRelevance.objects.create(storeclassification_id=group_id, service_id=id, rank=rank_start, doctor_id=doctor_id)
            rank_start += 1
            data.append({'id': obj.service.id, 'name': obj.service.name, 'is_online': obj.service.is_online, 'rank': obj.rank})
    return {'result': data}