# coding=utf-8
import json
import re

import datetime
import unicodedata

import tablib
import xlwt
from django.core.management import BaseCommand

from api.models import Order, ORDER_STATUS, Q
from hera.models import BackendGroup

BUSINESS_GROUPS = [
    'shangwuhuabeizu',
    'shangwuhuadongzu',
    'shangwuhuananzu',
    'shangwuxinanzu',
    'shangwuhuazhongzu',
    'yakezu',
    'shangwuziyingyishengzuA',
    'shangwuziyingyishengzuB',
    'bd_korea',
]


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 make_business_dic():
    buss_dic = {}
    for g_name in BUSINESS_GROUPS:
        g = BackendGroup.objects.get(name=g_name)
        ms = g.members.all()
        for m in ms:
            buss_dic[m.id] = {
                'name': m.first_name or m.username,
                'group_name': g.name,
                'group_title': g.title
            }
    return buss_dic


def xlwt_write_row(sheet, row_num, data):
    colum_num = 0
    for o in data:
        sheet.write(row_num, colum_num, o)
        colum_num += 1


def make_file_by_xlwt(data, header, filename):
    workbook = xlwt.Workbook()
    sheet = workbook.add_sheet('xx')
    xlwt_write_row(sheet, 0, header)

    row_num = 1
    for row in data:
        xlwt_write_row(sheet, row_num, row)
        row_num += 1

    workbook.save(filename)


def real_partner(order, end_time):
    try:
        doctor = order.service.doctor
        now_partner = doctor.business_partener
        if not end_time:
            return None

        change_record = doctor.docbusinessrecord_set.filter(action_time__lte=end_time).last()
        if not change_record:
            return now_partner
        else:
            return change_record.to_business
    except Exception as e:
        print e.message
        return None


def validate_partner(order):
    return real_partner(order, order.validate_time)


class Command(BaseCommand):
    """
    导出订单数据
    python manage.py export_order_data
    """

    def handle(self, *args, **options):
        today = datetime.date.today()
        firstday_of_thismonth = datetime.date(day=1, month=1, year=today.year)
        firstday_of_lastmonth = datetime.date(day=1, month=today.month, year=today.year)
        q = Q(validate_time__range=[firstday_of_thismonth, firstday_of_lastmonth]) | Q(
            pay_time__range=[firstday_of_thismonth, firstday_of_lastmonth])
        orders = Order.objects.filter(q)

        result_tab = tablib.Dataset()

        result_tab.headers = [
            u'订单id', u'订单状态',
            u'付款时间', u'验证时间',
            u'美购id', u'美购名称',
            u'医生id', u'医生姓名', u'医院id', u'医院名称', u'所在城市',
            u'订单总价', u'预付款', u'实际线上付款', u'保险金额', u'美券抵扣金额', u'美分抵扣金额', u'抽成金额',
            u'付款商务id', u'付款商务姓名', u'付款商务分组',
            u'验证商务id', u'验证商务姓名', u'验证商务分组']

        business_dic = make_business_dic()
        i = 0
        begin = 0
        count = orders.count()
        print count

        step = 1000

        while begin <= count:

            for order in orders[begin:begin + step]:
                try:
                    validate_partner = real_partner(order, order.validate_time)
                    pay_partner = real_partner(order, order.pay_time)
                    validate_id = validate_partner.id if validate_partner else ""
                    pay_partner_id = pay_partner.id if pay_partner else ""
                    if validate_id:
                        validate_partner_name = validate_partner.first_name if validate_partner.first_name else \
                            strformat(validate_partner.username)
                        validate_group = business_dic.get(validate_partner.id, {'group_tile': ''}).get('group_title',
                                                                                                       '')
                    else:
                        validate_partner_name = ""
                        validate_group = ""
                    if pay_partner_id:
                        pay_partner_name = pay_partner.first_name if pay_partner.first_name else \
                            strformat(pay_partner.username)
                        pay_partner_group = business_dic.get(pay_partner.id, {'group_tile': ''}).get('group_title', '')
                    else:
                        pay_partner_name = ""
                        pay_partner_group = ""
                    service_snapshopt_json = json.loads(order.service_snapshot)
                    pre_payment_price = service_snapshopt_json.get('pre_payment_price', 0)
                    # insurance_premium = 0
                    insurance_info = order.get_insurance_info()
                    if insurance_info:
                        insurance_premium = insurance_info.get('premium')
                    else:
                        insurance_premium = 0
                    data_set = [
                        order.id,
                        ORDER_STATUS.getDesc(order.status),
                        datetime.datetime.strftime(order.pay_time, "%Y-%m-%d %H:%M:%S") if order.pay_time else '',
                        datetime.datetime.strftime(order.validate_time,
                                                   "%Y-%m-%d %H:%M:%S") if order.validate_time else '',
                        order.service_id,
                        order.service.name,
                        order.service.doctor.id,
                        order.service.doctor.name,
                        order.service.doctor.hospital.id if order.service.doctor.hospital else "",
                        order.service.doctor.hospital.name if order.service.doctor.hospital else "",
                        order.service.doctor.hospital.city.name if order.service.doctor.hospital else "",
                        order.service_price,
                        pre_payment_price,
                        order.real_payment,
                        insurance_premium,
                        order.coupon_deduction,
                        order.points_deduction,
                        order.discount,
                        pay_partner_id,
                        pay_partner_name,
                        pay_partner_group,
                        validate_id,
                        validate_partner_name,
                        validate_group,
                    ]
                    result_tab.append(data_set)
                    i += 1
                    if i % 100 == 0:
                        print(i)
                except Exception as e:
                    print e.message
                    continue
            begin += step

        # make_file_by_xlwt(data, headers, '/data/service/商务绩效.xls')
        open(u'/data/service/商务绩效.xlsx', 'wb').write(result_tab.xlsx)
        open(u'/data/service/商务绩效.csv', 'wb').write(result_tab.csv)
        print ("write is done")
