#!/usr/bin/env python
# coding=utf-8

import json
from django.db import models
from django.contrib.auth.models import User

from gm_upload import ImgUrlField, IMG_TYPE
from gm_crypto.fields import EncryptedCharField
from gm_types.gaia import PHONE400_VENDOR, USERCALL_STATUS

from .doctor import Doctor


class PhoneRecord(models.Model):
    class Meta:
        verbose_name = u'35. 通话记录'
        verbose_name_plural = u'35. 通话记录'
        db_table = 'api_phonerecord'
        app_label = 'api'

    user = models.ForeignKey(User, null=True, blank=True, related_name="phone_record_user", help_text=u"用户")
    udid = models.CharField(max_length=100, null=True, blank=True, help_text=u"用户的设备Id")
    doctor = models.ForeignKey(Doctor, related_name="phone_record_doctor", help_text=u"通话医生")
    phone_time = models.DateTimeField(auto_now_add=True, verbose_name=u"通话时间")
    phone_num = models.CharField(max_length=100)

    def __unicode__(self):
        return unicode(self.user)


class PhoneServiceRecord(models.Model):
    class Meta:
        verbose_name = u'通话录音数据'
        db_table = 'api_phone_service_record'
        app_label = 'api'

    doctor = models.ForeignKey(Doctor, verbose_name=u"城市ID", help_text=u"城市ID", null=True)
    call_phone = EncryptedCharField(max_length=20, verbose_name="主叫号码", null=True, blank=True, default='')
    dest_phone = EncryptedCharField(max_length=20, verbose_name="被叫号码", null=True, blank=True, default='')
    call_time = models.DateTimeField(null=True, blank=True, verbose_name='呼叫时间')
    transfer_phone = models.CharField(max_length=10, verbose_name="分机号码", null=True, blank=True, default='')
    call_status = models.IntegerField(default=0, verbose_name=u'接听状态')
    audio_url = ImgUrlField(img_type=IMG_TYPE.AUDIO, max_length=120, verbose_name='音频地址', blank=True, default='')
    duration = models.IntegerField(default=0, verbose_name=u'通话时长')

    vendor = models.CharField(u'400服务提供商', max_length=50, choices=PHONE400_VENDOR, default='')
    record_id = models.CharField(
        u'服务商提供的记录唯一标识', max_length=100, default='',
        db_index=True, help_text=u'用于通话记录排重',
    )
    origin_data_json = models.TextField(u'原始数据(json)', default='')
    aduit_result = models.IntegerField('通话结果', default=USERCALL_STATUS.NOT_HANDLE, choices=USERCALL_STATUS, db_index=True)

    @property
    def origin_data(self):
        try:
            return json.loads(self.origin_data_json)
        except:
            return self.origin_data_json

    @origin_data.setter
    def origin_data(self, value):
        self.origin_data_json = json.dumps(value)

