<template>
  <user-dashboard-container page-class="post" panel-title="افزودن تیکت">
    <form class="form form_3" @submit.prevent="post">
      <div class="formRow" :class="validation.title ? 'err' : null">
        <label for="title">:عنوان تیکت</label>
        <input id="title" v-model="ticket.title" type="text" />
        <p v-if="validation.title">{{ validation.title.msg }}</p>
      </div>
      <div class="formRow">
        <label>کد پذیرش:</label>
        <el-select v-model="ticket.transaction_id" filterable :placeholder="tnPlaceholder" :loading="fetching">
          <el-option-group :key="0" label="پذیرش موقت ها">
            <el-option
              v-for="(item, index) in ttns"
              :key="index + '_getAll_tempTransactions_for_new_ticket'"
              :value="item"
            ></el-option>
          </el-option-group>
          <el-option-group :key="1" label="پذیرش دائم ها">
            <el-option
              v-for="(item, index) in atns"
              :key="index + '_getAll_transactions_for_new_ticket'"
              :value="item"
            ></el-option>
          </el-option-group>
        </el-select>
      </div>
      <div class="btnRow">
        <button class="btn btn-primary" type="submit">
          <span>افزودن</span>
          <i class="far fa-plus-circle"></i>
        </button>
      </div>
    </form>
  </user-dashboard-container>
</template>

<script>
export default {
  name: 'AccountAddTicket',
  layout: 'user',
  data() {
    return {
      verityTransactions: [],
      panatechTransactions: [],
      agentsTransactions: [],
      fetching: false,
      ticket: {
        title: '',
        transaction_id: '',
        user_id: this.$auth.user._id
      },
      validation: {}
    }
  },
  computed: {
    transactions() {
      return [...this.verityTransactions, ...this.panatechTransactions, ...this.agentsTransactions]
    },
    ttns() {
      const array = []
      this.transactions.forEach(item => {
        if (!item.ItemReceptionTransNumber) array.push(item.TempReceiptTransNumber)
      })
      return array
    },
    atns() {
      const array = []
      this.transactions.forEach(item => {
        if (item.ItemReceptionTransNumber) array.push(item.ItemReceptionTransNumber)
      })
      return array
    },
    tnPlaceholder() {
      if (this.fetching) return 'در حال بارگیری...'
      else return 'اختیاری'
    }
  },
  async mounted() {
    try {
      this.fetching = true
      const user = this.$auth.user
      const verityData = {
        url: `/api/GetItemReceptionInfo?BusinessCode=${user.verity_businessCode}`,
        db: 'verity'
      }
      const panatechData = {
        url: `/api/GetItemReceptionInfo?BusinessCode=${user.panatech_businessCode}`,
        db: 'panatech'
      }

      const allData = await Promise.all([
        // fetch verityTransactions
        this.$axios.post('/api/cross/getRouteManager', verityData),
        // fetch panatechTransactions
        this.$axios.post('/api/cross/getRouteManager', panatechData),
        // fetch agentstransactions
        this.$axios.get('/api/user/transactions')
      ])

      const verityTransactions = allData[0]
      const panatechTransactions = allData[1]
      const agentsTransactions = allData[2]

      this.verityTransactions = verityTransactions.data.data
      this.panatechTransactions = panatechTransactions.data.data
      this.agentsTransactions = agentsTransactions.data

      this.fetching = false
    } catch (e) {
      this.$arpaError()
    }
  },
  methods: {
    post() {
      this.validation = {}

      this.$axios
        .post('/api/user/addTicketConversation', this.ticket)
        .then(res => {
          this.$message({
            type: 'success',
            message: 'تیکت با موفقیت ثبت شد، پیام خودرا بنویسید.'
          })
          this.$router.push({ name: 'account-tickets-ticket', params: { ticket: res.data._id } })
        })
        .catch(err => {
          if (err.response.data.status === 401) {
            return this.$message({
              type: 'warning',
              message: 'لطفا دوباره وارد حساب خود شوید'
            })
          }
          if (err.response.status === 422) this.validation = err.response.data.validation
          else console.log(err)
        })
    }
  }
}
</script>
