# coding=utf-8

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

from channel.models import Channel, ChannelVendor

class Command(BaseCommand):
    """
    python manage.py insert_20170320_create_statement_account
    """

    def handle(self, *args, **options):
        filename = 'statistic_channel.xlsx'
        if os.path.exists(filename):
            data = xlrd.open_workbook(filename)
            for table in data.sheets():
                for row in range(1, table.nrows):
                    r_info = table.row_values(row)
                    try:
                        name = r_info[2]
                        channelvendor, created = ChannelVendor.objects.update_or_create(name=r_info[3])
                        if not name:
                            if '--' in r_info[3]:
                                name = r_info[3].split('--')[-1]
                            elif '-' in r_info[3]:
                                name = r_info[3].split('-')[-1]

                        c, created = Channel.objects.update_or_create(
                            name=name,
                            url_name=r_info[1],
                            vendor_id=channelvendor.id
                        )
                        print("channel_id: %d, channelvendor_id: %d" % (c.id, channelvendor.id))
                    except Exception as e:
                        print(r_info[0], 'failed!----------', str(e))

        else:
            print('file does not exisits!!!')

        print("done!!!")