from common.utils.views import ManagerApiView

from rest_framework.response import Response

from common.utils.return_structure import general_message, error_message
from common.utils.service_code import THIRD_PARTY_API_ERROR, PARAMETER_ERROR

from console.circuit_diagram.services import circuit_file_upload, \
    get_circuit_file_url

from console.circuit_diagram.serializers import CircuitFileUploadSerializer

from console.powerstation.models import PowerStation


class UpdateCircuitFileView(ManagerApiView):
    serializer_class = CircuitFileUploadSerializer

    def post(self, request):
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            file = request.data.get("file")
            station_id = request.data.get("station_id")
            code = circuit_file_upload(file, station_id)
            if code == 0:
                return Response(general_message(msg_show="上传成功"))
            else:
                return Response(error_message(code=THIRD_PARTY_API_ERROR))
        return Response(
            error_message(code=PARAMETER_ERROR,
                          msg=serializer.errors,
                          msg_show="上传失败"))


class GetCircuitFileView(ManagerApiView):
    def get(self, request, *args, **kwargs):
        station_id = request.GET.get("station_id")
        power_station = PowerStation.objects.filter(deleted=False,
                                                    id=station_id).first()
        if not power_station:
            return Response(
                error_message(code=PARAMETER_ERROR,
                              msg_show="电站%s不存在" % station_id))
        if not power_station.file_id:
            return Response(general_message("电站还未上传一次线路图"))
        url = get_circuit_file_url(power_station.file_id)
        return Response(general_message(bean={"url": url}))
