# coding=utf-8
import codecs

from django.core.management import BaseCommand
from requests import codes

from api.models import Doctor, Service, Hospital


class Command(BaseCommand):
    """
    python manage.py set_tips_hanguo update
    """

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

    def handle(self, *args, **options):
        print options
        for item in options['param']:
            if item == 'update':
                Process.save_data()
            elif item == 'test':
                Process.test_data()


class Process():
    @staticmethod
    def save_data():
        file_log = open('hostipals.txt', 'r')
        result_log = codecs.open('tips.txt', mode='w', encoding='utf-8')
        lines = file_log.readlines(100000)
        for line in lines:
            try:
                doctor_hospital = Doctor.objects.get(user_id=int(line.strip()))
                doctors = Doctor.objects.filter(hospital_id=doctor_hospital.hospital.id)
                for doctor in doctors:
                    services = Service.objects.filter(doctor_id=doctor.id)
                    for service in services:
                        tip = service.tip
                        service.tip = u'韩国'
                        service.save()
                        print service.id
                        message = u'%s,%s\n' % (service.id, tip)
                        print message
                        result_log.write(message)
            except Exception as e:
                print e.message
                continue
        file_log.close()
        result_log.close()

    @staticmethod
    def test_data():
        file_log = open('hostipals.txt', 'r')
        lines = file_log.readlines(100000)
        for line in lines:
            print line
            try:
                doctor_hospital = Doctor.objects.get(user_id=int(line.strip()))
                doctors = Doctor.objects.filter(hospital_id=doctor_hospital.hospital.id)
                for doctor in doctors:
                    services = Service.objects.filter(doctor_id=doctor.id)
                    for service in services:
                        service.tip = u'韩国'
            except Exception as e:
                print e.message
                continue
        file_log.close()
