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

import pinyin

from django.contrib import admin, messages
from django.contrib.admin import ModelAdmin
from django.contrib.auth.models import User
from django.db import IntegrityError

from api.models import Doctor, Hospital, BodyPart
from api.tool.image_utils import get_full_path
from doctor.models import DoctorRegister, HospitalCapture, DoctorCapture, ItemsCapture


class DoctorRegisterAdmin(ModelAdmin):
    """
    医生注册
    """
    list_display = ('name', 'hospital', 'add_time', 'is_handled', 'comments')
    list_editable = ('is_handled', 'comments')
    ordering = ('-id',)
    readonly_fields = ('image_preview',)

    fieldsets = (
        ("详情", {
            'fields': (
                ('name', 'image_preview', 'portrait', 'profession_number',),
                ('hospital', 'department', 'title',),
                ('good_at',),
                ('introduction',),
                ('inviter', 'is_handled',),
                ('comments',),
            )
        }),
    )

    def image_preview(self, data):
        if data and data.portrait:
            return u'<img src="{}"/>'.format(get_full_path(data.portrait))
        else:
            return u''

    image_preview.short_description = u'图片'
    image_preview.allow_tags = True

    def is_handled(self, data):
        doctor = DoctorRegister.objects.get(phone=data['phone'])
        doctor.is_handled = True
        doctor.save()

    def create_user(self, data):
        user = User()
        user.username = data['phone']
        user.set_password(data['phone'])
        user.last_name = data['name']
        user.email = data['email']
        user.is_staff = True
        user.save()
        return user

    def create_doctor(self, user, data):
        doctor = Doctor()
        name = pinyin.get(data['name'])
        doctor.id = name
        doctor.name = data['name']
        doctor.department = data['department']
        doctor.good_at = data['good_at']
        doctor.introduction = data['introduction']
        doctor.title = data['title']
        doctor.phone = data['phone']
        doctor.portrait = get_full_path(data['portrait'])
        doctor.user = user
        doctor.process_status = '0'
        doctor.is_online = False
        doctor.doc_email = data['email']
        doctor.accept_private_msg = False
        doctor.operate_log = u"医院：{}\n医生执业号{}".format(data['hospital'], data['profession_number'])
        doctor.save()
        for part in data['good_at'].split(','):
            try:
                body = BodyPart.objects.get(name=part)
                doctor.body_parts.add(body)
            except BodyPart.DoesNotExist:
                pass
        doctor.save()

    def generate_doctor(self, request, queryset):
        for data in queryset.values():
            try:
                try:
                    doctor = Doctor.objects.get(id=pinyin.get(data['name']))
                    if doctor:
                        messages.error(request, u'同名医生已经存在，请手动处理！')
                        continue
                except Doctor.DoesNotExist:
                    pass
                # 手机号注册过用户
                user = User.objects.get(username=data['phone'])
                if user.is_staff:
                    # try:
                    #     doctor = Doctor.objects.get(id=pinyin.get(data['name']))
                    #     # 是医生账号, 补充信息
                    #     for part in data['good_at'].split(','):
                    #         try:
                    #             body = BodyPart.objects.get(name=part)
                    #             doctor.body_parts.add(body)
                    #         except BodyPart.DoesNotExist:
                    #             pass
                    #     doctor.operate_log = u"医院：{}\n医生执业号{}".format(data['hospital'], data['profession_number'])
                    #     doctor.save()
                    # except Doctor.DoesNotExist:
                    #     pass
                    messages.error(request, u'相同手机号的医生用户已经存在,请手动检查处理！')
                else:
                    # 生成医生账号
                    user.is_staff = True
                    user.last_name = data['name']
                    user.set_password(data['phone'])
                    user.groups = '2'
                    user.email = data['email']
                    user.save()
                    self.create_doctor(user, data)
                    self.is_handled(data)
            except User.DoesNotExist:
                # 不是注册用户,先生成用户账号再生成医生账号
                user = self.create_user(data)
                user.groups = '2'
                self.create_doctor(user, data)
                self.is_handled(data)
    generate_doctor.short_description = u'生成医生账号'
    actions = ['generate_doctor']

admin.site.register(DoctorRegister, DoctorRegisterAdmin)


class HospitalCaptureAdmin(ModelAdmin):
    list_display = ('name', 'specialty', 'description', 'tel', 'is_handled', 'info_verified')
    list_editable = ('tel', 'description', 'is_handled', 'info_verified')
    list_filter = ('specialty',)
    search_fields = ('name',)

    def handled(self, data):
        hospital = HospitalCapture.objects.get(url_id=data['url_id'])
        hospital.is_handled = True
        hospital.save()

    def generate_hospital(self, request, queryset):
        for data in queryset.values():
            hospital_capture = HospitalCapture.objects.get(url_id=data['url_id'])
            #先判断是否有同名医院已经存在,若果有直接关联到现有医院
            try:
                hos = Hospital.objects.get(name=data['name'])
                hospital_capture.uuid = hos.id
                hospital_capture.save()
            except Hospital.DoesNotExist:
                uuid = pinyin.get_initial(data['name']).replace(' ', '') + str(data['url_id'])
                #保存uuid以便在生成医生账户时可关联对应的医院
                hospital_capture.uuid = uuid
                hospital_capture.save()
                try:
                    Hospital.objects.get(id=uuid)
                except Hospital.DoesNotExist:
                    hospital = Hospital()
                    hospital.id = uuid
                    hospital.name = data['name']
                    hospital.location = data['address']
                    hospital.description = data['description']
                    hospital.hospital_type = data['hospital_type']
                    hospital.save()
            except IntegrityError:
                pass

            self.handled(data)
    generate_hospital.short_description = u'生成医院'
    actions = ['generate_hospital']


admin.site.register(HospitalCapture, HospitalCaptureAdmin)


class DoctorCaptureAdmin(ModelAdmin):
    list_display = ('name', 'hospital', 'description', 'comments', 'is_handled', 'info_verified',)
    list_editable = ('description', 'info_verified', 'comments', 'is_handled',)
    raw_id_fields = ('hospital', )
    search_fields = ('name',)
    actions = ['generate_doctor']

    def handled(self, data):
        doctor = DoctorCapture.objects.get(doctor_url_id=data['doctor_url_id'])
        doctor.is_handled = True
        doctor.save()

    def create_doctor(self, user, data):
        doctor = Doctor()
        name = pinyin.get(data['name'])
        doctor.id = name
        doctor.name = data['name']
        doctor.introduction = data['description']
        doctor.title = ''
        doctor.phone = ''
        doctor.user = user
        doctor.process_status = '0'
        doctor.is_online = False
        doctor.accept_private_msg = False
        doctor.operate_log = u"医院：{}".format(data['hospital_id'])
        if data['hospital_id']:
            doctor.hospital = Hospital.objects.get(id=HospitalCapture.objects.get(url_id=data['hospital_id']).uuid)

        doctor.save()

    def generate_doctor(self, request, queryset):
        for data in queryset.values():
            #已经处理的忽略掉
            if data['is_handled']:
                continue
            try:
                uuid = pinyin.get(data['name'])
                Doctor.objects.get(id=uuid)
                messages.error(request, u'同名医生{}已经存在'.format(data['name']))
                continue
            except Doctor.DoesNotExist:
                user = User()
                user.username = uuid + str(data['doctor_url_id'])
                user.set_password(uuid)
                user.last_name = data['name']
                user.is_staff = True
                user.save()
                user.groups = '2'
                try:
                    self.create_doctor(user, data)
                except Hospital.DoesNotExist:
                    messages.error(request, u'请先将{}关联的医院生成!'.format(data['name']))
                self.handled(data)
    generate_doctor.short_description = u'生成医生账号'

admin.site.register(DoctorCapture, DoctorCaptureAdmin)


class ItemsCaptureAdmin(ModelAdmin):
    list_display = ('item_name', 'item_sub_item', 'slogan', 'level_attention', 'level_safety', 'level_complex')
    list_filter = ('level_attention', 'level_safety', 'level_complex')

admin.site.register(ItemsCapture, ItemsCaptureAdmin)
