import json
import time

from django.db.models import Q
from rest_framework.response import Response
from rest_framework import status
from common.accounts.models import Users
from common.utils.return_structure import general_message, error_message
from common.utils.service_code import API_ERROR
from common.utils.views import ManagerApiView, AllowAnyApiView

from console.APP.models import Drafts, VersionUpdate, AppVersion

from console.APP.serializers import DraftsInfoSerialzier, \
    VersionUpdateSerializer, UserLocationCreateSerializer, \
    DraftsCreateSerialzier, OrderSettingSerialzier

from common.utils.redis_api import redis_api_base

# from common.celery_task.tasks import create_plan

from console.inspection.services import create_inspection_plan_and_task

# from console.APP.services import create_station_building,
# relation_station_and_team
#
# from console.inspection.services import create_inspection_task_by_team
#
# from console.APP.services import assign_inspection_task

# from console.APP.services import create_permission

from console.APP.services import create_version_message

from console.APP.services import move_inspection_data

from console.APP.services import create_equipment

from console.electricity_bill.services import create_ele_price

from common.celery_task.tasks import create_day_inspection_task

from console.APP.services import sync_transformer_capacity

from console.task.services import task_create_calling

from common.celery_task.tasks import create_plan

from console.APP.services import export_ele_billing_data

from common.third_party_api.surveillance.ys7 import YSConfiguration

from console.APP.services import add_outline_data

# from console.APP.services import update_ele_bill_data

from console.APP.services import create_perms

from console.APP.services import create_perm_by_role

from console.APP.services import export_ele_billing

from console.APP.services import change_inspection_task

from common.third_party_api.danbing.openapi import ZYRHApi

from console.APP.services import change_inspection_task_2

from console.APP.services import change_task

from console.APP.services import power_station_add_customer_data, inport_changsha_equipment, test

from console.APP.services import send_monitor_msg

from console.APP.services import get_fengxian_power

from console.APP.services import get_defect

from console.APP.services import change_jinshan_task

from common.accounts.models import UserEnterprise
from console.team.models import Team

from common.celery_task.tasks import del_timeout_user_location, save_user_location


class OrderSettingView(ManagerApiView):
    queryset = Users.objects.filter()
    serializer_class = OrderSettingSerialzier

    def put(self, request, *args, **kwargs):
        user = Users.objects.filter(account=request.user).first()
        serializer = OrderSettingSerialzier(user, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(general_message(msg_show="设置成功"))
        return Response(
            error_message(msg=serializer.errors,
                          msg_show="设置失败",
                          code=API_ERROR))


class DraftsCreateView(ManagerApiView):
    queryset = Drafts.objects.filter()
    serializer_class = DraftsCreateSerialzier

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(general_message(msg_show="保存成功"))
        return Response(
            error_message(msg=serializer.errors,
                          msg_show="保存失败",
                          code=API_ERROR))


class DraftsView(ManagerApiView):
    serializer_class = DraftsInfoSerialzier
    queryset = Drafts.objects.filter()

    def get(self, request, *args, **kwargs):
        user = Users.objects.filter(account=request.user).first()
        drafts = self.get_queryset().filter(user=user)
        serializer = self.get_serializer(drafts, many=True)
        return Response(general_message(list=serializer.data))


class DraftsInfoView(ManagerApiView):
    serializer_class = DraftsInfoSerialzier
    queryset = Drafts.objects.filter()

    def get(self, request, *args, **kwargs):
        return self.get_info(request, *args, **kwargs)


class UserLocationView(ManagerApiView):
    serializer_class = UserLocationCreateSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data,
                                         context={"request": request})
        if serializer.is_valid():
            # serializer.save()
            redis = redis_api_base.connect()
            redis = redis.redis
            user = Users.objects.filter(account=request.user,
                                        deleted=False).first()
            enterprise_ids = UserEnterprise.objects.filter(user=user).values_list("enterprise_id__id", flat=True)
            team = Team.objects.filter(Q(team_headman=user) | Q(
                member=user
            )).first()
            redis.hset('user_location',
                       user.id,
                       value=json.dumps({
                           "time":
                               time.time(),
                           "location":
                               request.data.get("location"),
                           "enterprise": list(enterprise_ids),
                           "team_name": team.name if team else None,
                           "team_type": team.type if team else None,
                           "nickname": user.nickname,
                           "phone": user.phone
                       }, ensure_ascii=False))
            redis.hset('user_histoory_location',
                       user.id,
                       value=json.dumps({
                           "time":
                               time.time(),
                           "location":
                               request.data.get("location"),
                           "enterprise": list(enterprise_ids),
                           "team_name": team.name if team else None,
                           "team_type": team.type if team else None,
                           "nickname": user.nickname,
                           "phone": user.phone
                       }, ensure_ascii=False))
            return Response(general_message("添加成功"))


class TestApi(ManagerApiView):
    def get(self, request, *args, **kwargs):
        # make_inspection_data_from_oa(request.GET.get("date"))
        # create_inspection_plan_and_task([37889,37333,6128,34806,78940])
        # create_inspection_plan_and_task([15963])
        # create_inspection_task_by_team(698)
        # create_day_inspection_task()
        # create_plan()
        # assign_inspection_task()
        # create_permission(90014)
        # create_ele_price()
        # move_inspection_data()
        # create_equipment()
        # sync_transformer_capacity()
        # task_create_calling()
        # export_ele_billing_data()
        # config = YSConfiguration()
        # data = config.get_vedio(deviceSerial="D37852477")
        # update_ele_bill_data()
        # export_ele_billing_data()
        # create_perms(request.GET.get("role_id"))
        # create_perm_by_role(request.GET.get("role_id"),
        #                     request.GET.get("perm"))
        # export_ele_billing_data()
        export_ele_billing()
        # change_inspection_task()
        # change_jinshan_task()
        # change_inspection_task()
        # change_inspection_task_2()
        # api = ZYRHApi()
        # data = api.get_device_tree()
        # change_task()
        # export_ele_billing()
        # power_station_add_customer_data()
        # inport_changsha_equipment()
        # test()
        # send_monitor_msg()
        # data = get_fengxian_power()
        # get_defect()
        # del_timeout_user_location()
        # save_user_location()
        return Response(general_message("测试成功"))


class CreateNormalInspectionTask(ManagerApiView):
    def get(self, request, *args, **kwargs):
        create_inspection_plan_and_task(request.GET.get("leader"),
                                        request.GET.get("month"))
        return Response(general_message("创建成功！"))


class VersionUpdateStatus(ManagerApiView):
    queryset = VersionUpdate.objects.filter()
    serializer_class = VersionUpdateSerializer

    def get(self, request, *args, **kwargs):
        user = Users.objects.filter(account=request.user).first()
        queryset = self.get_queryset().filter(user=user).first()
        serializer = self.get_serializer(queryset)
        return Response(general_message(bean=serializer.data))


class UpdateVersion(ManagerApiView):
    queryset = VersionUpdate.objects.filter()

    def put(self, request, *args, **kwargs):
        user = Users.objects.filter(account=request.user).first()
        queryset = self.get_queryset().filter(user=user).first()
        if queryset:
            queryset.is_updated = True
            queryset.save()
        return Response(general_message("更新完成"))


class CreateVersionMessage(ManagerApiView):
    def post(self, request, *args, **kwargs):
        version = request.data.get("version")
        package_url = request.data.get("package_url")
        create_version_message(version=version, package_url=package_url)
        return Response(general_message("版本更新内容添加成功"))


class AppVersionRView(AllowAnyApiView):
    def get(self, request, *args, **kwargs):
        dt = AppVersion.objects.filter(deleted=False).order_by("created_time").first()
        data = general_message(bean=dt.to_dict() if dt else None)
        return Response(data, status=status.HTTP_200_OK)


class CreateSettled(AllowAnyApiView):
    def post(self, request, *args, **kwargs):
        print(request.data)
        return Response(general_message("测试"))
