#!/usr/bin/env python
# encoding=utf-8

import xlrd
import json
from django.core.management import BaseCommand

from gm_types.gaia import ORDER_STATUS
from api.models import SettlementItem, Order


class Command(BaseCommand):

    def handle(self, *args, **options):
        total = 0
        settlement_data = xlrd.open_workbook("settlement.xlsx")
        xls_sheet = settlement_data.sheets()[0]
        not_exists, wait_to_handle = [], []
        for line in range(0, xls_sheet.nrows):
            total += 1
            row_value = xls_sheet.row_values(line)
            settlement_id = row_value[0]
            order_list = SettlementItem.objects.filter(settlement_id=settlement_id).values_list('order_id', flat=True)
            for order_id in order_list:
                try:
                    o = Order.objects.get(id=order_id)
                    if o.status in [
                        ORDER_STATUS.PAID,
                        ORDER_STATUS.USED,
                        ORDER_STATUS.WAIT_REFUNDED,
                        ORDER_STATUS.REFUNDED
                    ]:
                        continue
                    print("current_order_status: {}".format(o.status))
                    wait_to_handle.append(order_id)
                except Order.DoesNotExist:
                    not_exists.append(order_id)

        with open('wait_to_handle.txt', 'w') as f:
            f.write(json.dumps(wait_to_handle))

        with open('not_exists.txt', 'w') as f:
            f.write(json.dumps(not_exists))

        print("done!, total: %d" % total)