from rest_framework import serializers
from smartfarming.models.ascend import MongoBase, MongoLandInfo, MongoPlantInfo,MongoAreaJob, CountryModel, PlanWeekend, LandPlanInfo
from smartfarming.models.user import DeviceUser
import os 
import json 
from smartfarming.serializers.pests_serializers import PestBankSerializers
from smartfarming.models.pests_bank import MongoPestBank


class BaseSerializers(serializers.ModelSerializer):

    base_area = serializers.SerializerMethodField()
    base_lng_lat = serializers.SerializerMethodField()

    def base_info(self):
        BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
        try:
            with open(os.path.join(BASE_DIR, "base.json"), 'r', encoding="utf-8") as f:
                base = json.load(f)
            features = base.get("features")
            base_size = 0
            base_lng_lat = []
            for f in features:
                attributes = f.get("attributes", {})
                base_size += float(attributes.get("亩"))
                base_lng_lat.append(f.get("geometry", {}).get("rings", [])[0])
            return base_size, base_lng_lat
        except Exception as e:
            print(e)
            return 0, []
        
    def get_base_area(self, obj):
        base_size, _ = self.base_info()
        return str("{:.2f}".format(base_size))

    def get_base_lng_lat(self, obj):
        _, base_lng_lat = self.base_info()
        return base_lng_lat

    class Meta:
        model = MongoBase
        fields = [
            "base_name",
            "base_charge",
            "base_phone",
            "base_img",
            "base_area",
            "base_lng_lat"
        ]

class LandPlanInfoSerializers(serializers.ModelSerializer):

    class Meta:
        model = LandPlanInfo
        fields = "__all__"


class MongoLandInfoSerializers(serializers.ModelSerializer):

    # 地块列表
    plan = serializers.SerializerMethodField()

    def get_plan(self, obj):
        land_id = obj.id
        queryset = LandPlanInfo.objects.filter(land_id=land_id).order_by("-addtime").first()
        status = queryset.status
        plan_id = queryset.plan_id
        plan_obj = MongoPlantInfo.objects.filter(id=plan_id)
        if plan_obj:
            plan_obj = plan_obj.first()
            plan_name = plan_obj.plantname
            pickcode = plan_obj.pickcode
        else:
            plan_id = ""
            plan_name = ""
            pickcode = ""
        if queryset:
            return {"pl_id": queryset.id, "plan_id": plan_id, "plan_name": plan_name,"pickcode": pickcode, "status": status}
        else:
            return {}


    class Meta:
        model = MongoLandInfo
        fields = [
            "id",
            "farm",
            "landname",
            "landaddr",
            "landarea",
            "user",
            "tel",
            "is_delete",
            "uptime",
            "plan",
        ]


class CkPlanWeekendSerializers(serializers.ModelSerializer):
    p_obj = serializers.SerializerMethodField()

    def get_p_obj(self, obj):
        pests = [int(i) for i in obj.pest.split(",")]
        p_query = MongoPestBank.objects.filter(id__in=pests)
        p_serializers = PestBankSerializers(p_query, many=True)

        pick = [int(i) for i in obj.pick.split(",")]
        pk_query = MongoPestBank.objects.filter(id__in=pick)
        pk_serializers = PestBankSerializers(pk_query, many=True)
        return {"pest": p_serializers.data, "pick": pk_serializers.data}

    class Meta:
        model = PlanWeekend
        fields = [
            "id",
            "plan_id",
            "name",
            "start_time",
            "end_time",
            "pest",
            "pick",
            "mark",
            "is_delete",
            "p_obj"
        ]


class MongoPlanWeekendSerializers(serializers.ModelSerializer):
    cycle_list = serializers.SerializerMethodField()

    def get_cycle_list(self, obj):
        query = PlanWeekend.objects.filter(plan_id=obj.id, is_delete=1)
        serializer = CkPlanWeekendSerializers(query,many=True)
        return serializer.data
    
    class Meta:
        model = MongoPlantInfo
        fields = [
            "id",
            "batch",
            "plantname",
            "pickcode",
            "planttype",
            "uptime",
            "cycle_list"
        ]


class MongoPlantInfoSerializers(serializers.ModelSerializer):

    class Meta:
        model = MongoPlantInfo
        fields = [
            "id",
            "batch",
            "plantname",
            "pickcode",
            "planttype",
            "uptime"
        ]



class MongoAreaJobSerializers(serializers.ModelSerializer):

    class Meta:
        model = MongoAreaJob
        fields = "__all__"

    
class CountryModelSerializers(serializers.ModelSerializer):

    class Meta:
        model = CountryModel
        fields = "__all__"


class PlanWeekendSerializers(serializers.ModelSerializer):

    class Meta:
        model = PlanWeekend
        fields = "__all__"


class LandPlanInfoSerializers(serializers.ModelSerializer):

    plan = serializers.SerializerMethodField()

    def get_plan(self, obj):
        plan_id = obj.plan_id
        if plan_id:
            plan = MongoPlantInfo.objects.filter(id=obj.plan_id)
            if plan:
                return plan.first().plantname
            else:
                return ""
        else:
            return ""

    class Meta:
        model = LandPlanInfo
        fields = [
            "id",
            "land_id",
            "plan_id",
            "recovery_kg",
            "recovery_time",
            "plan_time",
            "addtime",
            "status",
            "plan"
        ]