# coding=utf-8

import re
import unicodedata
import tablib
from django.conf import settings
from django.core.management import BaseCommand
from gm_types.gaia import ORDER_STATUS
from gm_types.trade import STATEMENT_STATUS
from api.models import Doctor, Order, Message, Problem, TopicReply, Diary

DEFAULT_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 = DEFAULT_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


def get_doctor_order(doctor, status):
    orders = Order.objects.using(using).filter(service__doctor=doctor, status=status)
    sum_gengmei_price = sum(orders.values_list('servicesnapshot__gengmei_price', flat=True))
    sum_pre_payment_price = sum(orders.values_list('servicesnapshot__pre_payment_price', flat=True))
    return orders.count(), sum_gengmei_price, sum_pre_payment_price


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

    def handle(self, *args, **options):

        doctors = Doctor.objects.using(using).filter(is_online=True)
        dt_result = tablib.Dataset()
        dt_result.headers = [
            u'医生ID', u'医生姓名', u'医院', u'职称', u'每日回复限制', u'自营', u'大牌', u'资格证', u'医生执业证',
            u'未付款订单量', u'已付款订单量', u'已使用订单量', u'已退款订单量', u'已取消订单量', u'退款处理中订单量',
            u'未付款交易额', u'已付款交易额', u'已使用交易额', u'已退款交易额', u'已取消交易额', u'退款处理中交易额',
            u'未付款预付款',u'已付款预付款', u'已使用预付款', u'已退款预付款', u'已取消预付款', u'退款处理中预付款',
            u'已付款抽成', u'已使用抽成',u'结算金额', u'电话接通量(/人次)', u'电话未接通量(/人次)', u'接收私信量(/人次)',
            u'回复私信量(/人次)', u'医生账号发帖数', u'医生账号回复数', u'医生美购关联的帖子数', u'医生美购关联帖子的回复数',
            u'医生关联的日记本数', u'医生关联日记本的回复数'
        ]
        for doctor in doctors:
            try:
                not_paid_num, not_paid_gengmei_price, not_paid_pre_payment = get_doctor_order(doctor, ORDER_STATUS.NOT_PAID)
                paid_num, paid_gengmei_price, paid_pre_payment = get_doctor_order(doctor, ORDER_STATUS.PAID)
                use_num, use_gengmei_price, use_pre_payment = get_doctor_order(doctor, ORDER_STATUS.USED)
                refund_num, refund_gengmei_price, refund_pre_payment = get_doctor_order(doctor, ORDER_STATUS.REFUNDED)
                cancel_num, cancel_gengmei_price, cancel_pre_payment = get_doctor_order(doctor, ORDER_STATUS.CANCEL)
                wait_refund_num, wait_refund_gengmei_price, wait_refund_pre_payment = get_doctor_order(doctor, ORDER_STATUS.WAIT_REFUNDED)
                send_message = Message.objects.using(using).filter(user_id=doctor.user_id).count()
                message = Message.objects.using(using).filter(conversation__user=doctor.user).count()
                x = (
                    strformat(doctor.id),
                    strformat(doctor.name),
                    strformat(doctor.hospital.name) if doctor.hospital_id else u'',
                    strformat(doctor.title),
                    doctor.reply_limit,
                    u'是' if doctor.self_run else u'否',
                    u'是' if doctor.big else u'否',
                    u'有' if doctor.business_licence else u'无',
                    u'有' if doctor.practice_licence else u'无',
                    not_paid_num, paid_num, use_num, refund_num, cancel_num, wait_refund_num,
                    not_paid_gengmei_price, paid_gengmei_price, use_gengmei_price, refund_gengmei_price, cancel_gengmei_price, wait_refund_gengmei_price,
                    not_paid_pre_payment, paid_pre_payment, use_pre_payment, refund_pre_payment, cancel_pre_payment, wait_refund_pre_payment,
                    sum(Order.objects.using(using).filter(service__doctor=doctor, status=ORDER_STATUS.PAID).values_list('discount', flat=True)),
                    sum(Order.objects.using(using).filter(service__doctor=doctor, status=ORDER_STATUS.USED).values_list('discount', flat=True)),
                    sum(doctor.statement_set.using(using).filter(status=STATEMENT_STATUS.SETTLED).values_list('settle_amount', flat=True)),
                    doctor.phoneservicerecord_set.using(using).filter(call_status=2).count(),
                    doctor.phoneservicerecord_set.using(using).exclude(call_status=2).count(),
                    send_message,
                    message - send_message,
                    Problem.objects.using(using).filter(user=doctor.user).count(),
                    TopicReply.objects.using(using).filter(user=doctor.user).count(),
                    Problem.objects.using(using).filter(diary__service__doctor=doctor).count(),
                    TopicReply.objects.using(using).filter(problem__diary__service__doctor=doctor).count(),
                    Diary.objects.using(using).filter(service__doctor=doctor).count(),
                    TopicReply.objects.using(using).filter(diary__service__doctor=doctor).count(),
                )
                dt_result.append(x)
                print doctor.id
            except Exception as e:
                print e.message
                continue
        open(u'doctors_info.csv', 'wb').write(dt_result.csv)
        open(u'doctors_info.xlsx', 'wb').write(dt_result.xlsx)
        print 'DONE!'
