<template>
  <DefaultField
    :field="currentField"
    :errors="errors"
    :show-help-text="showHelpText"
    :full-width-content="fullWidthContent"
  >
    <template #field>
      <div class="payout-product-card">
        <div class="w-full">
          <div class="w-1/3">
            <span>{{ __('Hasap') }}: <strong>{{ total.toFixed(2) }}</strong></span>
          </div>
          <div class="w-1/3">
            <span>{{ __('Telekeci') }}: <strong>{{ entrepreneurTotal.toFixed(2) }}</strong></span>
          </div>
          <div class="w-1/3">
            <span>{{ __('POSTSHOP jemi') }}: <strong>{{ postshopTotal.toFixed(2) }}</strong></span>
          </div>
        </div>

        <div class="flex flex-wrap">
          <product-cart
            v-for="product in currentField.products"
            :key="product.id"
            :product="product"
          ></product-cart>
        </div>
      </div>
    </template>
  </DefaultField>
</template>

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

export default {
  mixins: [DependentFormField, HandlesValidationErrors],
  components: {
    ProductCart,
  },
  props: ['resourceName', 'resourceId', 'field'],
  data() {
    return {
      total: 0,
      entrepreneurTotal: 0,
      postshopTotal: 0,
      values: [],
      prices: [],
    };
  },
  methods: {
    /*
        * Set the initial, internal value for the field.
        */
        setInitialValue() {
            this.value = this.currentField.value || []
        },

        /**
        * Fill the given FormData object with the field's internal value.
        */
        fill(formData) {
            Array.from(this.values).forEach(value => {
                formData.append(this.currentField.attribute + '[]', value)
            })

            Array.from(this.prices).forEach(value => {
                formData.append('prices[]', JSON.stringify(value))
            })

            formData.append('total_sum', this.total.toFixed(2))
            formData.append('entrepreneur_total', this.entrepreneurTotal.toFixed(2))
            formData.append('postshop_total', this.postshopTotal.toFixed(2))
        },

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

    resetMoney() {
      this.total = 0;
      this.postshopTotal = 0;
      this.entrepreneurTotal = 0;
    },
    calculateMoney() {
      this.resetMoney();

      this.prices.forEach(item => {
        if (! this.values.includes(item.order_item_id)) {
            console.log('should return')
            return;
        }

        const unitPriceAmount = Number(item.unit_price_amount);
        const costAmount = Number(item.cost_amount);
        const quantity = Number(item.quantity);
        const percentageDifference = unitPriceAmount - costAmount;

        this.total += unitPriceAmount * quantity;
        this.postshopTotal += percentageDifference * quantity;
        this.entrepreneurTotal += costAmount * quantity;
      });

      this.total = parseFloat(this.total.toFixed(2));
      this.postshopTotal = parseFloat(this.postshopTotal.toFixed(2));
      this.entrepreneurTotal = parseFloat(this.entrepreneurTotal.toFixed(2));
    },
  },
  provide() {
    return {
      sharedState: {
        total: this.total,
        entrepreneurTotal: this.entrepreneurTotal,
        postshopTotal: this.postshopTotal,
        values: this.values,
        prices: this.prices,
        calculateMoney: this.calculateMoney,
        resetMoney: this.resetMoney,
      },
    };
  },
  mounted() {
    Nova.$on('add_to_values', (product) => {
        this.values.push(product.order_item_id)
    })

    Nova.$on('remove_from_values', (product) => {
        this.values = this.values.filter(item => item !== product.order_item_id)
    })
  }
};
</script>
