<template>
  <div class="mb-5 mb-sm-d-2">
    <b-row class="p-2 border no-gutters d-sm-d-block" align-v="center">
      <b-col cols="auto" class="display-image d-sm-d-none">
        <img :src="img" class="p-2" />
      </b-col>
      <b-col class="d-flex flex-column justify-content-center d-sm-d-block">
        <div class="font-weight-bold d-sm-d-inline-block">
          {{ title }}
        </div>
        <div v-if="amp" class="text-info-green font-weight-bold d-sm-d-none">
          {{ $t('Eshop.Product.CV') }} {{ ampCv }}
        </div>
        <div v-else-if="fpp" class="text-fpp font-weight-bold d-sm-d-none">
          {{ $t('Eshop.Product.CV') }} {{ fppCv }}
        </div>
        <div v-else class="text-primary font-weight-bold d-sm-d-none">{{ $t('Eshop.Product.CV') }} {{ cv }}</div>
        <div class="text-medium d-sm-d-inline-block">
          {{ code }}
        </div>
        <div class="text-secondary font-weight-bold d-sm-d-none">{{ currency }} {{ price }}</div>
      </b-col>
      <b-row>
        <b-col cols="6" lg="6">
          <b-form-group
            :label="$t('Eshop.InstSelection.InstallationDate')"
            :label-for="$t('Eshop.InstSelection.InstallationDate')"
            class="required"
          >
            <custom-date-picker
              :name="$t('Eshop.InstSelection.InstallationDate')"
              :value="installationDate"
              @input="updateInstallationDate($event)"
              :disable-date-range="{ to: new Date(Date.now()) }"
              :has-error="!installationDate && getErrors('cartError')"
              data-qa="installation-date-select"
            ></custom-date-picker>
          </b-form-group>
        </b-col>
        <b-col cols="6" lg="6">
          <b-form-group
            :label="$t('Eshop.InstSelection.InstallationSession')"
            :label-for="$t('Eshop.InstSelection.InstallationSession')"
            class="required"
          >
            <b-form-select
              :value="installationTime"
              :options="installationTimeOptions"
              @input="updateInstallationTime($event)"
              :class="{ 'border-danger': !installationTime && getErrors('cartError') }"
              data-qa="installation-time-select"
            />
          </b-form-group>
        </b-col>
      </b-row>
      <b-col
        cols="auto"
        class="text-right text-sm-d-left d-flex justify-content-center flex-column px-5 d-sm-d-block px-sm-d-0"
      >
        <h5 class="font-size-md-d-6 d-sm-d-inline-block">
          {{ $t('Eshop.SizeSelection.TotalQuantity') }}
        </h5>
        <h1 class="font-size-md-d-6 d-sm-d-inline-block">
          {{ quantity }}
        </h1>
      </b-col>
    </b-row>
  </div>
</template>
<script>
import currencyMixin from '../../mixins/currencyMixin'
import moment from 'moment'
import { mapGetters, mapActions, mapState } from 'vuex'
import { mapMasterDataId } from '@/app/_global/mixins'
import _ from 'lodash'
import CustomDatePicker from '@/elements/common/components/CustomDatePicker'

export default {
  name: 'ProductInstAddressSelection',
  mixins: [currencyMixin],
  inject: ['$validator'],
  components: { CustomDatePicker },
  props: {
    identifier: { type: String, required: true },
    productId: { type: Number, required: false },
    kittingId: { type: Number, required: false },
    isDummyCode: { type: Number, required: false },
    isFree: { type: Boolean, required: false },
    title: { type: String, default: '' },
    img: { type: String, default: '' },
    code: { type: String, default: '' },
    amp: { type: Boolean, default: false },
    fpp: { type: Boolean, default: false },
    cv: { type: Number, default: 0 },
    ampCv: { type: Number, default: 0 },
    fppCv: { type: Number, default: 0 },
    price: { type: String, default: '' },
    quantity: { type: Number, default: 0 },
    installationDate: { type: String },
    installationTime: { type: [String, Number] },
  },
  data() {
    return {
      installationTimeOptions: [],
      curDate: null,
    }
  },
  async mounted() {
    this.$validator.attach({
      name: 'InstallationDate',
      rules: 'required',
      getter: () => {
        return this.isInstallationDetailsValid()
      },
    })
    // clear date one mount
    // TODO: retrive data from state
    await this.loadMasterDataKeys({ keys: ['rental_installation_time_section'] })
    this.installationTimeOptions = this.getMasterDataOptionsByKey('rental_installation_time_section')

    let curDate = moment().add('days', 1)
    curDate = moment(curDate).format('YYYY-MM-DD')
    this.curDate = curDate
  },
  methods: {
    ...mapActions('eshop', ['selectCartProductsInstDetails', 'isInstallationDetailsValid']),
    ...mapActions(['loadMasterDataKeys']),
    updateInstallationTime(data) {
      let instDetails = { inst_details: [] }
      let obj = {}
      let cartInstDetails = this.getCartSelectedInstDetails
      let isFound = false
      for (let i = 0; i < cartInstDetails.inst_details.length; i++) {
        let productId = cartInstDetails.inst_details[i].product_id
        let kittingId = cartInstDetails.inst_details[i].kitting_id
        if (productId !== null && productId === this.productId) {
          isFound = true
          cartInstDetails.inst_details[i].installation_time = data
        }
        if (kittingId !== null && kittingId === this.kittingId) {
          isFound = true
          cartInstDetails.inst_details[i].installation_time = data
        }
      }
      if (!isFound) {
        obj = {
          product_id: this.productId,
          kitting_id: this.kittingId,
          is_dummy: this.isDummyCode,
          is_foc: this.isFree,
          installation_date: this.installationDate,
          installation_time: data,
        }
        instDetails.inst_details.push(obj)
        cartInstDetails.inst_details = _.union(instDetails.inst_details, cartInstDetails.inst_details)
      }

      this.selectCartProductsInstDetails(cartInstDetails)
    },
    updateInstallationDate(data) {
      let instDetails = { inst_details: [] }
      let obj = {}
      let cartInstDetails = this.getCartSelectedInstDetails
      let isFound = false
      for (let i = 0; i < cartInstDetails.inst_details.length; i++) {
        let productId = cartInstDetails.inst_details[i].product_id
        let kittingId = cartInstDetails.inst_details[i].kitting_id
        if (productId !== null && productId === this.productId) {
          isFound = true
          cartInstDetails.inst_details[i].installation_date = data
        }
        if (kittingId !== null && kittingId === this.kittingId) {
          isFound = true
          cartInstDetails.inst_details[i].installation_date = data
        }
      }

      if (!isFound) {
        obj = {
          product_id: this.productId,
          kitting_id: this.kittingId,
          is_dummy: this.isDummyCode,
          is_foc: this.isFree,
          installation_date: data,
          installation_time: this.installationTime,
        }
        instDetails.inst_details.push(obj)
        cartInstDetails.inst_details = _.union(instDetails.inst_details, cartInstDetails.inst_details)
      }
      this.selectCartProductsInstDetails(cartInstDetails)
    },
    isInstallationDetailsFound() {
      let details = this.getCartInstDetails
      let isFound = false
      for (let i = 0; i < details.inst_details.length; i++) {
        let productId = details.inst_details[i].product_id
        let kittingId = details.inst_details[i].kitting_id
        if (productId !== null && productId === this.product_id) {
          isFound = true
        }
        if (kittingId !== null && kittingId === this.kitting_id) {
          isFound = true
        }
      }
      return isFound
    },
  },
  computed: {
    ...mapGetters('eshop', {
      getCartInstDetails: 'getCartInstDetails',
      getCartSelectedInstDetails: 'getCartSelectedInstDetails',
      getRentalInstDetails: 'getRentalInstDetails',
    }),
    ...mapGetters({
      getMasterDataOptionsByKey: 'getMasterDataOptionsByKey',
      getErrors: 'getErrors',
    }),
    ...mapMasterDataId({
      RENTAL_INSTALATION_TIME: {
        instTimeAmId: 'AM',
        instTimePmId: 'PM',
      },
    }),
  },
}
</script>
