# coding=utf-8

from django_measurement.models import MeasurementField
from measurement.measures import Volume
from django.db import models

# Create your models here.

class ICD9Diag(models.Model):
    code = models.CharField(max_length=5, primary_key=True)
    desc = models.CharField(max_length=50)

    def __str__(self):
        # return "%s.%s %s" % (self.code[0:3], self.code[3:], self.desc)
        return self.code

class ICD10CMfinal(models.Model):
    ICD9CM_code    = models.CharField(max_length=255, db_column=u"ICD-9-CM代碼", verbose_name=u"ICD-9-CM代碼")
    ICD9CM_English = models.CharField(max_length=255, db_column=u"ICD-9-CM英文名稱", verbose_name=u"ICD-9-CM英文名稱")
    ICD9CM_Chinese = models.CharField(max_length=255, db_column=u"ICD-9-CM中文名稱", verbose_name=u"ICD-9-CM中文名稱")
    ICD10CM         = models.CharField(max_length=8, db_column=u"ICD10CM", verbose_name=u"ICD-10-CM", primary_key=True)
#     ICD10CM         = models.CharField(max_length=255, db_column=u"ICD10CM", verbose_name=u"ICD-10-CM", primary_key=True)
#     ICD10CM         = models.CharField(max_length=255, primary_key=True)
    ICD10CM_English = models.CharField(max_length=255, db_column=u"ICD-10-CM英文名稱", verbose_name=u"ICD-10-CM英文名稱")
    ICD10CM_Chinese = models.CharField(max_length=255, db_column=u"ICD-10-CM中文名稱", verbose_name=u"ICD-10-CM中文名稱")
    Corresponding = models.CharField(max_length=255, db_column=u"對應情形", verbose_name=u"對應情形")
    class Meta:
        managed = False
        db_table = u'ICD10CMfinal2'

    def __str__(self):
#         return "%s|%s| %s\n%s" % (self.ICD10CM, self.ICD9CM_code, self.ICD10CM_English, self.ICD9CM_English)
        # return "%s|%s|%s" % (self.ICD10CM, self.ICD9CM_code, self.ICD10CM_English)
        return "%s %s" % (self.ICD10CM, self.ICD10CM_English)

    def __jsonencode__(self):
        return {'ICD10CM': self.ICD10CM}

class ICD10Count(models.Model):
    # icd10cm = models.ForeignKey(ICD10CMfinal, blank=True, null=True, verbose_name='ICD-10-CM', to_field='ICD10CM', on_delete=models.SET_NULL, primary_key=True)
    icd10cm = models.OneToOneField(ICD10CMfinal, on_delete=models.DO_NOTHING, primary_key=True)
    count = models.IntegerField(null=True)


class Activity(models.Model):
    title = models.CharField(max_length=200)

    def __str__(self):
        return self.title

    class Admin:
        pass

class Patient(models.Model):
    GENDER_CHOICES = (
        (1, 'Male'),
        (2, 'Female'),
    )
#    STATUS_CHOICES = (
#        ( 0, 'Male'),
#        (10, 'Female'),
#    )
    name = models.CharField(max_length=200, verbose_name='姓名')
    medical_records = models.CharField(max_length=200, unique=True)
    gender = models.IntegerField(choices=GENDER_CHOICES)
    birthday = models.DateField()
    address = models.CharField(max_length=200)
    phone = models.CharField(max_length=200)
    id_cards = models.CharField(max_length=200, unique=True)
    memo = models.CharField(max_length=200, blank=True, null=True)
    dead = models.DateField(blank=True, null=True)

    height = models.DecimalField(max_digits=4, decimal_places=1, null=True)
    weight = models.DecimalField(max_digits=6, decimal_places=3, null=True)
    native = models.CharField(max_length=200, blank=True, null=True)
    past_and_family_history = models.TextField(blank=True, null=True)

#    last_followup = models.DateField(blank=True, null=True)
#    next_followup = models.DateField(blank=True, null=True)
    
    timestamp = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name
#        return self.name+' '+str(self.medical_records)

    class Admin:
        pass
    def get_absolute_url(self):
        return "/patient/detail/%i/" % self.id

    # class Meta:
    #     ordering = ['name']


class Oncologist(models.Model):
    name = models.CharField(max_length=200)
    staff_code = models.CharField(max_length=9,null=True)
    def __str__(self):
        return self.name

class Surgeon(models.Model):
    name = models.CharField(max_length=200)
    staff_code = models.CharField(max_length=9,null=True)
    def __str__(self):
        return self.name

class DiseaseStage(models.Model):
    stage = models.CharField(max_length=200)
    def __str__(self):
        return self.stage

    class Admin:
        pass


class PrimaryTumorSite(models.Model):
#    id = models.IntegerField('ID', primary_key=True)
    site = models.CharField(max_length=200)

    def __str__(self):
        return self.site

    class Admin:
        pass

ACCOUNTING = (
    (10, '健保'),
    (20, '自費'),
    (30, '內含'),
)

class Treatment(models.Model):
    KARNOFSKY_SCORING = (
        (100, '100% - normal, no complaints, no signs of disease'),
        ( 90, ' 90% - capable of normal activity, few symptoms or signs of disease'),
        ( 80, ' 80% - normal activity with some difficulty, some symptoms or signs'),
        ( 70, ' 70% - caring for self, not capable of normal activity or work'),
        ( 60, ' 60% - requiring some help, can take care of most personal requirements'),
        ( 50, ' 50% - requires help often, requires frequent medical care'),
        ( 40, ' 40% - disabled, requires special care and help'),
        ( 30, ' 30% - severely disabled, hospital admission indicated but no risk of death'),
        ( 20, ' 20% - very ill, urgently requiring admission, requires supportive measures or treatment'),
        ( 10, ' 10% - moribund, rapidly progressive fatal disease processes'),
        (  0, '  0% - death'),
    )

    IMAGE_GUIDANCE = (
        (100, '6D Skull'),
        (200, 'Xsight-Spine'),
        (210, 'Xsight-Lung'),
        (300, 'Fiducial'),
        (400, 'Synchrony'),
    )

    patient = models.ForeignKey(Patient, on_delete=models.CASCADE)
    bed = models.CharField(max_length=200, blank=True, null=True, verbose_name='病床號')
    icd9 = models.ForeignKey(ICD9Diag, blank=True, null=True, verbose_name='ICD9診斷', on_delete=models.SET_NULL)
    icd10cm = models.ForeignKey(ICD10CMfinal, blank=True, null=True, verbose_name='ICD-10-CM', to_field='ICD10CM', on_delete=models.SET_NULL)
    other_diagnosis = models.CharField(max_length=200, blank=True, null=True, verbose_name='其他診斷')
    tracking_mode = models.IntegerField(choices=IMAGE_GUIDANCE, blank=True, null=True)
    referral = models.CharField(max_length=200, blank=True, null=True, verbose_name='轉介醫師')
    oncologist = models.ForeignKey(Oncologist, blank=True, null=True, on_delete=models.SET_NULL, verbose_name='放射腫瘤')
    surgeon = models.ForeignKey(Surgeon, blank=True, null=True, on_delete=models.SET_NULL, verbose_name='神經外科')
    date_started = models.DateField(blank=True, null=True)
    date_completed = models.DateField(blank=True, null=True)
    accounting = models.IntegerField(choices=ACCOUNTING, blank=True, null=True, verbose_name='記帳別')
    karnofsky_score = models.IntegerField(choices=KARNOFSKY_SCORING, blank=True, null=True)
    disease_stage = models.ForeignKey(DiseaseStage, blank=True, null=True, on_delete=models.SET_NULL)
    primary_tumor_site = models.ForeignKey(PrimaryTumorSite, blank=True, null=True, on_delete=models.SET_NULL)
    input = models.ForeignKey(Activity, related_name='input', blank=True, null=True, verbose_name='已', on_delete=models.SET_NULL)
    output = models.ForeignKey(Activity, related_name='output', blank=True, null=True, verbose_name='待', on_delete=models.SET_NULL)
    complications = models.CharField(max_length=200, blank=True, null=True, verbose_name='併發症')
    chief_complaint = models.TextField(blank=True, null=True) 

    memo            = models.CharField(max_length=200, blank=True, null=True)
    timestamp       = models.DateTimeField(auto_now=True)
    creation        = models.DateTimeField(auto_now_add=True)

    class Admin:
        pass

    def get_absolute_url(self):
        return "/treatment/detail/%i/" % self.id

    def save(self, *args, **kwargs):
        if self.icd10cm:
            self.icd9_id = self.icd10cm.ICD9CM_code.replace('.', '')
           
        super(Treatment, self).save(*args, **kwargs)

# 000B3121    Cyberknife Radiosurgery,Intracranial Lesion
# 000B3122    Cyberknife Radiosurgery,Extracranial Lesion
# 000B3123    Cyberknife Radiosurgery,Multifraction Therapy
class Price(models.Model):
    code = models.CharField(max_length=200, blank=True, null=True)
    identity = models.IntegerField(choices=ACCOUNTING)
    name = models.CharField(max_length=200)
    unit = models.CharField(max_length=200, blank=True, null=True)
    address = models.IntegerField(blank=True, null=True)

    class Admin:
        pass
    
    class Meta:
        ordering = ["code", "identity", "name"]

    def __str__(self):
        return self.code + '-' + self.get_identity_display() + '-' + self.name

class VEVENT(models.Model):
# iCalendar
    DTSTAMP = models.DateTimeField(auto_now=True)
    DTSTART = models.DateTimeField()
    DTEND = models.TimeField(blank=True)
    DURATION = models.TimeField()
    SUMMARY = models.CharField(max_length=200, blank=True, null=True)
    CLASS = models.CharField(max_length=200, blank=True, null=True) 
    CATEGORIES = models.CharField(max_length=200, blank=True, null=True)
    TRANSP = models.CharField(max_length=200, blank=True, null=True)
    RRULE = models.CharField(max_length=200, blank=True, null=True)

    DESCRIPTION = models.CharField(max_length=200, blank=True, null=True) # map to PatientAppointmentSchedule

    MODE_CHOICES = (
        (100, '衛教(日)'),
        (110, 'Fiducial'),
        (200, '固定器'),
        (210, 'CT'),
        (215, 'RT-CT'),
        (220, 'MRI'),
        (230, 'Angio'),
        (300, '預排'),
        (310, '治療'),
    )
    treatment = models.ForeignKey(Treatment, on_delete=models.CASCADE)
    mode = models.IntegerField(choices=MODE_CHOICES)
    mode_remark = models.CharField(max_length=200, blank=True, null=True)
    price = models.ForeignKey(Price, blank=True, null=True, on_delete=models.SET_NULL)
    
    break_frequency = models.IntegerField(blank=True)
    system_err = models.IntegerField(blank=True)
    shift = models.IntegerField(blank=True)
    cone = models.IntegerField(blank=True)
    path = models.IntegerField(blank=True)

    def get_absolute_url(self):
        return "/treatment/detail/%i/" % self.treatment.id

class TargetLocation(models.Model):
    location = models.CharField(max_length=200)

    def __str__(self):
        return self.location

    class Admin:
        pass


class Pathology(models.Model):
    pathology = models.CharField(max_length=200, unique=True)
    stage = models.ForeignKey(DiseaseStage, on_delete=models.CASCADE)

    def __str__(self):
        return self.pathology

    class Admin:
        pass


class SubLocation(models.Model):
    target_location = models.ForeignKey(TargetLocation, on_delete=models.CASCADE)
    group = models.IntegerField()
    sub_location = models.CharField(max_length=200)
    pathology = models.ManyToManyField(Pathology)

    def __str__(self):
#        return TargetLocation.objects.get(id=self.target_location)+' - '+self.sub_location
        return self.sub_location

    class Admin:
        pass


class Lesion(models.Model):
    treatment = models.ForeignKey(Treatment, on_delete=models.CASCADE)
    sub_location = models.ForeignKey(SubLocation, on_delete=models.CASCADE)
    pathology = models.ForeignKey(Pathology, on_delete=models.CASCADE)

    CT_CHOICES = (
        ('GE'  , 'GE'     ),
        ('PHIA', 'Philips'),
        ('SIE' , 'Siemens'),
    )

    calibration_table  = models.CharField   (max_length=9, choices=CT_CHOICES, null=True, verbose_name='CT Calibration table')
    density_correction = models.BooleanField(                                  null=True, verbose_name='影像密度修正'          )

    dimensions = models.CharField(max_length=200)
    volume         = models.DecimalField(max_digits=9, decimal_places=2                               , verbose_name='Target Volume(mm3)', null=True)
    volume_measure = MeasurementField   (measurement=Volume,unit_choices=(('cubic_centimeter','cm3'),), verbose_name='Target Volume'     , null=True)

# cubic_millimeter
# cubic_centimeter

    plan_name = models.CharField(max_length=200, blank=True, null=True)

    COLLIMATOR_CHOICES = (
        (10, 'fixed'),
        (20, 'Iris'),
        (30, 'MLC'),
    )

    collimator_type = models.IntegerField(choices=COLLIMATOR_CHOICES, default=10, verbose_name='Collimator Type'     )
    collimator = models.CharField(max_length=200)
    path_no = models.IntegerField()
    beam_no = models.IntegerField()

    # mu_max = models.DecimalField(max_digits=9, decimal_places=2, null=True)
    # mu_min = models.DecimalField(max_digits=9, decimal_places=2, null=True)
    mu_max = models.DecimalField(max_digits=9, decimal_places=2, blank=True, null=True)
    mu_min = models.DecimalField(max_digits=9, decimal_places=2, blank=True, null=True)

    dose = models.IntegerField()
    fractions = models.IntegerField()
    iso_dose_curve = models.DecimalField(max_digits=9, decimal_places=1)

    dmin  = models.DecimalField(max_digits=9, decimal_places=2)
    dmax  = models.DecimalField(max_digits=9, decimal_places=2)
    dmean = models.DecimalField(max_digits=9, decimal_places=2, verbose_name='Mean dose(cGy)', null=True)

    coverage = models.DecimalField(max_digits=9, decimal_places=2)
    ci = models.DecimalField(max_digits=9, decimal_places=2)
    nci = models.DecimalField(max_digits=9, decimal_places=2)

    start_date = models.DateField(blank=True, null=True)
    end_date = models.DateField(blank=True, null=True)

    memo = models.CharField(max_length=200, blank=True, null=True)

    def get_absolute_url(self):
        return "/treatment/detail/%i/" % self.treatment.id

    def sub_location_target_location(self):
        return self.sub_location.target_location

    def treatment_id(self):
        return treatment.id

    def save(self, *args, **kwargs):
        if self.volume_measure is not None:
            self.volume = self.volume_measure.cubic_millimeter
        super().save(*args, **kwargs)        


class PriorTreatment(models.Model):
    TREATMENT_CHOICES = (
        (1, 'Surgery'),
        (2, 'Biopsy'),
        (3, 'RT'),
        (4, 'Radiosurgery'),
        (5, 'Chemotherapy'),
    )
    PERIOD_CHOICES = (
        (1, 'Before'),
        (2, 'Concurrent'),
        (3, 'None'),
    )
    patient = models.ForeignKey(Patient, on_delete=models.CASCADE)
    date = models.DateField()
    treatment = models.IntegerField(choices=TREATMENT_CHOICES)
    period = models.IntegerField(choices=PERIOD_CHOICES, blank=True, null=True)
    dose = models.IntegerField(blank=True, null=True)
    memo = models.CharField(max_length=200, blank=True, null=True)

    def get_absolute_url(self):
        return "/patient/detail/%i/" % self.patient.id


class PathExam(models.Model):
    patient           = models.ForeignKey(Patient, on_delete=models.CASCADE)
    path_code         = models.CharField(max_length=200, unique=True, verbose_name='病理號')
    specimen_code     = models.CharField(max_length=200, verbose_name='檢體')
    specimen_get_date = models.DateField(verbose_name='收件日')
    report_date       = models.DateField(verbose_name='報告日')
    division          = models.CharField(max_length=200, verbose_name='科別')
    bed               = models.CharField(max_length=200, blank=True, null=True, verbose_name='病床')
    report            = models.TextField(blank=True, null=True, verbose_name='檢查報告')


class Followup(models.Model):
    patient = models.ForeignKey(Patient, on_delete=models.CASCADE)
#    date = models.DateField(auto_now_add=True)
    date = models.DateField()
    memo = models.CharField(max_length=200, blank=True, null=True)

    def get_absolute_url(self):
        return "/patient/detail/%i/" % self.patient.id

class PACSImage(models.Model):
    patient             = models.ForeignKey(Patient, on_delete=models.CASCADE)
    
    PatChartNo          = models.CharField(max_length=200, verbose_name='病歷號') 
    RequestSheetNo      = models.CharField(max_length=200, verbose_name='單號') 
    ExamDate            = models.DateField(                verbose_name='檢查日') 
    LinkOrderName       = models.CharField(max_length=200, verbose_name='檢查名稱') 
    Modality            = models.CharField(max_length=200, verbose_name='儀器') 
    VerifiedStateString = models.CharField(max_length=200, verbose_name='狀態') 
    Exam                = models.TextField(null=True,      verbose_name='報告內容')
    Impression          = models.TextField(null=True)
    Report              = models.TextField(null=True,      verbose_name='報告')

    SAVED_CHOICES = (
        (0 , '待處理'),
        (10, '有輸入'),
        (15, '已確認'),
        (20, '不適用'),
    )
#    Saved               = models.BooleanField() 
    Saved               = models.IntegerField(choices=SAVED_CHOICES, verbose_name='保存')

    
class ElectronicMedicalReport(models.Model):    
    report_key = models.CharField(max_length=200, primary_key=True)
    patient    = models.ForeignKey(Patient, on_delete=models.CASCADE)
    
    report_class = models.CharField(max_length=200)
    check_date   = models.DateField(null=True)
    report_date  = models.DateField(null=True)
    report_code  = models.CharField(max_length=200)
    report       = models.TextField(null=True)
    saved        = models.DateField(auto_now=True)
    

class XrayTextReport(models.Model):    
    # report_key = models.ForeignKey(ElectronicMedicalReport, primary_key=True)
    report_key = models.OneToOneField(ElectronicMedicalReport, primary_key=True, on_delete=models.CASCADE)
    
    old_access_no  = models.CharField(max_length=200, null=True)
    ioe            = models.CharField(max_length=200, null=True)
    refer_dept     = models.CharField(max_length=200, null=True)
    status         = models.CharField(max_length=200, null=True)
    formal_version = models.CharField(max_length=200, null=True)
    exam_date      = models.DateField(null=True)
    order_desc     = models.CharField(max_length=200, null=True)

    clean_html     = models.TextField(null=True)
    
    response       = models.CharField(max_length=200, null=True)


class TreatmentResponse(models.Model):    
    # treatment = models.ForeignKey(Treatment, primary_key=True)
    treatment = models.OneToOneField(Treatment, primary_key=True, on_delete=models.CASCADE)
    
    time      = models.DateField(null=True)
    event     = models.BooleanField(null=True)

    time1y    = models.DateField(null=True)
    event1y   = models.BooleanField(null=True)
    
class LesionFollow(models.Model):
    Lesion = models.ForeignKey(Lesion, on_delete=models.CASCADE)
    Date   = models.DateField(null=False, verbose_name='追蹤日期')
    Volume = models.FloatField(null=True, verbose_name='體積(mm3)')
    A = models.FloatField(null=True, verbose_name='長(mm)')
    B = models.FloatField(null=True, verbose_name='寬(mm)')
    C = models.FloatField(null=True, verbose_name='高(mm)')
    Memo   = models.CharField(max_length=200, blank=True, null=True)
    

class MedicalRecord(models.Model):
    patient           = models.ForeignKey(Patient, on_delete=models.CASCADE)
    
    Record            = models.CharField(max_length=200, null=True) # 住急門 
    
    HospName          = models.CharField(max_length=200, null=True) 
    DeptName          = models.CharField(max_length=200, null=True, verbose_name='科') 
    InDate            = models.DateField(               null=False, verbose_name='入') 
    OutDate           = models.DateField(                null=True, verbose_name='出') 
    WardName          = models.CharField(max_length=200, null=True, verbose_name='房') 
    RoomName          = models.CharField(max_length=200, null=True, verbose_name='室') 
    BedName           = models.CharField(max_length=200, null=True, verbose_name='床') 
    MainDrName        = models.CharField(max_length=200, null=True, verbose_name='主治') 
    MainDiagnosisName = models.CharField(max_length=200, null=True, verbose_name='診斷') 
    StatusName        = models.CharField(max_length=200, null=True, verbose_name='狀態')
     
    SpecialCureName   = models.CharField(max_length=200, null=True, verbose_name='行為')


#New records    
class PatientMedicalRecord(models.Model):
    key_code            = models.CharField(max_length=200, primary_key=True) # 住急門 
    patient             = models.ForeignKey(Patient, on_delete=models.CASCADE)

    key_name            = models.CharField(max_length=200) 
    
    hosp_name           = models.CharField(max_length=200, null=True) 
    dept_name           = models.CharField(max_length=200, null=True, verbose_name='科') 
    in_date             = models.DateField(                null=True, verbose_name='入') 
    out_date            = models.DateField(                null=True, verbose_name='出') 
    ward_name           = models.CharField(max_length=200, null=True, verbose_name='房') 
    room_name           = models.CharField(max_length=200, null=True, verbose_name='室') 
    bed_name            = models.CharField(max_length=200, null=True, verbose_name='床')
     
    come_clinic_date    = models.DateField(                null=True, verbose_name='掛號日') 
    discharge_date      = models.DateField(                null=True, verbose_name='離部日')

    special_cure_name   = models.CharField(max_length=200, null=True, verbose_name='行為')
     
    main_dr_name        = models.CharField(max_length=200, null=True, verbose_name='主治')
    main_diagnosis_name = models.CharField(max_length=200, null=True, verbose_name='診斷')
    status_name         = models.CharField(max_length=200, null=True, verbose_name='狀態')
    
    temp_bed_id         = models.CharField(max_length=200, null=True, verbose_name='床')
     
    account_status_name = models.CharField(max_length=200, null=True, verbose_name='狀態')

    func                = models.CharField(max_length=200, null=True)
    doc                 = models.TextField(                null=True, verbose_name='摘')
    saved               = models.DateField(auto_now=True)

class OPNote(models.Model):
    key_code            = models.CharField(max_length=200, primary_key=True) 
    patient             = models.ForeignKey(Patient, on_delete=models.CASCADE)

    key_name            = models.CharField(max_length=200) 
    
    doc                 = models.TextField(                null=True, verbose_name='摘')
    saved               = models.DateField(auto_now=True)

# {'ChartNo': '6791902', 'PatientName': '張秀玲', 'ApplyTypeDesc': '送核', 'StatusDesc': '新建案件', 'NhiDeptName': '放射腫瘤科', 'PackageTime': None, 'OrderCode': '37029B', 'OrderName': '加馬機立體定位放射手術', 'ResultDesc': '1', 'Quantity': None, 'ExamineQuantity': '0', 'ExamineDate': None}
# {'ChartNo': '3302509', 'PatientName': '賴慧如', 'Status': '影醫部處理中', 'ErrorMsg': None, 'SuccessMsg': None, 'ApplyType': '送核', 'ApplyDate': '2021/02/25', 'AnticancerMedicine': '否', 'ApplyPart': '無', 'EmrDateStr': None, 'NhiDept': '神經外科', 'ApplyDoctor': '蕭輔仁', 'Phone': '63424', 'Diagnosis': 'D32.9', 'Reason': 'A 46Y/O patient female, PHX: olfactory grove meningioma sp OP in 2018，因目前發現有recurrence，

class NHIOrder(models.Model):
    id             = models.CharField(max_length=20, primary_key=True)

    ChartNo        = models.CharField   (verbose_name='病歷號'  ,max_length=10)
    PatientName    = models.CharField   (verbose_name='病患姓名',max_length=30)
    ApplyTypeDesc  = models.CharField   (verbose_name='申請類別',max_length=10)
    StatusDesc     = models.CharField   (verbose_name='案件狀態',max_length=10)
    NhiDeptName    = models.CharField   (verbose_name='科別'    ,max_length=10)
    PackageTime    = models.DateField   (verbose_name='送案日期')
    OrderCode      = models.CharField   (verbose_name='申請項目',max_length=10)
    OrderName      = models.CharField   (verbose_name='項目名稱',max_length=20)
    ResultDesc     = models.IntegerField(verbose_name='申請數量',default=1)
    Quantity       = models.CharField   (verbose_name='核定結果',max_length=10, null=True)
    ExamineQuantity= models.IntegerField(verbose_name='核定數量',               null=True)
    ExamineDate    = models.DateField   (verbose_name='核定日期',               null=True)

    timestamp = models.DateTimeField(auto_now_add=True)
    updated   = models.DateTimeField(auto_now=True)

    # optional

    Status             = models.CharField   (verbose_name='目前狀態'    ,max_length=10, null=True)
    ErrorMsg           = models.CharField   (                           max_length=10, null=True)
    SuccessMsg         = models.CharField   (                           max_length=10, null=True)

    ApplyType          = models.CharField   (verbose_name='申請類別'    ,max_length=10, null=True)
    ApplyDate          = models.DateField   (verbose_name='申請日期'    ,               null=True)
    AnticancerMedicine = models.CharField   (verbose_name='抗癌藥物'    ,max_length=10, null=True)
    ApplyPart          = models.CharField   (verbose_name='申請部位'    ,max_length=10, null=True)
    EmrDateStr         = models.CharField   (verbose_name='緊急通報日'  ,max_length=10, null=True)
    NhiDept            = models.CharField   (verbose_name='申請科別'    ,max_length=10, null=True)
    ApplyDoctor        = models.CharField   (verbose_name='申請醫師'    ,max_length=10, null=True)
    Phone              = models.CharField   (verbose_name='聯絡分機'    ,max_length=10, null=True)
    Diagnosis          = models.CharField   (verbose_name='疾病分類號'  ,max_length=10, null=True)
    Reason             = models.TextField   (verbose_name='申請原因'                 , null=True)
    # OrderCode          = models.CharField   (verbose_name='醫令碼'     ,max_length=10, null=True)
    # OrderName          = models.CharField   (verbose_name='醫令名稱'   ,max_length=10, null=True)
    ApplyQty           = models.IntegerField(verbose_name='申請量'                   , null=True)
    # ResultDesc         = models.CharField   (verbose_name='核定結果'   ,max_length=10, null=True)
    # ExamineQuantity    = models.CharField   (verbose_name='核定量'     ,max_length=10, null=True)
    ExamineDateStr     = models.CharField   (verbose_name='核定日期'    ,max_length=10, null=True)
    ExamineReason1     = models.CharField   (verbose_name='核定原因1'   ,max_length=10, null=True)
    ExamineReason2     = models.CharField   (verbose_name='核定原因2'   ,max_length=10, null=True)
    ExamineReasonDesc  = models.TextField   (verbose_name='核定原因說明',              null=True)

    # extra

    other_diagnosis = models.CharField(max_length=200, blank=True, null=True, verbose_name='Dx')
    num_sessions = models.CharField   (verbose_name='預計分次', max_length=10, null=True)
    MainDrName   = models.TextField   (verbose_name='主治'    ,                null=True)
    Priority     = models.IntegerField(verbose_name='優先'    ,                null=True)
    Memo         = models.TextField   (verbose_name='備註'    ,                null=True)



    # def save(self, *args, **kwargs):
    #     if self.id is None:
    #         self.id = self.ChartNo+'_'+self.PackageTime[:7]

    #     super(NHIOrder, self).save(*args, **kwargs)

'''
sed 's/ENGINE=MyISAM/ENGINE=InnoDB/; s/DEFAULT CHARSET=utf8mb4//; s/DEFAULT CHARSET=utf8//; s/COLLATE=utf8_unicode_ci//' /data/tmp/ck_dev.sql > /data/tmp/ck_dev2.sql
'''
