import datetime
import hashlib

import requests
from django.contrib.auth.models import User, Group
from django.db.models import Count
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from openpyxl import Workbook
from openpyxl.styles import Alignment
from rest_framework import status
import openpyxl
from io import BytesIO
from rest_framework.response import Response
from rest_framework.decorators import permission_classes, api_view
from rest_framework.permissions import AllowAny

from LiveStock.Rancher.helpers import update_one_rancher
from LiveStock.helpers import convert_to_miladi
from LiveStock.models import Rancher, Cooperative, Union, Contractor, LiveStockRolseProduct, LiveStockProvinceJahad, \
    LiveStock
from authentication.models import SystemUserProfile, Province, SystemAddress, City
from authentication.register import ARTA_REGISTER
from panel.admin import PROJECT_API_KEY
from panel.helper_excel import create_header, excel_description, create_header_freez, create_value


@api_view(["POST"])
@permission_classes([AllowAny])
@csrf_exempt
def get_rancher_excel(request):
    file = request.FILES['file'].read()
    wb_obj = openpyxl.load_workbook(filename=BytesIO(file))
    sheet = wb_obj.active
    group = Group.objects.get(name__exact="Rancher")
    system_user = SystemUserProfile.objects.filter(trash=False)
    for i, row in enumerate(sheet.iter_rows(values_only=True)):
        if i < 1:
            continue
        herd_code = row[0]
        epidemiological_code = row[1]
        postal_code = row[2]
        unit_id = row[3]
        herd_name = row[4]
        national_id = row[5]
        name = row[6]
        mobile = row[7]
        city = row[9]
        lng = row[10]
        lot = row[11]
        registering_user = row[12]
        mobile = str(mobile)

        if len(mobile) < 10:
            continue
        if len(mobile) == 10:
            mobile = '0' + mobile

        full_name = name.split(':')
        if not system_user.filter(mobile=mobile).exists():
            if not User.objects.filter(username=mobile).exists():
                hashed_password = hashlib.sha256(str('1404').encode()).hexdigest()
                data = {
                    "username": mobile,
                    "first_name": full_name[0],
                    "last_name": full_name[1],
                    "password": hashed_password,
                    "national_code": national_id,
                    "role": "Rancher",
                    "api_key": PROJECT_API_KEY
                }
                req = requests.post(
                    url=ARTA_REGISTER,
                    data=data,
                    verify=False
                )

                if req.status_code == 200:
                    province = Province.objects.filter(trash=False).first()
                    user = User(username=mobile, first_name=full_name[0], last_name=full_name[1],
                                password=hashed_password)
                    user.save()
                    base_id = SystemUserProfile.objects.all()
                    if base_id.count() > 0:
                        base_id = int(base_id.last().base_order) + 1
                    else:
                        base_id = 1000
                    city_id = City.objects.filter(trash=False, id=city).first()

                    system_profile = SystemUserProfile(
                        mobile=mobile,
                        first_name=full_name[0],
                        last_name=full_name[1],
                        fullname=name,
                        user=user,
                        base_order=base_id,
                        password='1404',
                        birthday=datetime.datetime.now().date(),
                        city=city_id,
                        province=province
                    )
                    system_profile.save()
                    system_profile.role.add(group)
                    address = SystemAddress(
                        province=province,
                        city=city_id,
                        address=city,
                        postal_code=postal_code

                    )
                    address.save()
                    cooperative = Cooperative.objects.filter(trash=False, address__city=city_id).first()
                    if not Rancher.objects.filter(trash=False, herd_code=herd_code).exists():
                        rancher = Rancher(
                            user=system_profile,
                            address=address,
                            cooperative=cooperative,
                            name=name,
                            registering_user=registering_user,
                            lng=lng,
                            lot=lot,
                            mobile=mobile,
                            fullname=name,
                            city=city,
                            herd_name=herd_name,
                            unit_id=unit_id,
                            postal_code=postal_code,
                            epidemiological_code=epidemiological_code,
                            herd_code=herd_code,
                            national_id=national_id,

                        )
                        rancher.save()

    return Response({"result": "ok"}, status=status.HTTP_200_OK)


@api_view(["POST"])
@permission_classes([AllowAny])
@csrf_exempt
def get_union_excel(request):
    file = request.FILES['file'].read()
    wb_obj = openpyxl.load_workbook(filename=BytesIO(file))
    sheet = wb_obj.active
    group = Group.objects.get(name__exact="Union")

    for i, row in enumerate(sheet.iter_rows(values_only=True)):
        if i < 3:
            continue
        type = row[4]
        address = row[5]

        name = row[2]
        mobile = row[6]

        mobile = str(mobile)

        if len(mobile) < 10:
            continue
        if len(mobile) == 10:
            mobile = '0' + mobile
        print(mobile)
        full_name = name.split(' ')
        if not SystemUserProfile.objects.filter(trash=False, mobile=mobile).exists():
            hashed_password = hashlib.sha256(str('1404').encode()).hexdigest()
            data = {
                "username": mobile,
                "first_name": full_name[0],
                "last_name": full_name[1],
                "password": hashed_password,
                "national_code": '0',
                "role": "Union",
                "api_key": PROJECT_API_KEY
            }
            req = requests.post(
                url=ARTA_REGISTER,
                data=data,
                verify=False
            )

            if req.status_code == 200:
                province = Province.objects.filter(trash=False).first()
                user = User(username=mobile, first_name=full_name[0], last_name=full_name[1], password=hashed_password)
                user.save()
                base_id = SystemUserProfile.objects.all()
                if base_id.count() > 0:
                    base_id = int(base_id.last().base_order) + 1
                else:
                    base_id = 1000
                city_id = City.objects.filter(trash=False, name='همدان').first()

                system_profile = SystemUserProfile(
                    mobile=mobile,
                    first_name=full_name[0],
                    last_name=full_name[1],
                    fullname=name,
                    user=user,
                    base_order=base_id,
                    password='1404',
                    birthday=datetime.datetime.now().date(),
                    city=city_id,
                    province=province
                )
                system_profile.save()
                system_profile.role.add(group)
                address = SystemAddress(
                    province=province,
                    city=city_id,
                    address=address,

                )
                address.save()
                if not Union.objects.filter(trash=False, user__mobile=mobile).exists():
                    union = Union(
                        user=system_profile,
                        address=address,
                        name=name,
                        mobile=mobile,
                        type=type,

                    )
                    union.save()
                # role_product=LiveStockRolseProduct(union=union)
                # role_product.save()

    return Response({"result": "ok"}, status=status.HTTP_200_OK)


@api_view(["POST"])
@permission_classes([AllowAny])
@csrf_exempt
def get_cooperative_excel(request):
    file = request.FILES['file'].read()
    wb_obj = openpyxl.load_workbook(filename=BytesIO(file))
    sheet = wb_obj.active
    group = Group.objects.get(name__exact="Cooperative")

    for i, row in enumerate(sheet.iter_rows(values_only=True)):
        if i < 3:
            continue
        city = row[3]
        address = row[5]

        name = row[4]
        mobile = row[6]
        national_id = row[7]

        mobile = str(mobile)

        if len(mobile) < 10:
            continue
        if len(mobile) == 10:
            mobile = '0' + mobile
        print(mobile)
        full_name = name.split(' ')
        if not SystemUserProfile.objects.filter(trash=False, mobile=mobile).exists():
            hashed_password = hashlib.sha256(str('1404').encode()).hexdigest()
            data = {
                "username": mobile,
                "first_name": full_name[0],
                "last_name": full_name[1],
                "password": hashed_password,
                "national_code": national_id,
                "role": "Cooperative",
                "api_key": PROJECT_API_KEY
            }
            req = requests.post(
                url=ARTA_REGISTER,
                data=data,
                verify=False
            )

            if req.status_code == 200:
                province = Province.objects.filter(trash=False).first()
                user = User(username=mobile, first_name=full_name[0], last_name=full_name[1:], password=hashed_password)
                user.save()
                base_id = SystemUserProfile.objects.all()
                if base_id.count() > 0:
                    base_id = int(base_id.last().base_order) + 1
                else:
                    base_id = 1000
                city_id = City.objects.filter(trash=False, name__contains=city).first()

                system_profile = SystemUserProfile(
                    mobile=mobile,
                    first_name=full_name[0],
                    last_name=full_name[1],
                    fullname=name,
                    user=user,
                    base_order=base_id,
                    password='1404',
                    birthday=datetime.datetime.now().date(),
                    city=city_id,
                    province=province
                )
                system_profile.save()
                system_profile.role.add(group)
                address = SystemAddress(
                    province=province,
                    city=city_id,
                    address=address,

                )
                address.save()
                if not Cooperative.objects.filter(trash=False, user__mobile=mobile).exists():
                    cooperative = Cooperative(
                        user=system_profile,
                        address=address,
                        name=name,
                        mobile=mobile,
                        national_id=national_id,

                    )
                    cooperative.save()
                # role_product=LiveStockRolseProduct(union=union)
                # role_product.save()

    return Response({"result": "ok"}, status=status.HTTP_200_OK)


def hgsahgsad(request):
    rancher = Cooperative.objects.all().order_by('id')
    for r in rancher:
        m=LiveStockRolseProduct(
           cooperative=r
        )
        m.save()
    return HttpResponse('ok')


import random


def generate_random_phone_number():
    prefix = "0908"
    used_numbers = set()

    while True:
        suffix = ''.join([str(random.randint(0, 9)) for _ in range(7)])
        full_number = prefix + suffix

        if not SystemUserProfile.objects.filter(mobile=full_number):
            used_numbers.add(full_number)
            return full_number


@api_view(["POST"])
@permission_classes([AllowAny])
@csrf_exempt
def get_contractor_excel(request):
    file = request.FILES['file'].read()
    wb_obj = openpyxl.load_workbook(filename=BytesIO(file))
    sheet = wb_obj.active
    group = Group.objects.get(name__exact="Cooperative")

    for i, row in enumerate(sheet.iter_rows(values_only=True)):
        if i < 1:
            continue
        contractor_code = row[0]
        first_name = row[1]
        last_name = row[2]
        full_name=first_name+ ' ' + last_name
        entity_code=row[3]
        city=row[4]
        national_id=row[5]
        postal_code=row[7]
        company_name=row[8]

        mobile = str(generate_random_phone_number())


        if not SystemUserProfile.objects.filter(trash=False, mobile=mobile).exists():
            hashed_password = hashlib.sha256(str('1404').encode()).hexdigest()
            data = {
                "username": mobile,
                "first_name": first_name,
                "last_name": last_name,
                "password": hashed_password,
                "national_code": national_id,
                "role": "Contractor",
                "api_key": PROJECT_API_KEY
            }
            req = requests.post(
                url=ARTA_REGISTER,
                data=data,
                verify=False
            )

            if req.status_code == 200:
                province = Province.objects.filter(trash=False).first()
                user = User(username=mobile, first_name=first_name, last_name=last_name, password=hashed_password)
                user.save()
                base_id = SystemUserProfile.objects.all()
                if base_id.count() > 0:
                    base_id = int(base_id.last().base_order) + 1
                else:
                    base_id = 1000
                city_id = City.objects.filter(trash=False, id=city).first()

                system_profile = SystemUserProfile(
                    mobile=mobile,
                    first_name=first_name,
                    last_name=last_name,
                    fullname=full_name,
                    user=user,
                    base_order=base_id,
                    password='1404',
                    birthday=datetime.datetime.now().date(),
                    city=city_id,
                    province=province
                )
                system_profile.save()
                system_profile.role.add(group)
                address = SystemAddress(
                    province=province,
                    city=city_id,
                    postal_code=postal_code,

                )
                address.save()
                if not Contractor.objects.filter(trash=False, user__mobile=mobile).exists():
                    contractor = Contractor(
                        user=system_profile,
                        address=address,
                        contractor_code=contractor_code,
                        fullname=full_name,
                        entity_code=entity_code,
                        national_id=national_id,
                        company_name=company_name

                    )
                    contractor.save()
                # role_product=LiveStockRolseProduct(union=union)
                # role_product.save()

    return Response({"result": "ok"}, status=status.HTTP_200_OK)


def kjdfjsd(request):
    live=LiveStock.objects.filter(birth_day_gh__isnull=True).count()
    return HttpResponse(live)

@api_view(["POST"])
@permission_classes([AllowAny])
@csrf_exempt
def get_live_stock_excel(request):
    file = request.FILES['file'].read()
    wb_obj = openpyxl.load_workbook(filename=BytesIO(file))
    sheet = wb_obj.active

    existing_codes = set(LiveStock.objects.filter(trash=False).values_list('national_id_livestock_code', flat=True))

    live_stocks_to_create = []
    l = 0

    for i, row in enumerate(sheet.iter_rows(values_only=True)):
        if i < 1:
            continue

        national_id_livestock_code = row[0]
        if national_id_livestock_code not in existing_codes:
            birth_day = row[3].split('/')
            birth_day_ghamari = convert_to_miladi(
                year=int(birth_day[0]),
                month=int(birth_day[1]),
                day=int(birth_day[2])
            )

            live_stock = LiveStock(
                national_id_livestock_code=row[0],
                herd_code=row[1],
                type=row[2],
                birth_day=row[3],
                birth_day_gh=birth_day_ghamari,
                gender=row[4],
                contractor_code=row[5],
                unique_identifier=row[6],
                agent=row[7],
                registering_user=row[8],
                registering_date=row[9],
            )
            live_stocks_to_create.append(live_stock)
            l += 1

    LiveStock.objects.bulk_create(live_stocks_to_create)

    return Response({"result": l}, status=status.HTTP_200_OK)


@api_view(["POST"])
@permission_classes([AllowAny])
@csrf_exempt
def get_cooepritive_or_rural_excel(request):
    file = request.FILES['file'].read()
    wb_obj = openpyxl.load_workbook(filename=BytesIO(file))
    sheet = wb_obj.active
    rancher=Rancher.objects.filter(trash=False).only('national_id','type')
    l=0
    for i, row in enumerate(sheet.iter_rows(values_only=True)):
        national_id= row[0]

        new_rancher=rancher.filter(national_id=national_id)
        if new_rancher:
            if len(new_rancher) >1:
                for r in new_rancher:
                    r.type='industrial'
                    r.save()
            else:
                n=new_rancher.first()
                n.type = 'industrial'
                n.save()
            l+=1

    return Response({"result": l}, status=status.HTTP_200_OK)


def rancher_repetitive_excel(request):


    duplicates = Rancher.objects.filter(trash=False).values('national_id').annotate(
        count=Count('national_id')
    ).filter(count__gt=1)
    # حالا رکوردهایی که national_id تکراری دارند را استخراج می‌کنیم
    duplicate_records = Rancher.objects.filter(
        national_id__in=[item['national_id'] for item in duplicates],
        trash=False
    )




    excel_options = [
        'ردیف',
        'نام دامدار',
        'شماره ملی',
        'کد گله',
        'تعداد دام سبک',
        'تعداد دام سنگین',


    ]


    output = BytesIO()
    workbook = Workbook()
    worksheet = workbook.active
    worksheet.sheet_view.rightToLeft = True
    worksheet.insert_rows(1)
    cell = worksheet.cell(row=1, column=1)
    cell.alignment = Alignment(horizontal='center', vertical='center')



    excel_description(worksheet, 'B1', f'انبار', color='red', row2='C1')

    create_header_freez(worksheet, excel_options, 1, 6, 7, height=22)


    l = 5
    m = 1
    if duplicate_records:
        for data in duplicate_records:

            while True:
                update_ranchers = update_one_rancher(data)
                if update_ranchers:
                    break
            list1 = [
                m,
                data.fullname,
                data.national_id,
                data.herd_code,
                data.light_livestock,
                data.heavy_livestock,


            ]
            m += 1
            l += 1
            create_value(worksheet, list1, l + 1, 1, border_style='thin')


    workbook.save(output)
    output.seek(0)

    response = HttpResponse(
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response[
        'Content-Disposition'] = f'attachment; filename="تکراری.xlsx"'.encode(
        'utf-8')
    response.write(output.getvalue())
    return response

def create_live_stovk(request):
    l=0
    for _i in range(60):
        live_stock=LiveStock(
            national_id_livestock_code=random.randint(10**9, 10**10 - 1),
            herd_code='000005307',
            type='اسب',
            birth_day='1402/12/27',
            birth_day_gh=datetime.datetime.now() - datetime.timedelta(days=360),
            gender='نر',
            unique_identifier='0000053070',
        )
        live_stock.save()
        l+=1
    return HttpResponse(l)