<template>
  <el-dialog :title="title" :visible.sync="showModal">
    <div class="addPtoPrModal reportModal">
      <el-form label-position="top" :model="formData">
        <el-form-item label="نام و نام خانوادگی مشتری" :class="validation.customerName && 'err'">
          <el-input v-model="formData.customerName" placeholder="نام را وارد کنید"></el-input>
          <p v-if="validation.customerName" class="errMsg">{{ validation.customerName.msg }}</p>
        </el-form-item>

        <el-form-item label="شماره تماس مشتری" :class="validation.customerTel && 'err'">
          <el-input v-model="formData.customerTel" placeholder="شماره را وارد کنید"></el-input>
          <p v-if="validation.customerTel" class="errMsg">{{ validation.customerTel.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.productIssue && 'err'">
          <el-input
            v-model="formData.productIssue"
            type="textarea"
            :rows="5"
            placeholder="شرح ایرادات کالا را بنویسید"
          ></el-input>
          <p v-if="validation.productIssue" class="errMsg">{{ validation.productIssue.msg }}</p>
        </el-form-item>

        <el-form-item label="قطعات مصرفی" :class="validation.usedPieces && 'err'">
          <el-input
            v-model="formData.usedPieces"
            type="textarea"
            :rows="5"
            placeholder="شرح قطقات مصرفی را بنویسید"
          ></el-input>
          <p v-if="validation.usedPieces" class="errMsg">{{ validation.usedPieces.msg }}</p>
        </el-form-item>

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

        <el-form-item label="تاریخ تحویل به مشتری" :class="validation.deliverDate && 'err'">
          <div class="datePickerWrapper">
            <persian-date-picker
              v-model="formData.deliverDate"
              display-format="jYYYY/jMM/jDD"
              format="YYYY-MM-DD HH:mm:ss"
              :min="formData.recieveDate"
              placeholder="تاریخ را انتخاب کنید"
              color="#065495"
            />
          </div>
          <p v-if="validation.deliverDate" class="errMsg">{{ validation.deliverDate.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: 'AddReportToGuaranteeReportForm',
  props: {
    show: {
      type: Boolean,
      default: false
    },
    grId: {
      requred: true,
      type: String,
      default: null
    }
  },
  data() {
    return {
      postingForm: false,
      selectedItem: '',
      formData: {
        customerName: '',
        customerTel: '',
        // product info
        ItemName: '',
        SerialNo1: '',
        ItemID: '',
        ItemCode: '',

        // product issue
        productIssue: '',
        usedPieces: '',

        // dates
        recieveDate: '',
        deliverDate: ''
      },
      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
    },
    recieveDate() {
      return this.formData.recieveDate
    }
  },
  watch: {
    recieveDate(newVal, oldVal) {
      this.formData.deliverDate = ''
    },
    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: {
    add() {
      this.validation = {}
      this.postingForm = true
      const data = this.formData

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