import requests
import json
from rest_framework.views import APIView
from rest_framework.response import Response
from smartfarming.models.device import MongoDevice
from smartfarming.models.weather import QXZdata_New, MongoQXZ_Conf
from smartfarming.utils import get_weather

from smartfarming.utils import get_center_lnglat


class WeatherAPIView(APIView):

    def post(self, request):
        # 调用天气
        try:
            ip = request.META['HTTP_X_FORWARDED_FOR']
        except Exception as e:
            ip = request.META['REMOTE_ADDR']
        # ip 转化为 省市县
        data = get_weather(ip)
        content = []
        for i in data:
            content.append(
                {
                    "week": i.get("week"),
                    "wea_img": i.get("wea_img"),
                    "wea_day_img": i.get("wea_day_img"),
                    "tem": i.get("tem"),
                    "tem1": i.get("tem1"),
                    "tem2": i.get("tem2")
                }
            )
        return Response({"code": 0, "msg": "success", "data": content})
    

class QxzListAPIView(APIView):

    def post(self, request):
        shang = MongoDevice.objects.filter(device_type_id=8).values_list("device_id", flat=True)
        return Response({"code": 0, "msg": "success", "data": shang})
    
class QxzShangAPIView(APIView):

    def post(self, request):
        # 墒情统计
        request_data = request.data 
        device_id = request_data.get("device_id")
        qx_conf = MongoQXZ_Conf.objects.filter(device_id=device_id).values().order_by("-uptime").first()
        qx_data = QXZdata_New.objects.filter(device_id=device_id).values().order_by("-uptime").first()
        result = {}
        for k, v in qx_conf.items():
            if k.startswith("e"):
                if qx_data.get(k):
                    v_tp = v.split("#")
                    result[v_tp[0]] = (qx_data.get(k)).split("#")[0] + v_tp[1]
        return Response({"code": 0, "msg": "success", "data": result})
