<template>
  <div class="bg-white">
    <!-- TODO: Limitation: UX for mobile mode is bad, need to improve it with custom css-->
    <b-table-simple outlined responsive class="mb-0">
      <b-thead>
        <b-tr>
          <template v-for="(field, fieldIndex) in tableFieldMeta">
            <b-th :key="fieldIndex" :class="field.class || ''">{{ field.title }}</b-th>
          </template>
        </b-tr>
      </b-thead>
      <b-tbody v-if="orderItem.length > 0">
        <template v-for="(item, idx) in orderItem.sort((a, b) => a.free - b.free)">
          <b-tr
            :key="idx"
            :class="{
              'border-top-double': item.free,
              'c-pointer': item.subItems && !item.size,
              'bg-downy lighten-30': isCvTransferItemChecked(item),
            }"
            @click="
              () => {
                item.subItems && !item.size && toggleProducts(item, idx)
              }
            "
          >
            <b-td
              v-if="getEnableFields.index"
              :stacked-heading="getEnableFields.index.title"
              :class="[getEnableFields.index.tdClass]"
            >
              <span>{{ ++idx }}</span>
            </b-td>

            <b-td
              v-if="getEnableFields.product_image"
              :stacked-heading="$t('Common.Image.Label')"
              :class="[getEnableFields.product_image.tdClass]"
            >
              <b-img
                v-if="item.item_image && !item.free"
                width="50"
                alt="product image"
                class="rounded-2"
                :src="item.item_image"
              />
            </b-td>

            <b-td
              v-if="getEnableFields.product_code"
              :stacked-heading="getEnableFields.product_code.title"
              :class="[getEnableFields.product_code.tdClass]"
            >
              <span>{{ item.item_code }}</span>
            </b-td>

            <b-td
              v-if="getEnableFields.product_description"
              :stacked-heading="getEnableFields.product_description.title"
              :class="[getEnableFields.product_description.tdClass]"
            >
              <b-row>
                <b-col>{{ item.item_name }}</b-col>
                <b-col v-if="item.subItems && !item.size" cols="2" md="1" class="text-right">
                  <icon name="angle-down" :flip="isCollapsed(idx) === true ? null : 'vertical'" />
                </b-col>
              </b-row>
            </b-td>

            <b-td
              v-if="getEnableFields.cv_transfer"
              :stacked-heading="getEnableFields.cv_transfer.title"
              :class="[getEnableFields.cv_transfer.tdClass]"
            >
              <b-checkbox :checked="isCvTransferItemChecked(item)" @change="cvTransferItemChecked(item, $event)" />
            </b-td>

            <b-td
              v-if="getEnableFields.quantity"
              :stacked-heading="getEnableFields.quantity.title"
              :class="[getEnableFields.quantity.tdClass]"
            >
              <span>{{ item.quantity }}</span>
            </b-td>

            <b-td
              v-if="getEnableFields.total_bv"
              :stacked-heading="getEnableFields.total_bv.title"
              :class="[getEnableFields.total_bv.tdClass]"
            >
              <span>{{ item.cv }}</span>
            </b-td>

            <b-td
              v-if="getEnableFields.total_sv"
              :stacked-heading="getEnableFields.total_sv.title"
              :class="[getEnableFields.total_sv.tdClass]"
            >
              <span>{{ item.sv }}</span>
            </b-td>

            <b-td
              v-if="getEnableFields.total_cbp"
              :stacked-heading="getEnableFields.total_cbp.title"
              :class="[getEnableFields.total_cbp.tdClass]"
            >
              <span>{{ item.cbp }}</span>
            </b-td>

            <b-td
              v-if="getEnableFields.total_amount"
              :stacked-heading="getEnableFields.total_amount.title"
              :class="[getEnableFields.total_amount.tdClass]"
            >
              <span :class="{ 'text-info-green': item.free }">{{ itemPrice(item) }}</span>
            </b-td>

            <b-td
              v-if="getEnableFields.remove_item"
              :stacked-heading="getEnableFields.remove_item.title"
              :class="[getEnableFields.remove_item.tdClass]"
            >
              <b-button
                v-if="!item.removable"
                class="p-0"
                variant="link"
                @click="addProductToCart({ product_id: item.product_id, kitting_id: item.kitting_id, quantity: 0 })"
              >
                <icon name="eshop-remove" class="text-black icon-size-2" />
              </b-button>
            </b-td>
          </b-tr>
          <template v-if="item.subItems && isCollapsed(idx) === false">
            <b-tr
              v-for="(product, idx2) in item.subItems"
              variant="light"
              :key="`sub-items-${idx}-${idx2}`"
              class="animated flipInX border"
            >
              <b-td v-if="getEnableFields.index" :stacked-heading="getEnableFields.index.title" />

              <b-td
                v-if="getEnableFields.product_image"
                :stacked-heading="$t('Common.Image.Label')"
                :class="[getEnableFields.product_image.tdClass]"
              >
                <b-img v-if="product.image" width="50" alt="product-image" :src="product.image" class="rounded-2" />
              </b-td>

              <b-td
                v-if="getEnableFields.product_code"
                :stacked-heading="getEnableFields.product_code.title"
                :class="[getEnableFields.product_code.tdClass]"
              >
                <span>{{ product.sku }}</span>
              </b-td>

              <b-td
                v-if="getEnableFields.product_description"
                :stacked-heading="getEnableFields.product_description.title"
                :class="[getEnableFields.product_description.tdClass]"
              >
                <span>{{ product.name }}</span>
              </b-td>

              <b-td v-if="getEnableFields.cv_transfer" :stacked-heading="getEnableFields.cv_transfer.title" />

              <b-td
                v-if="getEnableFields.quantity"
                :stacked-heading="getEnableFields.quantity.title"
                :class="[getEnableFields.quantity.tdClass]"
              >
                <span>{{ product.quantity }}</span>
              </b-td>

              <b-td v-if="getEnableFields.total_bv" :stacked-heading="getEnableFields.total_bv.title" />
              <b-td v-if="getEnableFields.total_sv" :stacked-heading="getEnableFields.total_sv.title" />
              <b-td v-if="getEnableFields.total_cbp" :stacked-heading="getEnableFields.total_cbp.title" />
              <b-td v-if="getEnableFields.total_amount" :stacked-heading="getEnableFields.total_amount.title" />
              <b-td v-if="getEnableFields.remove_item" :stacked-heading="getEnableFields.remove_item.title" />
            </b-tr>
          </template>
        </template>
      </b-tbody>
      <b-tbody v-else>
        <b-td :colspan="tableFieldMeta.length" class="text-center py-4">{{ $t('Common.Cart.EmptyCart') }}</b-td>
      </b-tbody>
    </b-table-simple>
    <div v-if="showNoteForFocPwpItems" class="text-danger p-2 border">
      * {{ $t('Eshop.Order.GlobalWords.NoteForFOCPWPItems') }}
    </div>
  </div>
</template>
<script>
import _ from 'lodash'
import { mapActions } from 'vuex'
import { CurrencyMixin } from '../../mixins'

export default {
  name: 'Orderitem',
  mixins: [CurrencyMixin],
  props: {
    showRemoveCartItem: { type: Boolean, default: false },
    showItemImage: { type: Boolean, required: true },
    showItemCv: { type: Boolean, required: true },
    orderItem: { type: Array, required: true },
    showNoteForFocPwpItems: { type: Boolean, required: true },
    currencySymbol: { type: String, required: true },
    hasCvTransferOption: { type: Boolean, required: true },
    value: { type: Array, default: () => [] },
  },
  data() {
    return {
      freeStarted: false,
      freeIndex: -1,
      expanded: [],
      selectedCvTransferItems: [],
      flag: 1,
    }
  },
  methods: {
    ...mapActions('eshop', ['addProductToCart']),
    itemPrice(item) {
      if (item.free) {
        return this.$t('Eshop.Order.GlobalWords.Free')
      } else {
        return this.$helpers.getCurrencyValue(item.amount)
      }
    },
    identifyFreeStart(item, index) {
      if (typeof item !== 'undefined' && item.free && !this.freeStarted) {
        this.freeStarted = true
        this.freeIndex = index
      }
      return this.freeIndex
    },
    toggleProducts(item, idx) {
      if (!item.size) {
        var index = this.expanded.indexOf(idx)
        if (index > -1) {
          this.expanded.splice(index, 1)
        } else {
          this.expanded.push(idx)
        }
      }
    },
    cvTransferItemChecked(item, checked) {
      this.selectedCvTransferItems = _.merge([], this.value, this.selectedCvTransferItems)
      if (checked) {
        this.selectedCvTransferItems.push(item)
      } else {
        let index = _.findIndex(this.selectedCvTransferItems, { item_code: item.item_code })
        if (index !== -1) {
          this.selectedCvTransferItems.splice(index, 1)
        }
      }
      this.$emit('input', this.selectedCvTransferItems)
    },
    isCvTransferItemChecked(item) {
      return _.find(this.value, { item_code: item.item_code }) !== undefined
    },
  },
  computed: {
    tableFieldMeta() {
      let {
        evo: { enable: isEvo },
        eshop: {
          order_item: { cv_transfer_checkbox: cvTransferFeature },
        },
      } = this.$appSettings

      return [
        { key: 'index', title: this.$t('Common.Table.No'), order: 1 },
        { key: 'product_image', title: '', show: this.showItemImage, class: 'd-none d-lg-table-cell', order: 2 },
        { key: 'product_code', title: this.$t('Eshop.Order.ItemList.TableHeader.Code'), order: 3 },
        { key: 'product_description', title: this.$t('Eshop.Order.ItemList.TableHeader.ItemDescription'), order: 4 },
        {
          key: 'cv_transfer',
          title: this.$t('Eshop.Order.ItemList.TableHeader.CVTransfer'),
          show: cvTransferFeature && this.hasCvTransferOption,
          tdClass: 'text-center',
          order: 5,
        },
        { key: 'quantity', title: this.$t('Common.Quantity'), class: 'text-center', order: 6 },
        {
          key: 'total_bv',
          title: this.$t('Common.Terminology.TotalBV'),
          show: this.showItemCv,
          class: 'text-right',
          order: 7,
        },
        {
          key: 'total_sv',
          title: this.$t('Common.Terminology.TotalSv'),
          show: this.showItemCv && isEvo,
          class: 'text-right',
          order: 8,
        },
        {
          key: 'total_cbp',
          title: this.$t('Common.Terminology.TotalCbp'),
          show: this.showItemCv && isEvo,
          class: 'text-right',
          order: 9,
        },
        {
          key: 'total_amount',
          title: this.$t('Common.TotalAmount.WithCurrency', { currency: this.currencySymbol }),
          class: 'text-right',
          order: 10,
        },
        {
          key: 'remove_item',
          title: '',
          show: this.showRemoveCartItem,
          order: 12,
        },
      ]
        .filter(field => field.show !== false)
        .sort((a, b) => a.order - b.order)
    },

    getEnableFields() {
      let result = {}
      this.tableFieldMeta.forEach(meta => {
        result[meta.key] = { title: meta.title, class: meta.class || '', tdClass: meta.tdClass || meta.class || '' }
      })
      return result
    },

    isCollapsed: vue => idx => {
      return vue.expanded.indexOf(idx) === -1
    },
  },
  watch: {
    orderItem() {
      this.freeStarted = false
      let idx = 1
      this.orderItem.forEach(item => {
        if (item.size) {
          this.expanded.push(idx)
        }
        idx++
      })
    },
  },
}
</script>
