# coding=utf-8

import re
import unicodedata
import tablib
from django.conf import settings
from django.core.management import BaseCommand
from api.models import Hospital

DFAULT_DBS = [getattr(settings, 'HERA_EXPORT_DB', ''), 'default']


def get_db_key(dbs):
    for db in dbs:
        if db in settings.DATABASES:
            return db
    return None

using_dbs = DFAULT_DBS
using = get_db_key(using_dbs)

def unvisible_pattern():
    # \x00-\x1f\x7f 不可见的ascii码
    # \ue000-\uf8ff\u000f0000-\u000ffffd\u00100000-\u0010fffd Private Use Area
    return re.compile(u'[\x00-\x1f\x7f\uffff]')


def pua_process(s):
    s0 = ''
    for i in range(len(s)):
        if unicodedata.category(s[i]) == 'Co':
            continue
        s0 += s[i]
    return s0


def strformat(s):
    s = re.sub(unvisible_pattern(), '', s)
    # s = pua_process(s)
    if s.startswith('='):
        s = '\'' + s
    return s


class Command(BaseCommand):
    """
    python manage.py dump_20170106_export_hospital_data
    导出医院信息
    """

    def handle(self, *args, **options):
        hospitals = Hospital.objects.using(using).all()
        dt_result = tablib.Dataset()
        dt_result.headers = [
            u'医院ID', u'医院名称', u'所在城市', u'营业执照', u'医疗机构许可证'
        ]

        for hospital in hospitals:
            try:
                x = (
                    strformat(hospital.id),
                    strformat(hospital.name),
                    getattr(hospital.city, 'name', u''),
                    u'有' if hospital.business_licence else u'无',
                    u'有' if hospital.practice_licence else u'无'
                )
                dt_result.append(x)
                print hospital.id
            except Exception as e:
                print e.message
                continue
        open(u'hospital_info.csv', 'wb').write(dt_result.csv)
        open(u'hospital_info.xlsx', 'wb').write(dt_result.xlsx)
        print 'DONE!!!'
