<template>
  <el-dialog :title="title" :visible.sync="showModal">
    <div v-loading="fetchingBuffers" class="addPtoPrModal">
      <el-form label-position="top" :model="formData">
        <el-form-item label="نام کالا" :class="validation.ItemName && 'err'">
          <el-select v-model="selectedItem" filterable style="width: 100%">
            <el-option-group label="لوازم جانبی کامپیوتر و موبایل">
              <el-option
                v-for="item in verityProducts"
                :key="item.ItemID + '_V'"
                :value="item.ItemID + '__v'"
                :label="item.ItemName"
              ></el-option>
            </el-option-group>

            <el-option-group label="لوازم صوتی و تصویری خودرو">
              <el-option
                v-for="item in panatechProducts"
                :key="item.ItemID + '_P'"
                :value="item.ItemID + '__p'"
                :label="item.ItemName"
              ></el-option>
            </el-option-group>
          </el-select>
          <p v-if="validation.ItemName" class="errMsg">{{ validation.ItemName.msg }}</p>
        </el-form-item>

        <el-form-item label="تعداد درخواستی" :class="validation.bufferQuantity && 'err'">
          <el-input
            v-model="formData.bufferQuantity"
            placeholder="تعداد را وارد کنید"
            @input="normalizeQuantityInput"
          ></el-input>
          <p v-if="validation.bufferQuantity" class="errMsg">{{ validation.bufferQuantity.msg }}</p>
        </el-form-item>
      </el-form>
      <div class="btnRow">
        <el-button class="btn btn-primary custom-el-button" :loading="postingForm" @click="add">افزودن</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: 'AddBuffersToBufferRequest',
  props: {
    show: {
      type: Boolean,
      default: false
    },
    brId: {
      requred: true,
      type: String,
      default: null
    }
  },
  data() {
    return {
      fetchingBuffers: false,
      postingForm: false,
      selectedItem: '',
      formData: {
        ItemName: '',
        ItemID: '',
        ItemCode: '',
        bufferQuantity: ''
      },
      validation: {}
    }
  },
  computed: {
    showModal: {
      get() {
        return this.show
      },
      set(value) {
        this.$emit('closeModal')
      }
    },
    title() {
      return 'افزودن کالای بافر به فرم'
    },
    bufferQuantity() {
      return this.formData.bufferQuantity
    },
    verityProducts() {
      return this.$store.state.front.verityProducts
    },
    panatechProducts() {
      return this.$store.state.front.panatechProducts
    }
  },
  watch: {
    selectedItem() {
      const selectedItem = this.selectedItem
      let ItemID, db_name
      if (selectedItem.includes('__v')) {
        ItemID = selectedItem.replace('__v', '')
        db_name = 'verity'
      } else if (selectedItem.includes('__p')) {
        ItemID = selectedItem.replace('__p', '')
        db_name = 'panatech'
      } else {
        return this.$message({
          type: 'error',
          message: 'Invalid Value'
        })
      }

      // find product
      let products
      if (db_name === 'verity') products = this.verityProducts
      if (db_name === 'panatech') products = this.panatechProducts

      const item = products.find(item => item.ItemID === ItemID)
      this.formData.ItemName = item?.ItemName
      this.formData.ItemID = item?.ItemID
      this.formData.ItemCode = item?.ItemCode
    }
  },
  methods: {
    normalizeQuantityInput() {
      this.formData.bufferQuantity = this.formData.bufferQuantity.toString().replace(/[^0-9]/g, '')
      if (
        this.formData.bufferQuantity === '' ||
        this.formData.bufferQuantity === null ||
        this.formData.bufferQuantity < 1
      ) {
        this.formData.bufferQuantity = 1
      }
    },
    add() {
      this.validation = {}
      this.postingForm = true
      const data = this.formData

      this.$axios
        .put(`/api/agent/addBrItems/${this.brId}`, data)
        .then(res => {
          this.postingForm = false
          this.showModal = false
          this.$message({
            type: 'success',
            message: 'کالای بافر درخواستی به فرم افزوده شد'
          })
          this.$nuxt.refresh()
        })
        .catch(err => {
          this.postingForm = false
          if (err.response.status === 422) {
            this.$message({
              type: 'warning',
              message: 'پارامترها رو بررسی و دوباره تلاش کنید'
            })
            this.validation = err.response.data.validation
          } else {
            this.$message({
              type: 'error',
              message: err.response?.data?.message
            })
          }
        })
    }
  }
}
</script>
