# coding=utf-8

from django.core.management import BaseCommand
from django.db import transaction
from openpyxl import load_workbook
from api.models.itemwiki import ItemWiki, OptimizeWiki
from gm_types.gaia import OPTIMIZE_WIKI_TYPE
import json


def get_value(ws, row, column):
    return ws.cell(row=row, column=column).value or 0


def create_optimizewiki(itemwiki_id, type, content):
    if content and type not in [2, 4]:
        content = '<p>' + content.replace('\n', '</p><p>') + '</p>'
    data = {
        'wiki_id': itemwiki_id,
        'title': OPTIMIZE_WIKI_TYPE.getDesc(str(type)),
        'type': type,
        'ordering': type,
        'content': content if content else '',
        'is_visible': False if type == 4 else True
    }
    try:
        opwiki = OptimizeWiki.objects.get(wiki_id=itemwiki_id,type=type)
        for k, v in data.iteritems():
            setattr(opwiki, k, v)
        opwiki.save()
    except:
        opwiki = OptimizeWiki.objects.create(**data)
    return opwiki.id


class Command(BaseCommand):
    def handle(self, *args, **options):
        ItemWiki.objects.all().update(is_online=False)
        result_log = open('itemwiki.txt', 'a')
        wb = load_workbook(filename=u'百科数据导入表.xlsx')
        sheetnames = wb.get_sheet_names()
        ws = wb.get_sheet_by_name(sheetnames[0])
        for rx in range(2, ws.get_highest_row() + 1):
            try:
                with transaction.atomic():
                    itemwiki_id = get_value(ws, rx, 1)
                    item_date = {
                        'item_name': get_value(ws, rx, 2),
                        'is_online': True,
                        'treatment_means': str(get_value(ws, rx, 5)),
                        'ache_level': str(get_value(ws, rx, 6)),
                        'effect_duration_md': get_value(ws, rx, 7),
                        'treatment_time_min': get_value(ws, rx, 8),
                        'treatment_time_max': get_value(ws, rx, 9),
                        'price_min': get_value(ws, rx, 10),
                        'price_max': get_value(ws, rx, 11),
                        'anesthesia_type': str(get_value(ws, rx, 13)),
                        'hospital_treatment': str(get_value(ws, rx, 14)),
                        'hospital_days_min': get_value(ws, rx, 15),
                        'hospital_days_max': get_value(ws, rx, 16),
                        'line_days_min': get_value(ws, rx, 17),
                        'line_days_max': get_value(ws, rx, 18),
                    }
                    try:
                        itemwiki = ItemWiki.objects.get(id=itemwiki_id)
                    except:
                        itemwiki = ItemWiki.objects.create(**item_date)
                    for k, v in item_date.iteritems():
                        setattr(itemwiki, k, v)
                    itemwiki.save()

                    item_date.pop('item_name')
                    item_date.pop('is_online')
                    op1 = create_optimizewiki(itemwiki.id, 1, get_value(ws, rx, 3))
                    op2 = create_optimizewiki(itemwiki.id, 2, json.dumps(item_date))
                    op3 = create_optimizewiki(itemwiki.id, 3, get_value(ws, rx, 19))
                    op4 = create_optimizewiki(itemwiki.id, 4, get_value(ws, rx, 20))
                    op5 = create_optimizewiki(itemwiki.id, 5, get_value(ws, rx, 21))
                    op6 = create_optimizewiki(itemwiki.id, 6, get_value(ws, rx, 22))
                    op7 = create_optimizewiki(itemwiki.id, 7, get_value(ws, rx, 23))
                    op8 = create_optimizewiki(itemwiki.id, 8, get_value(ws, rx, 24))
                    name = itemwiki.item_name.encode('utf-8')
                    message = '%s:%s,%s,%s,%s,%s,%s,%s,%s,%s\n' % \
                              (itemwiki.id, name, op1, op2, op3, op4, op5, op6, op7, op8)
                    result_log.write(message)
                    print itemwiki.id
            except Exception as e:
                name = get_value(ws, rx, 2).encode('utf-8')
                result_log.write(name + '\n')
                print e.message
                continue
        print 'DONE!'
        result_log.close()
