<script>
import { markRaw } from 'vue'

import DefaultModal from '@inside-library/components/modals/default/DefaultModal'
import AvatarUsernameUsers from '@inside-users/displays/AvatarUsernameUsers'
import ModalForm from './../sub-components/ModalForm'

import { groupBy } from '@inside-library/helpers/Utils'

export default {
  name: 'restaurants-order-modal',
  $_i18nRootPath: 'customs.RESTAURANTS.MODALS.ORDER',
  components: {
    ModalForm,
    AvatarUsernameUsers
  },
  extends: DefaultModal,
  data() {
    return {
      selection: {
        user: 'authors',
        date: 'date',
        menu: 'order',
        status: 'dishes_orders_status',
        comment: 'comment',
        uuid: 'uuid',
        author: 'authors.uuid',
        canAdmin: 'admin.permission.update'
      }
    }
  },
  methods: {
    scaffold(fields) {
      return {
        sections: [
          {
            fields: [
              {
                label: this.$_tr('day'),
                tag: 'date-ui',
                data: { date: fields.date }
              },
              {
                label: this.$_tr('reservationFor'),
                tag: markRaw(AvatarUsernameUsers),
                data: { user: fields.user }
              },
              ...this.buildMenu(fields.menu)
            ]
          },
          {
            fields: [
              {
                tag: markRaw(ModalForm),
                data: {
                  status: fields.status.uuid,
                  comment: fields.comment,
                  uuid: fields.uuid,
                  author: fields.author,
                  listingId: this.heritedOptions.listingId
                }
              }
            ]
          }
        ]
      }
    },
    buildMenu(menu) {
      const data = JSON.parse(menu)
      const parsedData = groupBy(data, 'category')

      return Object.entries(parsedData).map(([category, items]) => ({
        tag: 'ul',
        label: category,
        children: items.map(({ name, quantity }) => ({
          tag: 'li',
          value: `- ${name} ${quantity > 1 ? `x${quantity}` : ''}`.trim()
        }))
      }))
    }
  }
}
</script>

<style lang="scss">
.restaurants-order-modal {
  .modal__body__header {
    .modal__body__title {
      text-align: left;
    }
  }
}
</style>
