import datetime
import hashlib
from io import BytesIO

import openpyxl
import requests
from django.contrib.auth.models import Group, User
from django.db.models import Q
from django.views.decorators.csrf import csrf_exempt
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
from rest_framework.response import Response

from LiveStock.models import LiveStock, Rancher, Cooperative

#todo:فعلا چون دامدار تکراری داریم نمیشه ثبت کر باید از طریف آدرس بریم
from authentication.models import SystemUserProfile, Province, City, SystemAddress
from authentication.register import ARTA_REGISTER
from panel.admin import PROJECT_API_KEY
from panel.convert_date import convert_to_shamsi


def add_rancher_to_live_stock(request):
    livestock=LiveStock.objects.filter(trash=False)
    for l in livestock:
        rancher=Rancher.objects.filter(trash=False,herd_code=l.herd_code).first()
        l.rancher=rancher
        l.save()


@api_view(["POST"])
@permission_classes([AllowAny])
@csrf_exempt
def create_live_stock_and_rancher_from_excel(request):
    file = request.FILES['file'].read()
    read = openpyxl.load_workbook(BytesIO(file), data_only=True)
    sheet = read.active
    group = Group.objects.get(name='Rancher')
    password = '123456'
    result_list=[]
    yesterday= datetime.datetime.now().date() - datetime.timedelta(days=1)
    birth_day=convert_to_shamsi(day=yesterday.day,
                                         month=yesterday.month,
                                         year=yesterday.year).replace('-','/')
    for i, row in enumerate(sheet.iter_rows(values_only=True)):
        if i <= 1:
            continue
        first_name = row[1]
        last_name = row[2]
        rancher_name = row[3]
        type_rancher = row[4]
        herd_code = row[5]
        epidemiological_code = row[6]
        postal_code = row[7]
        type_live_stock = row[8]
        gender = row[9]
        national_id = row[10]
        mobile = row[11]
        city = row[12]
        range_live_stock = row[13]
        if not herd_code:
            herd_code = '0000' + str(national_id)
        mobile = str(mobile)

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

        try:
            city_id = City.objects.filter(trash=False, name=city).first()
            province = Province.objects.filter(trash=False,key=city_id.province.key).first()

            if not Rancher.objects.filter(Q(herd_code=herd_code) | Q(user__mobile=mobile) | Q(mobile=mobile)
                    ,trash=False).exists():
                if not SystemUserProfile.objects.filter(trash=False, mobile=mobile).exists():
                    hashed_password = hashlib.sha256(str(password).encode()).hexdigest()
                    data = {
                        "username": mobile,
                        "first_name": first_name,
                        "last_name": last_name,
                        "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:
                        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


                        system_profile = SystemUserProfile(
                            mobile=mobile,
                            first_name=first_name,
                            last_name=last_name,
                            fullname=first_name+' ' + last_name,
                            user=user,
                            base_order=base_id,
                            password=password,
                            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.save()
                system_profile=SystemUserProfile.objects.filter(trash=False, mobile=mobile).first()
                cooperative = Cooperative.objects.filter(trash=False, address__city=city_id).first()
                rancher = Rancher(
                    user=system_profile,
                    cooperative=cooperative,
                    name=rancher_name,
                    mobile=mobile,
                    fullname=first_name + ' ' + last_name,
                    city=city,
                    herd_name=rancher_name,
                    postal_code=postal_code,
                    epidemiological_code=epidemiological_code,
                    herd_code=herd_code,
                    national_id=national_id,
                    type='rural' if type_rancher == 'روستایی' else 'industrial'


                )
                rancher.save()
            rancher = Rancher.objects.filter(Q(herd_code=herd_code) | Q(user__mobile=mobile) | Q(mobile=mobile)
                                   ,trash=False).first()
            if rancher:
                live_stock_count = LiveStock.objects.filter(trash=False, herd_code=rancher.herd_code,
                                                            type=type_live_stock)\
                    .count()
                if live_stock_count > int(range_live_stock):
                    new_range = live_stock_count - range_live_stock
                    for _i in range(new_range):
                        live_stock = LiveStock.objects.filter(
                            herd_code=rancher.herd_code,
                            type=type_live_stock,
                            trash=False
                        ).first()
                        live_stock.trash = True
                        live_stock.save()
                elif live_stock_count < int(range_live_stock):
                    new_range = range_live_stock - live_stock_count
                    for _i in range(new_range):
                        live_stock = LiveStock(
                            herd_code=rancher.herd_code,
                            type=type_live_stock,
                            birth_day=birth_day,
                            birth_day_gh=yesterday,
                            gender=gender,

                        )
                        live_stock.save()
        except:
            result_list.append(rancher_name)

    return Response(result_list)
