# -*- coding: UTF-8 -*-
import re
import tablib
from django.core.management import BaseCommand
from api.models import DoctorAccount
from gm_types.doctor import DOCTOR_ACCOUNT_TYPE
from .utils import get_mail


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 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_201703024_export_doctor_account
        导出医生账户信息
    """

    def handle(self, *args, **options):
        error_message = ''
        doctor_accounts = DoctorAccount.objects.all()
        dt_result = tablib.Dataset()
        dt_result.headers = [
            u'医生ID', u'医生姓名', u'医院ID', u'医院', u'是否在线', u'开户类型', u'省', u'市',
            u'开户银行', u'户名', u'账号'
        ]
        for account in doctor_accounts.iterator():
            try:
                hospital = account.doctor.hospital.name
            except:
                hospital = u''
            try:
                x = (
                    strformat(account.doctor_id),
                    account.doctor.name,
                    account.doctor.hospital_id,
                    hospital,
                    u'是' if account.doctor.is_online else u'否',
                    DOCTOR_ACCOUNT_TYPE.getDesc(account.account_type),
                    account.province.name if account.province_id else '',
                    account.city.name if account.city_id else '',
                    account.bank,
                    account.account_name,
                    u' {}'.format(account.account_number),
                )
                dt_result.append(x)
                print account.doctor_id
            except Exception as e:
                message = u'account_id:{}, doctor_id:{}, message:{}'.format(account.id, account.doctor_id, e.message)
                print message
                error_message += message
        get_mail(u'医生账户信息.csv', u'医生账户信息', u'chenfeifei@gmei.com', dt_result.csv).send()
        get_mail(u'医生账户信息.xlsx', u'医生账户信息', u'chenfeifei@gmei.com', dt_result.xlsx).send()
        get_mail(u'医生账户信息_error.txt', u'医生账户信息_error', u'chenfeifei@gmei.com', error_message).send()
        print 'DONE!'
