# coding: utf-8
from gm_types.error import ERROR

from api.models import BDTransfer, Q, GaiaRPCFaultException, transaction, City, OPERATION_ACTION, \
    Tag, BDTransferWillingProject
from api.tool.user_tool import get_user_from_context
from rpc.decorators import bind, bind_context
from rpc.tool.dict_mixin import to_dict
from rpc.tool.error_code import CODES, gen

uri_pre = 'api/call_center/bdtransfer/'


@bind(uri_pre + 'get')
def get_bdtransfer_info(bdtransfer_id):
    """获取商务转诊完整信息用户渲染

    :param bdtransfer_id: 商务转诊ID
    :rtype: Dict[str, List[Dict]]
    """
    bdtransfer = BDTransfer.objects.prefetch_related(
        'willing_projects', 'willing_cities__tag'
    ).filter(id=bdtransfer_id).first()
    if not bdtransfer:
        gen(CODES.BDTRANSFER_NOT_EXIST)
    res = to_dict(bdtransfer, fields=['id', 'user', 'source', 'wechat', 'creator',  'person_id',
                                      'user_phone', 'create_time', 'note'])
    res['willing_projects'] = [to_dict(_.tag, fields=['id', 'name']) for _ in bdtransfer.willing_projects.all()]
    res['willing_cities'] = [to_dict(_, fields=['id', 'name']) for _ in bdtransfer.willing_cities.all()]
    return res


@bind_context(uri_pre + 'create')
def edit_bdtransfer_info(ctx, bdtransfer_info):
    """更新和创建商务转诊信息

    :param bdtransfer_id: 商务转诊ID, 如果存在则为更新，否则为创建
    :return:
    """
    # TODO 是否创建过后分配的人才能修改改信息
    operate_user = get_user_from_context(ctx)

    # 微信号和手机号至少填一个才允许保存
    if not any([bdtransfer_info['wechat'], bdtransfer_info['user_phone']]):
        raise GaiaRPCFaultException(
            error=ERROR.UNKNOWN_ERROR, message=u'微信号和手机号至少填一个才允许保存', data=None
        )

    check_contact_bd_query = Q()
    if bdtransfer_info['wechat'] != '':
        check_contact_bd_query |= Q(wechat=bdtransfer_info['wechat'])
    if bdtransfer_info['user_phone'] != '':
        check_contact_bd_query |= Q(user_phone=bdtransfer_info['user_phone'])
    check_contact_bd_obj = BDTransfer.objects.filter(check_contact_bd_query).first()
    if check_contact_bd_obj:
        if check_contact_bd_obj.wechat != '' and check_contact_bd_obj.wechat == bdtransfer_info['wechat']:
            bdtransfer_exist_field = u'微信号'
        else:
            bdtransfer_exist_field = u'手机号'
        raise GaiaRPCFaultException(
            error=ERROR.UNKNOWN_ERROR, message=u'已存在相同 {} 的转诊对象'.format(bdtransfer_exist_field), data=None
        )
    with transaction.atomic():
        """
            创建或者更新商务转诊信息
            如果转诊信息为新增，则创建操作记录
            创建或者更新意向城市
            创建或者更新线索标签
        """
        create_bdtransfer_data = {
            "user": bdtransfer_info['user'],
            "user_phone": bdtransfer_info['user_phone'],
            "qq": bdtransfer_info['qq'],
            "wechat": bdtransfer_info['wechat'],
            "weibo": bdtransfer_info['weibo'],
            "source": bdtransfer_info["source"],
            'creator': operate_user.id,
            'note': bdtransfer_info.get('note', ''),
            'person_id': bdtransfer_info.get('person_id', '')
        }
        bdtransfer_obj = BDTransfer.objects.create(**create_bdtransfer_data)
        bdtransfer_obj.operation_records.create(
            operate_user=operate_user, action=OPERATION_ACTION.CREATE, content=u"转诊信息创建"
        )

        willing_cities_obj = list(City.objects.filter(id__in=bdtransfer_info['willing_cities']))
        bdtransfer_obj.willing_cities.add(*willing_cities_obj)

        willing_project_obj = list(Tag.objects.filter(id__in=bdtransfer_info['will_projects']))
        create_willing_project = list()
        for tag in willing_project_obj:
            create_willing_project.append(BDTransferWillingProject(
                tag=tag, bdtransfer=bdtransfer_obj
            ))
        BDTransferWillingProject.objects.bulk_create(create_willing_project)

        return bdtransfer_obj.id
