#!/usr/bin/env python
# encoding=utf-8
import hashlib

from django.conf import settings
from django.core.management import BaseCommand
from gm_types.gaia import PAYMENT_TYPE

from api.models import PeriodHospital
from api.models.service import Service


def service_is_support_renmai(service):
    if service.is_multiattribute:
        prices = service.gengmei_price_list
        if prices:
            min_price = min(prices)
            max_price = max(prices)
        else:
            min_price = service.gengmei_price
            max_price = service.gengmei_price
    else:
        min_price = service.gengmei_price
        max_price = service.gengmei_price

    if service.payment_type == PAYMENT_TYPE.PREPAYMENT \
            and (settings.RENMAI_INSTALLMENT_MIN_PAY <= min_price <= settings.RENMAI_INSTALLMENT_MAX_PAY) \
            and (settings.RENMAI_INSTALLMENT_MIN_PAY <= max_price <= settings.RENMAI_INSTALLMENT_MAX_PAY) \
            and PeriodHospital.check_hospital_in_list(service.doctor.hospital.id):
        return True
    else:
        return False


class Command(BaseCommand):
    def handle(self, *args, **options):
        service = open('service_renmai.txt', 'r')
        result = open('result.txt', 'w')
        error = open('error.text', 'w')
        allline = service.readlines()
        for line in allline:
            try:
                if int(line) == 0:
                    continue
                print('id:'+line)
                try:
                    service = Service.objects.get(id=int(line))
                except Service.DoesNotExist:
                    continue
                if not service.is_stage:
                    if service_is_support_renmai(service):
                        temp = service.doctor.hospital.id + ' ' + service.doctor.hospital.name + ' ' +\
                               service.doctor.id + " " + service.doctor.name + ' ' + service.name + ' ' +\
                               str(service.id) + '\n'
                        try:
                            temp1 = temp.encode('utf-8')
                            result.write(temp1)
                        except:
                            result.write(temp)
            except Exception as e:
                print e
                error.write(line + '\n')

        service.close()
        result.close()
