# -*- coding: UTF-8 -*-
import datetime

from django.db import transaction
from gm_types.gaia import MERCHANT_FREEZE_ACTION

from hippo.models import Merchant, MerchantFreezeRecord
from hippo.models import MerchantRelatedInfo
from rpc.decorators import bind, bind_context
from hippo.tool.merchant_tool import doctor_merchant_map
from api.models import Q
from api.models import Merchant, MerchantRelevance, Doctor
from themis.models import Team


@bind('hippo/merchant/fetch_doctor_merchant')
def fetch_doctor_merchant(ctx, doctor_ids):
    """根据医生id获取对应商户的医生id

    :param doctor_ids: 医生id列表
    :return: {doctor_id: 医生对应商户的医生id}
    """
    return doctor_merchant_map(doctor_ids)


@bind('hippo/merchant/get_doctor_id')
def get_doctor_id_by_merchant_id(id=None, name=None):
    """
    根据商户ID，获取医生ID
    :param ctx:
    :param id: 商户ID
    :return:
    """
    result = list()
    q_list = Q()
    if id is not None:
        q_list.add(Q(merchant__id=id), Q.AND)
    if name is not None:
        q_list.add(Q(merchant__name=name), Q.AND)

    if len(q_list) > 0:
        data = MerchantRelevance.objects\
            .values('merchant__id', 'merchant__name', 'doctor__id', 'doctor__name')\
            .filter(q_list)
        if data:
            result = list({'id': item.get('merchant__id'),
                           'name': item.get('merchant__name'),
                           'doctor_id': item.get('doctor__id'),
                           'doctor_name': item.get('doctor__name')
                           } for item in data)
    return result


@bind_context('hippo/merchant/get_related_info')
def get_related_info(ctx, merchant_id):
    """
    获取商户的联系方式
    :param ctx:
    :param merchant_id:
    :return:
    """
    merchant = Merchant.objects.get(id=merchant_id)
    business  = merchant.doctor.business_partener.last_name
    try:
        team_name = Team.objects.get(id=merchant.doctor.business_group).name
    except:
        team_name = ''
    infos = MerchantRelatedInfo.objects.filter(merchant=merchant)
    related_infos = [{
        "name":info.name,
        "role":info.role,
        "phone":info.phone
                     } for info in infos]
    return {
        'business':business,
        'team_name':team_name,
        'related_infos':related_infos
    }


@bind_context('hippo/merchant/set_related_info')
def set_related_info(ctx, merchant_id, infos):
    """
    编辑商户的联系信息
    :param ctx:
    :param merchant_id:
    :param infos:
    :return:
    """
    with transaction.atomic():
        MerchantRelatedInfo.objects.filter(merchant_id=merchant_id).delete()
        for info in infos:
            MerchantRelatedInfo.objects.create(
                merchant_id=merchant_id,
                name=info["name"],
                role=info["role"],
                phone=info["phone"],
            )


@bind_context('hippo/merchant/set_merchant')
def set_merchant(ctx, merchant_id, data):
    """
    保存商户关联商务信息
    :param ctx:
    :param merchat_id:
    :param data:
    :return:
    """
    if not merchant_id:
        return

    with transaction.atomic():
        Doctor.objects.filter(id__in=list(
            MerchantRelevance.objects.filter(merchant_id=merchant_id).values_list('doctor_id', flat=True)
        )).update(**data)
        Doctor.objects.filter(d_merchant__id=merchant_id).update(**data)

@bind('hippo/merchantfreezerecord/create')
def create_merchant_freeze_record(merchant_id, status, reason):
    status = int(status)
    merchant = Merchant.objects.get(id=merchant_id)
    merchant.is_freeze = True if status else False
    merchant.save()
    MerchantFreezeRecord.objects.create(merchant=merchant, action=status, reason=reason)


@bind('hippo/merchantfreezerecord/query')
def merchant_freeze_query(merchant_id):
    status = Merchant.objects.get(id=merchant_id).is_freeze
    records = MerchantFreezeRecord.objects.filter(merchant_id=merchant_id).order_by('-created_time')
    data = {}
    data['status'] = '1' if status else '0'
    data['reason'] = records.first().reason if records else ''
    result = []
    for record in records:
        action = MERCHANT_FREEZE_ACTION.getDesc(record.action)
        if record.reason:
            reason = action + ':' + record.reason
        else:
            reason = action
        result.append({'merchant_name':record.merchant.name, 'reason':reason, 'created_time':datetime.datetime.strftime(record.created_time,'%Y-%m-%d %H:%M:%S')})
    data['result']=result
    return data


@bind('hippo/doctor_merchant/get_merchant_level')
def get_doctor_id_merchant_level(doctor_id=None, merchant_id=None):
    merchant_level = 1
    try:
        if doctor_id is not None:
            merchant_level = Doctor.objects.get(id=doctor_id).merchant.merchant_level
        elif merchant_id is not None:
            merchant_level = Merchant.objects.get(id=merchant_id).merchant_level
        else:
            return merchant_level
    except Exception as e:
        merchant_level = 1
    return merchant_level


@bind('hippo/get_merchant_info')
def get_doctor_id_merchant_level(merchant_id):
    if not merchant_id:
        return {}
    merchant = Merchant.objects.filter(id=merchant_id).first()
    if not merchant:
        return {}
    return {
        'id': merchant.id,
        'name': merchant.name,
        'doctor_id': merchant.doctor.id,
        'merchant_level': merchant.merchant_level,
        'merchant_score': merchant.merchant_score
    }
    
@bind('hippo/merchant/get_merchant_by_ids')
def get_merchant_info_by_merchant_ids(ids,doctor_ids=None):
    """
    根据商户ID，获取医生ID
    :param ctx:
    :param id: 商户ID
    :return:
    """
    result = dict()
    q_list = Q()
    if ids is not None:
        q_list.add(Q(id__in=ids), Q.AND)
    elif doctor_ids:
        q_list.add(Q(doctor__id__in=doctor_ids), Q.AND)

    if len(q_list) > 0:
        data = Merchant.objects\
            .values('id', 'name', 'doctor__id', 'doctor__name','doctor__hospital__city__name','doctor__hospital__name',
            'doctor__hospital__id','merchantcontract_merchant__cash_back_rate_str')\
            .filter(q_list)
        if data:
            for item in data:
                if str(item.get('id')) in result:
                    temp=result[str(item.get('id'))].get("cash_back_rate_str")
                    result[str(item.get('id'))]["cash_back_rate_str"]=temp+","+item.get("merchantcontract_merchant__cash_back_rate_str")
                else:
                    cash_back_rate_str=item.get("merchantcontract_merchant__cash_back_rate_str") 
                    result[str(item.get('id'))]={
                        'id': item.get('id'),
                        'name': item.get('name'),
                        'doctor_id': item.get('doctor__id'),
                        'doctor_name': item.get('doctor__name'),
                        'city_name': item.get("doctor__hospital__city__name"),
                        'hospital_name': item.get("doctor__hospital__name"),
                        'hospital_id': item.get("doctor__hospital__id"),
                        'cash_back_rate_str': cash_back_rate_str if cash_back_rate_str else "10%",
                    } 
    return result