<template>
  <el-dialog :title="title" :visible.sync="showModal">
    <div v-loading="fetchingPieces" class="addPtoPrModal">
      <el-form label-position="top" :model="formData">
        <h3 class="mb-3">مشخصات کالا:</h3>

        <el-form-item label="تاریخ پذیرش" :class="validation.ItemReceptionTransDate && 'err'">
          <div class="datePickerWrapper">
            <persian-date-picker
              v-model="formData.ItemReceptionTransDate"
              display-format="jYYYY/jMM/jDD"
              format="YYYY-MM-DD HH:mm:ss"
              placeholder="تاریخ را انتخاب کنید"
              color="#065495"
            />
          </div>
          <p v-if="validation.ItemReceptionTransDate" class="errMsg">{{ validation.ItemReceptionTransDate.msg }}</p>
        </el-form-item>

        <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="سریال">
          <el-input v-model="formData.SerialNo1" placeholder="اختیاری"></el-input>
        </el-form-item>

        <el-form-item label="وضعیت گارانتی" :class="validation.gStatus && 'err'">
          <el-select v-model="formData.gStatus" style="width: 100%">
            <el-option :value="true" label="دارد"></el-option>
            <el-option :value="false" label="ندارد"></el-option>
          </el-select>
          <p v-if="validation.gStatus" class="errMsg">{{ validation.gStatus.msg }}</p>
        </el-form-item>

        <h3 class="mb-3">مشخصات قطعه درخواستی:</h3>
        <el-form-item label="نام قطعه" :class="validation.pieceName && 'err'">
          <el-select v-model="selectedPiece" filterable style="width: 100%">
            <el-option
              v-for="item in pieces"
              :key="item._id"
              :value="item._id"
              :label="item.name + ` ( کد: ${item.code} ) `"
            ></el-option>
          </el-select>
          <p v-if="validation.pieceName" class="errMsg">{{ validation.pieceName.msg }}</p>
        </el-form-item>

        <el-form-item label="تعداد درخواستی" :class="validation.pieceQuantity && 'err'">
          <el-input
            v-model="formData.pieceQuantity"
            placeholder="تعداد را وارد کنید"
            @input="normalizeQuantityInput"
          ></el-input>
          <p v-if="validation.pieceQuantity" class="errMsg">{{ validation.pieceQuantity.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: 'AddPiecesToPieceRequest',
  props: {
    show: {
      type: Boolean,
      default: false
    },
    prId: {
      requred: true,
      type: String,
      default: null
    }
  },
  data() {
    return {
      fetchingPieces: false,
      postingForm: false,
      pieces: [],
      selectedItem: '',
      selectedPiece: '',
      formData: {
        ItemReceptionTransDate: '',
        ItemName: '',
        SerialNo1: '',
        ItemID: '',
        ItemCode: '',
        gStatus: '',

        // piece info
        pieceName: '',
        pieceCode: '',
        pieceQuantity: '',
        pieceId: ''
      },
      validation: {}
    }
  },
  computed: {
    showModal: {
      get() {
        return this.show
      },
      set(value) {
        this.$emit('closeModal')
      }
    },
    title() {
      return 'افزودن قطعه به فرم'
    },
    pieceQuantity() {
      return this.formData.pieceQuantity
    },
    verityProducts() {
      return this.$store.state.front.verityProducts
    },
    panatechProducts() {
      return this.$store.state.front.panatechProducts
    }
  },
  watch: {
    showModal(newVal, oldVal) {
      if (newVal) {
        this.fetchingPieces = true

        this.$axios
          .get('/api/agent/pieces')
          .then(res => {
            this.fetchingPieces = false
            this.pieces = res.data
          })
          .catch(err => {
            console.log(err)
          })
      }
    },
    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
    },
    selectedPiece() {
      const item = this.pieces.find(item => item._id === this.selectedPiece)
      this.formData.pieceId = item?._id
      this.formData.pieceName = item?.name
      this.formData.pieceCode = item?.code
    }
  },
  methods: {
    normalizeQuantityInput() {
      this.formData.pieceQuantity = this.formData.pieceQuantity.toString().replace(/[^0-9]/g, '')
      if (
        this.formData.pieceQuantity === '' ||
        this.formData.pieceQuantity === null ||
        this.formData.pieceQuantity < 1
      ) {
        this.formData.pieceQuantity = 1
      }
    },
    add() {
      this.validation = {}
      this.postingForm = true
      const data = this.formData

      this.$axios
        .put(`/api/agent/addPrItems/${this.prId}`, 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>
