# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import tablib
import xlrd
import datetime
from django.core.management import BaseCommand
from api.models.freecustom import FreeCustom
from api.models import Order, ORDER_STATUS


class Command(BaseCommand):

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

        dt = tablib.Dataset()
        dt.headers = ['咨询日期', '免费定制ID', '用户ID', '用户名', '订单号', '订单状态', '美购名称', '多属性', '医生', '下单时间', '金额']

        # file_name = '咨询组李星星7.22-7.28数据反馈'
        # file_name = '咨询组苏德7.22-7.28数据反馈'
        file_name = '咨询组苏歌7.22-7.28数据反馈'

        data = xlrd.open_workbook(file_name + '.xlsx')
        table = data.sheets()[0]
        rows = table.nrows
        print rows

        failed = []
        fid_list = []
        for i in range(1, rows):
            d = table.row_values(i)
            print d[0]
            if d[0]:
                fid = int(d[0])
                fid_list.append(fid)
        print len(fid_list), fid_list

        time_range = [datetime.date(2016, 7, 22), datetime.date(2016, 7, 29)]
        paid_status = ['1', '2', '3', '4', '6', '7', '8', '9']

        for fid in fid_list:
            try:
                free = FreeCustom.objects.get(id=fid)
                user = free.user.user
                orders = Order.objects.filter(user=user, created_time__range=time_range, status__in=paid_status)
                print(orders.count())

                for o in orders:
                    try:
                        uid = user.id
                        uname = user.last_name
                        service = o.service.name
                        doctor = o.service.doctor.name
                        money = o.service_price
                        multi = u'是' if o.service.is_multiattribute else u'否'
                        status = ORDER_STATUS.getDesc(o.status)

                        r = [
                            str(free.create_time), fid, uid, uname, o.id, status, service, multi, doctor, str(o.created_time), money
                        ]
                        dt.append(r)
                        print str(free.create_time), fid, uid, uname, o.id, status, service, multi, doctor, str(o.created_time), money

                    except Exception as e:
                        print o.id, e
                        failed.append(o.id)
                # if not orders:
                #     r = [str(free.create_time), fid, '', '', '', '', '', '', '', '']
                #     dt.append(r)

            except Exception as e:
                failed.append(i)
                print i, e

        with open(file_name + '.csv', 'w') as f:
            f.write(dt.csv)

        print len(failed), failed
