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

from openpyxl import Workbook, load_workbook
from api.models import Hospital, City
from django.core.management import BaseCommand
from gm_types.gaia import HOSPITAL_TYPE
from datetime import datetime
import sys
reload(sys)
sys.setdefaultencoding("utf-8")


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

    '''
       1,导出execl命令 sudo python manage.py get_hospital_data export,
       hospital_data.xlsx文件即为导出文件
    '''

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


class HandleExcel:
    def __init__(self, file_name):
        self.file = file_name
        self.daqu_dict = {
            u'重庆': u'西南',
            u'云南': u'西南',
            u'新疆': u'西南',
            u'四川': u'西南',
            u'陕西': u'西南',
            u'青海': u'西南',
            u'宁夏': u'西南',
            u'河南': u'西南',
            u'贵州': u'西南',
            u'甘肃': u'西南',
            u'西藏': u'西南',

            u'江西': u'华中',
            u'湖南': u'华中',
            u'湖北': u'华中',
            u'广西': u'华中',

            u'海南': u'华南',
            u'广东': u'华南',
            u'福建': u'华南',

            u'浙江': u'华东',
            u'上海': u'华东',
            u'江苏': u'华东',
            u'安徽': u'华东',

            u'天津': u'华北',
            u'山西': u'华北',
            u'山东': u'华北',
            u'内蒙古': u'华北',
            u'辽宁': u'华北',
            u'吉林': u'华北',
            u'黑龙江': u'华北',
            u'北京': u'华北',
            u'河北': u'华北',

            u'香港': u'海外',
            u'台湾': u'海外',
            u'首尔': u'海外',
            u'曼谷': u'海外',
            u'济州岛': u'海外',
            u'东京': u'海外',
            u'澳门': u'海外'
        }

    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 export_file(self):
        hospital_list = Hospital.objects.all()
        self.save_log("info.log", "count is: %s " % str(len(hospital_list)))
        excel = Workbook()
        excel_active = excel.get_active_sheet()
        excel_active.title = 'hospital_data'
        head = [u'医院名称',
                u'医院类型',
                u'地址',
                u'城市',
                u'省份',
                u'大区',
                ]
        for col in range(6):
            excel_active.cell(row=1, column=col + 1).value = head[col]
        for index, hospital in enumerate(hospital_list):
            try:
                excel_active.cell(row=index + 2, column=1).value = hospital.name
                excel_active.cell(row=index + 2, column=2).value = HOSPITAL_TYPE.getDesc(hospital.hospital_type)
                excel_active.cell(row=index + 2, column=3).value = hospital.location
                excel_active.cell(row=index + 2, column=4).value = hospital.city.name
                excel_active.cell(row=index + 2, column=5).value = hospital.city.province.name \
                    if hospital.city.province else ''
                excel_active.cell(row=index + 2, column=6).value = self.daqu_dict.get(
                    hospital.city.province.name, '')
                info_log = 'import hospital_id:%s' % str(hospital.id)
                self.save_log('info.log', info_log)
            except Exception, ex:
                self.save_log("error.log", 'hospital_id :%s,error:%s' % ((hospital.id), str(ex)))
        excel.save(filename=self.file)
        complete = "------file:%s is command Complete------" % (self.file)
        self.save_log("info.log", complete)
        self.save_log("error.log", complete)
