# coding:utf-8

import tablib
import xlrd
from django.core.management import BaseCommand
from django.core.exceptions import ObjectDoesNotExist
from api.models import Order
from pay.models import PaymentOrder
from api.models.types import ORDER_STATUS, PAYMENT_CHANNEL
from api.tool.log_tool import logging_exception

__author__ = 'chengliang'


class Command(BaseCommand):

    @staticmethod
    def get_order_info_from_order(order):
        """
        :param order: order object
        :return:
        """
        result = []
        try:
            order_num = order.id
            payment = order.payment
            service_name = order.service.name
            create_time = order.created_time
            refund_why = order.refund_comment
            comment = order.comments
            nick_name = order.user.last_name if order.user else ''
            name = order.name
            doctor_name = order.service.doctor.name or ''
            channel = order.payment_channel

            trade_num = ''
            try:
                payment_order = PaymentOrder.objects.get(orders=order.id)
                trade_num = payment_order.out_trade_no
            except ObjectDoesNotExist:
                logging_exception()
            if channel == PAYMENT_CHANNEL.WECHAT:
                channel = u'微信支付'
            elif channel == PAYMENT_CHANNEL.ALIPAY:
                channel = u'支付宝支付'

            result = (order_num, trade_num, payment, service_name, doctor_name, create_time, refund_why, comment, nick_name, name, channel)

        except:
            logging_exception()

        return result

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

        f = open('doctors.txt')
        doctor_names = f.read().split('\n')

        headers = (u'订单号', u'交易流水号', u'金额', u'项目名称', u'医生姓名', u'下单时间', u'退款原因', u'备注', u'用户昵称', u'用户姓名', u'支付方式')
        data = []
        for d_name in doctor_names:
            orders = Order.objects.filter(status=ORDER_STATUS.WAIT_REFUNDED, service__doctor__name=d_name)
            for order in orders:
                item = self.get_order_info_from_order(order)
                data.append(item)

        headers = tuple(headers)
        data = tablib.Dataset(*data, headers=headers)

        with open('DOCTOR_ORDER_REFUND.csv', 'wb') as f:
            f.write(data.csv)

