# coding=utf-8
from django.core.management import BaseCommand
from openpyxl import load_workbook, Workbook
from openpyxl.writer.excel import ExcelWriter

from api.models import ItemWiki, Tag
import traceback


class Command(BaseCommand):
    """
    导入wiki数据 python manage.py wiki_guide_data 'xlsx文件名'
    会在项目目录下生成一个result.xlsx文件,记录导入数据结果
    """

    def add_arguments(self, parser):
        """
        文件路径
        """
        parser.add_argument('xlsx', type=str)

    def handle(self, *args, **options):
        if options['xlsx'] is None:
            return
        xlsx = options['xlsx']
        wb = load_workbook(filename=xlsx)
        sheetnames = wb.get_sheet_names()
        if sheetnames == 0:
            return
        ws = wb.get_sheet_by_name(sheetnames[0])
        QuideData.quide_data(ws=ws)


class QuideData():
    @classmethod
    def quide_data(self, ws):
        if ws is None:
            return
        wb_result = Workbook()  # 新建一个工作薄
        ew_result = ExcelWriter(workbook=wb_result)  # 新建一个ExcelWriter,用来写wb_result
        dest_filename = 'result.xlsx'  # wb_result的名字
        ws1 = wb_result.worksheets[0]  # 取得wb_result的第一个工作表ws1
        ws1.title = 'result'  # 指定ws1的名字
        for rx in range(3, ws.get_highest_row()):
            try:
                print rx
                tag_id = ws.cell(row=rx, column=3).value
                surgical_grade = ws.cell(row=rx, column=4).value
                treatment_means = ws.cell(row=rx, column=5).value
                treatment_time_min = ws.cell(row=rx, column=6).value
                treatment_time_max = ws.cell(row=rx, column=7).value
                complexity_type = ws.cell(row=rx, column=8).value
                risk_factor_type = ws.cell(row=rx, column=9).value
                line_days_min = ws.cell(row=rx, column=10).value
                line_days_max = ws.cell(row=rx, column=11).value
                price_min = ws.cell(row=rx, column=12).value
                price_max = ws.cell(row=rx, column=13).value
                hospital_treatment = ws.cell(row=rx, column=14).value
                hospital_days_min = ws.cell(row=rx, column=15).value
                hospital_days_max = ws.cell(row=rx, column=16).value
                recovery_time_min = ws.cell(row=rx, column=17).value
                recovery_time_max = ws.cell(row=rx, column=18).value
                description_md = ws.cell(row=rx, column=19).value
                effect_duration_md = ws.cell(row=rx, column=20).value
                advantage_md = ws.cell(row=rx, column=21).value
                shortcoming_md = ws.cell(row=rx, column=22).value
                notes_md = ws.cell(row=rx, column=23).value
                risk_warning_md = ws.cell(row=rx, column=24).value
                avoid_people_md = ws.cell(row=rx, column=25).value
                anesthesia_method = ws.cell(row=rx, column=26).value
            except Exception as e:
                ws1.cell(row=rx, column=1).value = rx
                ws1.cell(row=rx, column=2).value = u'读取excel数据失败!'
                ws1.cell(row=rx, column=3).value = e.message
                continue
            try:
                count = ItemWiki.objects.filter(tag__id=tag_id).count()
                if count > 0:
                    itemwiki = ItemWiki.objects.get(tag__id=tag_id)
                    itemwiki.surgical_grade = surgical_grade
                    itemwiki.treatment_means = treatment_means
                    itemwiki.treatment_time_min = treatment_time_min
                    itemwiki.treatment_time_max = treatment_time_max
                    itemwiki.complexity_type = complexity_type
                    itemwiki.risk_factor_type = risk_factor_type
                    itemwiki.line_days_min = line_days_min
                    itemwiki.line_days_max = line_days_max
                    itemwiki.price_min = price_min
                    itemwiki.price_max = price_max
                    itemwiki.hospital_treatment = hospital_treatment
                    itemwiki.hospital_days_min = hospital_days_min
                    itemwiki.hospital_days_max = hospital_days_max
                    itemwiki.recovery_time_min = recovery_time_min
                    itemwiki.recovery_time_max = recovery_time_max
                    itemwiki.description_md = description_md
                    itemwiki.effect_duration_md = effect_duration_md
                    itemwiki.advantage_md = advantage_md
                    itemwiki.shortcoming_md = shortcoming_md
                    itemwiki.notes_md = notes_md
                    itemwiki.risk_warning_md = risk_warning_md
                    itemwiki.avoid_people_md = avoid_people_md
                    itemwiki.anesthesia_method = anesthesia_method
                    if itemwiki.recovery_md is None:
                        itemwiki.recovery_md = u''
                    itemwiki.save()
                    ws1.cell(row=rx, column=1).value = tag_id
                    ws1.cell(row=rx, column=2).value = u'已更新成功'
                else:
                    if Tag.objects.filter(id=tag_id).count() != 1:
                        ws1.cell(row=rx, column=1).value = tag_id
                        ws1.cell(row=rx, column=2).value = u'添加失败!'
                        ws1.cell(row=rx, column=3).value = u'没有该TagID!'
                        continue
                    itemwiki = ItemWiki(
                        tag_id=tag_id,
                        surgical_grade=surgical_grade,
                        treatment_means=treatment_means,
                        treatment_time_min=treatment_time_min,
                        treatment_time_max=treatment_time_max,
                        complexity_type=complexity_type,
                        risk_factor_type=risk_factor_type,
                        line_days_min=line_days_min,
                        line_days_max=line_days_max,
                        price_min=price_min,
                        price_max=price_max,
                        hospital_treatment=hospital_treatment,
                        hospital_days_min=hospital_days_min,
                        hospital_days_max=hospital_days_max,
                        recovery_time_min=recovery_time_min,
                        recovery_time_max=recovery_time_max,
                        description_md=description_md,
                        effect_duration_md=effect_duration_md,
                        advantage_md=advantage_md,
                        shortcoming_md=shortcoming_md,
                        notes_md=notes_md,
                        risk_warning_md=risk_warning_md,
                        avoid_people_md=avoid_people_md,
                        anesthesia_method=anesthesia_method,
                        recovery_md=''
                    )
                    itemwiki.save()
                    ws1.cell(row=rx, column=1).value = tag_id
                    ws1.cell(row=rx, column=2).value = u'已添加成功'
            except Exception as e:
                ws1.cell(row=rx, column=1).value = tag_id
                ws1.cell(row=rx, column=2).value = u'更新失败!'
                ws1.cell(row=rx, column=3).value = e.message
                ws1.cell(row=rx, column=4).value = traceback.print_exc()
        print u'success!'
        ew_result.save(filename=dest_filename)  # 保存结果文件
