from django.db import models
from multiselectfield import MultiSelectField
from django.conf import settings
from app_medicalCenters.models import MedicalCenterInfo



class Specialty(models.Model):
    name = models.CharField(
        max_length=100, 
        unique=True, 
        verbose_name="تخصص"
    )

    def __str__(self):
        return self.name

    class Meta:
        db_table = 'tbl_doctor_specialties'
        verbose_name_plural = 'تخصص‌های پزشکی'


class University(models.Model):
    name = models.CharField(
        max_length=100, 
        unique=True, 
        verbose_name="نام دانشگاه"
    )

    def __str__(self):
        return self.name

    class Meta:
        db_table = 'tbl_doctor_universities'
        verbose_name_plural = 'دانشگاه‌های پزشکی'


class Degree(models.Model):
    name = models.CharField(
        max_length=100, 
        unique=True, 
        verbose_name="مقطع تحصیلی"
    )

    def __str__(self):
        return self.name

    class Meta:
        db_table = 'tbl_doctor_degrees'
        verbose_name_plural = 'مدارج تحصیلی'


class DoctorsInfo(models.Model):
    user = models.OneToOneField(
        settings.AUTH_USER_MODEL, 
        on_delete=models.CASCADE, 
        verbose_name="کاربر"
    )
    medical_id = models.CharField(
        max_length=255,
        primary_key = True,
        verbose_name="کد نظام پزشکی"
    )
    specialties = models.CharField(
        max_length=255,
        blank=True,
        null=True,
        verbose_name="تخصص‌ها"
    )
    university = models.CharField(
        max_length=255,
        blank=True, 
        null=True, 
        verbose_name="فارغ‌التحصیل"
    )
    degree = models.CharField(
        max_length=255,
        blank=True,
        null=True, 
        verbose_name="مدرک تحصیلی"
    )
    profile_image = models.ImageField(
        upload_to='app_doctors/profile_image/', 
        blank=True, 
        null=True, 
        verbose_name='تصویر پروفایل پزشک'
    )
    introduction_video = models.FileField(
        upload_to='app_doctors/introduction_video/', 
        blank=True, 
        null=True,
        verbose_name='ویدیو معرفی پزشک'
    )
    office_location = models.CharField(
        max_length=15, 
        blank=True, 
        null=True, 
        verbose_name='لوکیشن مطب'
    )
    resume = models.TextField(
        blank=True, 
        null=True, 
        verbose_name='رزومه'
    )
    description = models.TextField(
        blank=True, 
        null=True, 
        verbose_name='توضیحات'
    )
    name_medical_centers = models.CharField(
        max_length=255,
        blank=True, 
        null=True,
        verbose_name="فعالیت در مراکز درمانی"
    )
   
    

    def __str__(self):
        return f"{self.user.first_name} {self.user.last_name}"

    class Meta:
        db_table = 'tbl_doctor_info'
        verbose_name_plural = 'اطلاعات پزشک'


class DoctorsDatabase(models.Model):
    medical_id = models.CharField(
        max_length=40, 
        primary_key=True, 
        verbose_name="شماره نظام پزشکی"
    )
    first_name = models.CharField(
        max_length=30, 
        blank=True, 
        null=True, 
        verbose_name="نام"
    )
    last_name = models.CharField(
        max_length=50, 
        blank=True, 
        null=True, 
        verbose_name="نام خانوادگی"
    )
    specialtie = models.CharField(
        max_length=255, 
        blank=True, 
        null=True, 
        verbose_name="تخصص"
    )
    city = models.CharField(
        max_length=100, 
        blank=True, 
        null=True, 
        verbose_name="شهر"
    )
    degree = models.CharField(
        max_length=100, 
        blank=True, 
        null=True, 
        verbose_name="مدرک تحصیلی"
    )

    def __str__(self):
        return f"{self.first_name} {self.last_name} نظام پزشکی: {self.medical_id}"

    class Meta:
        db_table = 'tbl_doctor_database'
        verbose_name_plural = 'پایگاه داده پزشکان'


from django.contrib import admin
from .models import Specialty, University, Degree, DoctorsInfo
from .forms import DoctorsInfoForm
from app_medicalCenters.models import MedicalCenterInfo


class BaseAdmin(admin.ModelAdmin):
    list_display = ('name',)
    search_fields = ('name',)


@admin.register(Specialty)
class SpecialtyAdmin(BaseAdmin):
    list_display = ('name',)
    search_fields = ('name',)


@admin.register(University)
class UniversityAdmin(BaseAdmin):
    list_display = ('name',)
    search_fields = ('name',)


@admin.register(Degree)
class DegreeAdmin(BaseAdmin):
    list_display = ('name',)
    search_fields = ('name',)


@admin.register(DoctorsInfo)
class DoctorsInfoAdmin(admin.ModelAdmin):
    form = DoctorsInfoForm
    change_form_template = 'admin/app_doctors/DoctorsInfo/change_form.html'
    list_display = ('get_user_full_name', 'medical_id', 'university', 'degree', 'specialties', 'name_medical_centers')
    search_fields = (
        'user__first_name', 'user__last_name', 'specialties',
        'university', 'degree',
    )
    autocomplete_fields = ('user',)
    fields = (
        'user', 'medical_id', 'specialties_existing', 'specialties', 'university', 'degree',
        'office_location', 'medical_centers_existing', 'name_medical_centers', 'profile_image',
        'introduction_video', 'resume', 'description',
    )

    def get_extra_context(self, request):
        return {
            'university_list': list(University.objects.values_list('name', flat=True)),
            'degree_list': list(Degree.objects.values_list('name', flat=True)),
            'specialty_list': list(Specialty.objects.values_list('name', flat=True)),
            'name_medical_centers': list(MedicalCenterInfo.objects.values_list('name_medical_center', flat=True)),
        }

    def add_view(self, request, form_url='', extra_context=None):
        extra_context = extra_context or {}
        extra_context.update(self.get_extra_context(request))
        return super().add_view(request, form_url, extra_context=extra_context)

    def change_view(self, request, object_id, form_url='', extra_context=None):
        extra_context = extra_context or {}
        extra_context.update(self.get_extra_context(request))
        return super().change_view(request, object_id, form_url, extra_context=extra_context)

    def get_user_full_name(self, obj):
        return f"{obj.user.first_name} {obj.user.last_name}"
    get_user_full_name.short_description = 'نام پزشک'

from django import forms
from django_select2.forms import Select2MultipleWidget
from .models import DoctorsInfo, Specialty, DoctorsDatabase
from app_medicalCenters.models import MedicalCenterInfo


class DoctorsInfoForm(forms.ModelForm):
    medical_id = forms.CharField(
        label='کد نظام پزشکی',
        widget=forms.TextInput(attrs={'list': 'medical_id-list'})
    )

    university = forms.CharField(
        label='نام دانشگاه',
        widget=forms.TextInput(attrs={'list': 'university-list'})
    )
    
    degree = forms.CharField(
        label='مقطع تحصیلی',
        widget=forms.TextInput(attrs={'list': 'degree-list'})
    )

    specialties_existing = forms.MultipleChoiceField(
        label='انتخاب گر تخصص',
        choices=[(specialty.name, specialty.name) for specialty in Specialty.objects.all()],
        required=False,
        widget=Select2MultipleWidget
    )

    specialties = forms.CharField(
        label='تخصص‌ها',
        required=False,
        widget=forms.TextInput(attrs={
            'placeholder': 'وارد کردن تخصص'
        }),
    )

    medical_centers_existing = forms.MultipleChoiceField(
        label='انتخاب گر مراکز درمانی',
        choices=[(center.name_medical_center, center.name_medical_center) for center in MedicalCenterInfo.objects.all()],
        required=False,
        widget=Select2MultipleWidget
    )

    name_medical_centers = forms.CharField(
        label='نام مراکز درمانی',
        required=False,
        widget=forms.TextInput(attrs={
            'placeholder': 'وارد کردن نام مراکز درمانی'
        }),
    )

    class Meta:
        model = DoctorsInfo
        fields = '__all__'
        widgets = {
            'specialties': Select2MultipleWidget,
            'medical_centers_existing': Select2MultipleWidget,
        }

    def clean_name_medical_centers(self):
        centers_existing = self.cleaned_data.get('medical_centers_existing', [])
        centers_input = self.cleaned_data.get('name_medical_centers', '').split(',')
        all_centers = [c.strip() for c in centers_existing + centers_input if c.strip()]
        return ', '.join(set(all_centers))

    def clean_specialties(self):
        specialties_existing = self.cleaned_data.get('specialties_existing', [])
        specialties = self.cleaned_data.get('specialties', '').split(',')
        all_specialties = [s.strip() for s in specialties_existing + specialties if s.strip()]
        return ', '.join(set(all_specialties))

    def save(self, commit=True):
        instance = super().save(commit=False)
        instance.name_medical_centers = self.clean_name_medical_centers()
        instance.specialties = self.clean_specialties()
        if commit:
            instance.save()
        return instance

    class Media:
        css = {
            'all': ('app_doctors/css/custom_select2.css',)
        }


کد های بالا رو در نظر بگیر میخوام کاری کنم که در پنل ادمین وفتی بخشی از کد نظام پزشکی رو وارد میکنم موارد مشابه بهم  از جدول دیتا بیس پزشکان بهم پیشنهاد بشه 
مثل حالتی که برای نام دانشگاه و یا و مقطع تحصیلی وجود داره