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

from openpyxl import Workbook, load_workbook
from api.models.diary import Diary, Service
from django.core.management import BaseCommand
from datetime import datetime


class Command(BaseCommand):

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

    '''
       更新数据库命令 sudo python manage.py update_diary_serviceid update ,
       使用前请确认里面数据格式,info.log将记录能正确修改的记录,error.log将记录失败的记录
       包括diaryID对应的diary不存在,新给的serviceID对应的service不存在(不存在不给修改),
       以及保存过程中的一些错误.
    '''

    def handle(self, *args, **options):
        for param in options['param']:
            if param == 'update':
                excel = HandleExcel('update_diary_service_28_29.xlsx')
                excel.write_model()
                print "Complete!"


class HandleExcel:

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

    def save_log(self, log_file, content):
        with open(log_file, 'a+') as f:
            content = "%s--time:%s\n" % (content, datetime.now().strftime('%Y-%m-%d %H:%M:%S %f'))
            f.write(content)

    def write_model(self):
        excel = load_workbook(self.file)
        excel_active = excel.get_sheet_by_name('Sheet1')
        dict_data = {}
        rows = len(excel_active.rows)
        count_str = "count is: %s" % str(rows)
        self.save_log('info.log', count_str)
        for index in range(2, rows + 1):
            dict_data[excel_active.cell(row=index, column=1).value] = \
                excel_active.cell(row=index, column=4).value
        for key, value in dict_data.items():
            diary = None
            origin_service_id = None
            service = None
            try:
                diary = Diary.objects.get(id=key)
                origin_service_id = diary.service_id
            except Exception, ex:
                error_log = "the diary id %s error: the id is not exits in database!" % str(key)
                format_str = "diary_id:%s,orginal_id:%s,new_id:%s" % (str(key), str(origin_service_id), str(value))
                error_log = "%s--%s" % (format_str, error_log)
                self.save_log('error.log', error_log)
                continue
            try:
                service = Service.objects.get(id=value)
            except Exception, ex:
                error_log = "the service id %s error: the new_id is not exits in database, diary id %s!" \
                            % (str(value), str(key))
                format_str = "diary_id:%s,orginal_id:%s,new_id:%s" % (str(key), str(origin_service_id), str(value))
                error_log = "%s--%s" % (format_str, error_log)
                self.save_log('error.log', error_log)
                continue
            if diary and service:
                try:
                    setattr(diary, 'service_id', int(value))
                    diary.save()
                    str_log = "diary_id:%s,orginal_id:%s,new_id:%s" % (str(key), str(origin_service_id), str(value))
                    self.save_log("info.log", str_log)
                except Exception, ex:
                    error_log = "the diary id %s error: %s" % (str(key), str(ex))
                    format_str = "diary_id:%s,orginal_id:%s,new_id:%s" % (str(key), str(origin_service_id), str(value))
                    error_log = "%s--%s" % (format_str, error_log)
                    self.save_log("error.log", error_log)
        complete = "------file:%s is command Complete------" % (self.file)
        self.save_log("info.log", complete)
        self.save_log("error.log", complete)
