<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>

        <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>

      <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: 'AddOldPiecesToOldPieceRequest',
  props: {
    show: {
      type: Boolean,
      default: false
    },
    oprId: {
      requred: true,
      type: String,
      default: null
    }
  },
  data() {
    return {
      fetchingPieces: false,
      postingForm: false,
      pieces: [],
      selectedItem: '',
      selectedPiece: '',
      formData: {
        ItemReceptionTransDate: '',
        ItemName: '',
        SerialNo1: '',
        ItemID: '',
        ItemCode: '',

        // piece info
        pieceName: '',
        pieceCode: '',
        pieceId: ''
      },
      validation: {}
    }
  },
  computed: {
    showModal: {
      get() {
        return this.show
      },
      set(value) {
        this.$emit('closeModal')
      }
    },
    title() {
      return 'افزودن قطعه داغی به فرم'
    },
    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: {
    add() {
      this.validation = {}
      this.postingForm = true
      const data = this.formData

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