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="کاربر"
    )
    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 = 'اطلاعات پزشک'



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):
    pass


@admin.register(University)
class UniversityAdmin(BaseAdmin):
    pass


@admin.register(Degree)
class DegreeAdmin(BaseAdmin):
    pass


@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', 'university', 'degree', 'specialties', 'name_medical_centers')
    search_fields = (
        'user__first_name', 'user__last_name', 'specialties',
        'university', 'degree',
    )
    autocomplete_fields = ('user',)
    fields = (
        'user', '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
from app_medicalCenters.models import MedicalCenterInfo


class DoctorsInfoForm(forms.ModelForm):
    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',)
        }



{% extends "admin/change_form.html" %}

{% block content %}
    {{ block.super }}
    <datalist id="university-list">
        {% for name in university_list %}
            <option value="{{ name }}">{{ name }}</option>
        {% endfor %}
    </datalist>
    <datalist id="degree-list">
        {% for name in degree_list %}
            <option value="{{ name }}">{{ name }}</option>
        {% endfor %}
    </datalist>

{% endblock %}

با توجه به کد بالا میخوام کد زیر رو اصلاح کنی و فیلد sick رو مثل user و فیلد insurance_type رو مثل insurance_type و فیلد underlying_disease. رو مثل specialties و فیلد drug_sensitivity رو هم مثل specialties در پنل ادمین نمایش  داده شود
فقط در نظر بگیر برای فیلد underlying_disease باید از مدل DiseaseInfo و برای فیلد drug_sensitivity رو از مدل MedicinesInfo استفاده شود

from django.db import models

class MedicinesInfo(models.Model):
    name = models.CharField(
        max_length=100,
        unique=True,
        verbose_name="نام دارو"
    )

    def __str__(self):
        return self.name

    class Meta:
        db_table = 'tbl_medicines_info'
        verbose_name_plural = 'اطلاعات داروها'

from django.db import models
from django.conf import settings
from app_pharmacy.models import MedicinesInfo


class PatientSymptoms(models.Model):
    name = models.CharField(
        max_length=100,
        unique=True,
        verbose_name="عنوان علائم"
    )

    def __str__(self):
        return self.name

    class Meta:
        db_table = 'tbl_patient_symptoms'
        verbose_name_plural = 'علائم های بیمار'


class DiseaseInfo(models.Model):
    name = models.CharField(
        max_length=100,
        unique=True,
        verbose_name="عنوان بیماری"
    )

    def __str__(self):
        return self.name

    class Meta:
        db_table = 'tbl_disease_info'
        verbose_name_plural = 'اطلاعات بیماری ها'


class Insurance(models.Model):
    name = models.CharField(
        max_length=100,
        unique=True,
        verbose_name="عنوان بیمه"
    )

    def __str__(self):
        return self.name

    class Meta:
        db_table = 'tbl_insurance_type'
        verbose_name_plural = 'نوع بیمه درمانی'


class PatientsInfo(models.Model):
    sick = models.OneToOneField(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        verbose_name="بیمار"
    )
    insurance_type = models.CharField(
        max_length=255,
        blank=True,
        null=True,
        verbose_name="نوع بیمه"
    )
    underlying_disease = models.CharField(
        max_length=255,
        blank=True,
        null=True,
        verbose_name='بیماری زمینه ای'
    )
    drug_sensitivity = models.CharField(
        max_length=255,
        blank=True,
        null=True,
        verbose_name='حساسیت دارویی'
    )
    
    def __str__(self):
        return f"{self.sick.first_name} {self.sick.last_name}"

    class Meta:
        db_table = 'tbl_patients_info'
        verbose_name_plural = 'اطلاعات بیمار'

from django import forms
from django_select2.forms import Select2MultipleWidget
from .models import PatientsInfo


class PatientsInfoForm(forms.ModelForm):
    insurance_type = forms.CharField(
        label="نوع بیمه3",
        widget=forms.TextInput(attrs={'list': 'insurance_type-list'})
    )


    class Meta:
        model = PatientsInfo
        fields = '__all__'

from django.contrib import admin
from .models import PatientSymptoms, DiseaseInfo, Insurance, PatientsInfo
from .forms import PatientsInfoForm

@admin.register(PatientSymptoms)
class PatientSymptomsAdmin(admin.ModelAdmin):
    list_display = ('name',)
    search_fields = ('name',)

@admin.register(DiseaseInfo)
class DiseaseInfoAdmin(admin.ModelAdmin):
    list_display = ('name',)
    search_fields = ('name',)

@admin.register(Insurance)
class InsuranceAdmin(admin.ModelAdmin):
    list_display = ('name',)
    search_fields = ('name',)

@admin.register(PatientsInfo)
class PatientsInfoAdmin(admin.ModelAdmin):
    form = PatientsInfoForm
    change_form_template = 'admin/app_patients/PatientsInfo/change_form.html'
    list_display = ('sick', 'insurance_type', 'underlying_disease', 'drug_sensitivity')
    search_fields = ('sick__first_name', 'sick__last_name',)
    fields = (
        'sick', 'insurance_type', 'underlying_disease', 'drug_sensitivity',
    )



    def get_extra_context(self, request):
        return {
            'university_list': list(Insurance.objects.values_list('name', 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)



{% extends "admin/change_form.html" %}

{% block content %}
    {{ block.super }}
    <datalist id="university-list">
        {% for name in insurance_type_list %}
            <option value="{{ name }}">{{ name }}</option>
        {% endfor %}
    </datalist>

{% endblock %}