#! /usr/bin/env python
# -*- coding: utf-8 -*-

from openpyxl import Workbook, load_workbook
from api.models.doctor import DoctorAccount
from django.core.management import BaseCommand


class Command(BaseCommand):

    def add_arguments(self, parser):
        parser.add_argument('param', nargs='+', type=str)

    '''
       1,导出execl命令 sudo python manage.py handle_doctor_account_type export,
       导出后目录下会有一个account_type_data.xlsx文件即为导出文件
       2,导入数据库命令 sudo python manage.py handle_doctor_account_type import,
       使用前请确认account_type_data.xlsx文件确认以及里面数据格式,还有type时候赋值完全
    '''

    def handle(self, *args, **options):
        for param in options['param']:
            if param == 'export':
                excel = HandleExcel('account_type_data.xlsx')
                excel.export_file()
            if param == 'import':
                excel = HandleExcel('account_type_data.xlsx')
                excel.write_model()


class HandleExcel:

    def __init__(self, file_name):
        self.file = file_name

    def export_file(self):
        doctor_account_list = DoctorAccount.objects.all()
        excel = Workbook()
        excel_active = excel.get_active_sheet()
        excel_active.title = 'account_type_data'
        head = [u'结算对象ID',
                u'结算对象',
                u'开户银行',
                u'户名',
                u'账号',
                u'账户类型(银行请填0,支付宝填1)'
                ]
        for col in range(6):
            excel_active.cell(row=1, column=col + 1).value = head[col]
        for index, doctor_account in enumerate(doctor_account_list):
            excel_active.cell(row=index + 2, column=1).value = doctor_account.doctor.id
            excel_active.cell(row=index + 2, column=2).value = doctor_account.doctor.name
            excel_active.cell(row=index + 2, column=3).value = doctor_account.bank
            excel_active.cell(row=index + 2, column=4).value = doctor_account.account_name
            excel_active.cell(row=index + 2, column=5).value = doctor_account.account_number
        excel.save(filename=self.file)

    def write_model(self):
        excel = load_workbook(self.file)
        excel_active = excel.get_sheet_by_name('account_type_data')
        dict_data = {}
        rows = excel_active.rows
        for index in range(1, rows):
            dict_data[excel_active.cell(row=index, column=0).value] = \
                excel_active.cell(row=index, column=5).value
        for key, value in dict_data:
            doctor_account = DoctorAccount.objects.filter(doctor__id=key)
            if doctor_account:
                doctor_account.account_type = int(value)
                doctor_account.save()
