<template>
  <DefaultField
    :field="currentField"
    :errors="errors"
    :show-help-text="showHelpText"
    :full-width-content="fullWidthContent"
  >
    <template #field>
      <div class="payout-product-card">
        <div class="flex">
            <div class="flex flex-wrap">
                <product-cart
                    v-for="product in currentField.products"
                    :product="product"
                    :editMode="false"
                ></product-cart>
            </div>
          </div>
        </div>
    </template>
  </DefaultField>
</template>

<script>
import { DependentFormField, HandlesValidationErrors } from 'laravel-nova'
import ProductCart from './product-cart'

export default {
    mixins: [DependentFormField, HandlesValidationErrors],

    props: ['index', 'resource', 'resourceName', 'resourceId', 'field'],

    components: {
        ProductCart,
    },

    data: () => ({
        values: []
    }),

    methods: {
        /*
        * Set the initial, internal value for the field.
        */
        setInitialValue() {
            this.value = this.currentField.value || []
        },

        onSyncedField() {
            if (this.currentField.products) {
                this.value = Array.from(this.currentField.products).map(orderItem => orderItem.id)

                this.emitFieldValueChange(this.field.attribute, this.value)
            }
        },
    },

    mounted() {
        Nova.$on('orderItemChanged', (item) => {
            if (! item.checked) {
                this.value = Array.from(this.value).filter(element => element !== item.id);
            } else {
                this.value = [...this.value, item.id];
            }

            this.emitFieldValueChange(this.field.attribute, this.value)
        })
    }
}
</script>

