<template>
  <global-form
    :reset-on-success="false"
    :format-data="formatData"
    :endpoint="endpoint"
    :use-submit-slot="canAdmin"
    form-id="restaurants-modal-form"
    http-verb="put"
  >
    <template #fields>
      <input-selectbox
        v-if="availablesStatus.length"
        :label="$_tr('status')"
        :input-data="availablesStatus"
        :default-value="status"
        :extra-options-callback="({ color }) => ({ color })"
        :rules="['required']"
        :use-asterisk="false"
        :readonly="!canAdmin"
        form-id="restaurants-modal-form"
        model-name="dishes_orders_status"
        objectValueKey="uuid"
        objectLabelKey="title"
      >
        <template #default="{ node }">
          <div
            :style="{
              color: getCheckedData(node, ['raw', 'extraOptions', 'color'])
            }"
          >
            {{ node.raw.label }}
          </div>
        </template>
      </input-selectbox>

      <input-textarea
        form-id="restaurants-modal-form"
        model-name="comment"
        :label="$_tr('comment')"
        :default-value="comment"
        :readonly="!canAdmin"
      />

      <input-hidden
        form-id="restaurants-modal-form"
        model-name="author"
        :default-value="author"
        :rules="['required']"
      />
    </template>
  </global-form>
</template>

<script>
import { http } from '@inside-library/helpers/Http'

export default {
  name: 'modal-form',
  $_i18nRootPath: 'customs.RESTAURANTS.MODALS.ORDER.FORM',
  props: {
    status: {
      type: String,
      required: true
    },
    uuid: {
      type: String,
      required: true
    },
    comment: {
      type: String
    },
    author: {
      type: String,
      required: true
    },
    listingId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      availablesStatus: [],
      canAdmin: false
    }
  },
  computed: {
    endpoint() {
      return `content/dishes_orders/${this.uuid}`
    }
  },
  created() {
    this.fetchStatus()
    this.checkIfCanAdmin()
  },
  methods: {
    formatData(data) {
      if (!Array.isArray(data.dishes_orders_status)) {
        data.dishes_orders_status = [data.dishes_orders_status]
      }

      return {
        ...data,
        type: 'node',
        bundle: 'dishes_orders'
      }
    },
    async checkIfCanAdmin() {
      try {
        const { success = false } = await http.get(
          'catering/credits/permissions',
          {
            uuid: this.getUserInfos.uuid
          }
        )
        this.canAdmin = success
      } catch (err) {
        throw new Error(err)
      }
    },
    async fetchStatus() {
      try {
        const { data } = await http.get('content/dishes_orders_status', {
          fields: ['uuid', 'title', 'color'],
          filters: { 'status:eq': 1 }
        })

        this.availablesStatus = data
      } catch (err) {
        throw new Error(err)
      }
    }
  }
}
</script>
