<script>
import {mapActions, mapGetters} from 'vuex'
import { FwbSpinner } from 'flowbite-vue'
import Input from '@atoms/Input.vue'
import DoubleSwitch from '@atoms/DoubleSwitch.vue'
import Textarea from '@atoms/Textarea.vue'

export default {
  name: 'RouterRow',
  components: {Input, Textarea, DoubleSwitch, FwbSpinner},
  props: {
    id: {
      default: -1,
      type: Number
    },
    isCbOn: {
      default: false,
      type: Boolean
    },
    isOnline: {
      default: false,
      type: Boolean
    },
    path: {
      default: "",
      type: String
    },
    role: {
      default: null,
      type: Number
    },
    description: {
      default: "",
      type: String
    },
    errorPercent: {
      default: 0,
      type: Number
    },
    intervalDuration: {
      default: 0,
      type: Number
    },
    minRequests: {
      default: 0,
      type: Number
    },
    openStateTimeout: {
      default: 0,
      type: Number
    },
    requestLimit: {
      default: 0,
      type: Number
    },
    deepness: {
      default: 0,
      type: Number
    },
    order: {
      default: 0,
      type: Number
    },
  },
  data() {
    return {
      timer: null,
      state: "active",
      textAreaRows: 1,
      isRemoving: false,
    }
  },
  computed: {
    ...mapGetters('proxy', ["selectedSite", "routes", 'routeOptions', 'newRoute']),
  },
  methods: {
    ...mapActions('proxy', ["updateRouteRow", "removeRoute", "breateAddingRoute"]),
    toggle() {
      this.open = !this.open
      this.onToggle({isOpen: this.open})
    },
    setValue(key, value) {
      this.updateRouteRow({
        id: this.id,
        [key]: value
      })
    },
    setInputValue(params) {
      const value = params.isNumber ? this.parseNumber(params.value) : params.value
      this.updateRouteRow({
        id: this.id,
        [params.key]: value
      })
    },
    parseNumber (value) {
      if (isNaN(parseFloat(value)) || !value && value !== 0) return 0
      return parseFloat(value)
    },
    removeCurrentRoute() {
      this.removeRoute({id: this.id})
    },
    expandTextArea() {
      this.textAreaRows = 8
    },
    decreaseTextArea() {
      this.textAreaRows = 1
    }
  },
}
</script>

<template>
  <div class="w-full flex flex-row gap-2 mb-2 items-end">
    <div class="w-fit">
      <DoubleSwitch
        name="isCbOn"
        firstColor="#8b5cf6"
        secondColor="#2563eb"
        firstTitle="Без защиты"
        secondTitle="Защита"
        :isCheck="isCbOn"
        position="col"
        labelClass="pb-2"
        switchClass="mt-2.5"
        @switched="(v) => setValue('is_cb_on', v)"
      />
    </div>
    <div class="w-fit">
      <DoubleSwitch
        name="isOnline"
        firstColor="#8b5cf6"
        secondColor="#2563eb"
        firstTitle="Офлайн"
        secondTitle="Онлайн"
        :isCheck="isOnline"
        position="col"
        labelClass="pb-2"
        switchClass="mt-2.5"
        @switched="(v) => setValue('is_online', v)"
      />
    </div>
    <div class="w-full">
      <div class="mr-2 mb-1 min-w-[80px] text-xs">
        Путь
      </div>
      <Input
        name="path"
        :value="path"
        inputClass="!w-[100%] py-1.5"
        placeholder="Указать путь"
        :onChange="setInputValue"
      />
    </div>
    <div class="w-fit min-w-[70px]">
      <div class="mr-2 mb-1 text-xs">
        Роль
      </div>
      <select 
        :value="role"
        class="w-full rounded-lg border-gray-300 py-1.5 px-2"
        @change="(e) => setValue('role', parseFloat(e.target.value))"
      >
        <option
          v-for="(el, idx) in routeOptions" 
          :key="{idx}"
          :value="el.value"
        >
          {{ el.name }}
        </option>
      </select>
    </div>
    <div class="w-full translate-y-1.5">
      <div class="mr-2 mb-1 max-w-[80px] text-xs">
        Описание
      </div>
      <Textarea
        name="description"
        :value="description"
        textareaClass="py-2 resize-none "
        placeholder="Описание..."
        :rows="textAreaRows"
        :focus="expandTextArea"
        :blur="decreaseTextArea"
        :onChange="setInputValue"
      />
    </div>
    <div class="w-fit min-w-[80px]">
      <div class="mr-2 mb-1 text-xs">
        Ошибка, %
      </div>
      <Input
        name="cb_error_threshold_percentage"
        :value="`${errorPercent}`"
        inputClass="!w-[100%] py-1.5"
        placeholder="Процент ошибки"
        :onChange="(v) => setInputValue({...v, isNumber: true})"
      />
    </div>
    <div class="w-fit min-w-[80px]">
      <div class="mr-2 mb-1 text-xs">
        Интервал
      </div>
      <Input
        name="cb_interval_duration"
        :value="`${intervalDuration}`"
        inputClass="!w-[100%] py-1.5"
        placeholder="Интервал"
        :onChange="(v) => setInputValue({...v, isNumber: true})"
      />
    </div>
    <div class="w-fit min-w-[80px]">
      <div class="mr-2 mb-1 text-xs">
        Кол-во запросов
      </div>
      <Input
        name="cb_min_requests"
        :value="`${minRequests}`"
        inputClass="!w-[100%] py-1.5"
        placeholder="Кол-во запросов"
        :onChange="(v) => setInputValue({...v, isNumber: true})"
      />
    </div>
    <div class="w-fit min-w-[80px]">
      <div class="mr-2 mb-1 text-xs">
        Тайм-аут состояния
      </div>
      <Input
        name="cb_open_state_timeout"
        :value="`${openStateTimeout}`"
        inputClass="!w-[100%] py-1.5"
        placeholder="Тайм-аут состояния"
        :onChange="(v) => setInputValue({...v, isNumber: true})"
      />
    </div>
    <div class="w-fit min-w-[80px]">
      <div class="mr-2 mb-1 text-xs">
        Лимит запросов
      </div>
      <Input
        name="cb_request_limit"
        :value="`${requestLimit}`"
        inputClass="!w-[100%] py-1.5"
        placeholder="Лимит запросов"
        :onChange="(v) => setInputValue({...v, isNumber: true})"
      />
    </div>
    <div class="w-fit min-w-[80px]">
      <div class="mr-2 mb-1 text-xs">
        Глубина запросов
      </div>
      <Input
        name="deepness"
        :value="`${deepness}`"
        inputClass="!w-[100%] py-1.5"
        placeholder="Глубина запросов"
        :onChange="(v) => setInputValue({...v, isNumber: true})"
      />
    </div>
    <div class="w-fit min-w-[80px]">
      <div class="mr-2 mb-1 text-xs">
        Порядок сортировки
      </div>
      <Input
        name="order"
        :value="`${order}`"
        inputClass="!w-[100%] py-1.5"
        placeholder="Порядок сортировки"
        :onChange="(v) => setInputValue({...v, isNumber: true})"
      />
    </div>
    <div class="flex items-center col-span-1">
      <div
        v-if="!isRemoving"
        class=" transition-all h-9 w-9 mr-4 rounded-md bg-red-700 hover:bg-red-600 cursor-pointer text-white flex items-center justify-center"
        @click="() => isRemoving = true"
      >
        <i class="ri-delete-bin-line" />
      </div>
      <div
        v-if="isRemoving"
        class=" transition-all h-9 w-24 mr-4 rounded-md bg-gray-700 hover:bg-gray-600 cursor-pointer text-white flex items-center justify-center"
        @click="() => isRemoving = false"
      >
        Отменить
      </div>
      <div
        v-if="isRemoving"
        class=" transition-all h-9 w-24 mr-4 rounded-md bg-red-700 hover:bg-red-600 cursor-pointer text-white flex items-center justify-center"
        @click="removeCurrentRoute({id})"
      >
        Удалить
      </div>
      <div
        v-if="timer"
        class="flex items-center opacity-75"
      >
        <span class="mr-2 font-w-700 text-slate-900">Сохранение</span>
        <fwb-spinner
          v-if="timer"
          size="6"
        />
      </div>
      <div
        v-if="state === 'success'"
        class="flex items-center "
      >
        <span class="mr-2 text-slate-700 font-w-700">Сохранено</span>
        <i
          class="ri-check-line text-green-600"
        />
      </div>
    </div>
  </div>
</template>
