# -*- 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