<template>
  <user-dashboard-container page-class="guarantee-details" panel-title="جزئیات">
    <form action="" class="form form_3">
      <div class="userInfo">
        <div class="formRow">
          <label v-if="$route.query.atn">کد پذیرش دائم:</label>
          <label v-else>کد پذیرش موقت:</label>
          <input type="text" disabled :value="$route.query.atn || $route.query.ttn" />
        </div>
        <div class="formRow">
          <label>شماره تماس:</label>
          <input type="text" disabled :value="transactionInfo.cTel1" />
        </div>
        <div class="formRow">
          <label>تاریخ ارسال فرم:</label>
          <input
            type="text"
            disabled
            :value="$jDate(host === 'ar' ? transactionInfo.TransDate : transactionInfo.TempReceiptTransDate)"
          />
        </div>
      </div>

      <div class="formRow">
        <label>آدرس:</label>
        <textarea name="" rows="3" disabled :value="transactionInfo.cAddress1"></textarea>
      </div>
      <div class="formRow">
        <label>توضیحات فرم:</label>
        <textarea name="" rows="3" disabled :value="transactionInfo.Description"></textarea>
      </div>
    </form>

    <hr />

    <div class="tableBox">
      <table class="formItems">
        <thead>
          <tr>
            <th class="index">ردیف</th>
            <th class="itemName">نام کالا</th>
            <th class="quantity">تعداد</th>
            <th class="itemSerial">سریال گارانتی</th>
            <th class="date">تاریخ اتمام گارانتی</th>
          </tr>
        </thead>

        <tbody>
          <tr v-for="(item, index) in items" :key="index + '_guaranteeItemsList'" :title="item.ItemName">
            <td class="index">
              <span>{{ index + 1 }}</span>
            </td>
            <td class="itemName">
              <span v-if="host === 'ar'" class="singleLineTxt">{{ item.ItemName }}</span>
              <span v-if="host === 'as'" class="singleLineTxt">{{
                getItemName(item.ItemID) || 'درحال بارگیری ...'
              }}</span>
            </td>
            <td class="quantity">
              <span v-if="host === 'ar'">{{ item.NQty }}</span>
              <span v-if="host === 'as'">{{ item.MjQty }}</span>
            </td>
            <td class="itemSerial">
              <span>{{ item.SerialNo1 || '-' }}</span>
            </td>
            <td class="date">
              <span>{{ item.GEndDate || '-' }}</span>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <table-notice />

    <hr />

    <div class="buttons">
      <nuxt-link
        :to="{
          name: 'account-guarantee-receipt',
          query: { ttn: $route.query.ttn, host: host, db_name: $route.query.db_name }
        }"
        class="btn btn-primary"
        >مشاهده رسید ها</nuxt-link
      >
      <nuxt-link
        v-if="factor && factor.length"
        :to="{
          name: 'account-guarantee-factor',
          query: { atn: $route.query.atn, host: host, db_name: $route.query.db_name }
        }"
        class="btn btn-primary"
        style="margin-right: 5px"
      >
        مشاهده فاکتور
      </nuxt-link>
    </div>

    <template v-if="paymentFactor && paymentFactor.length">
      <hr />
      <div class="paymentFactorBtn mb-5">
        <strong
          >*در موارد ارسالی شما کالا بدون گارانتی وجود دارد و تعمیرات شامل هزینه میشود.برای مشاهده فاکتور هزینه ها روی
          دکمه زیر کلیک کنید و پس از پرداخت هزینه عکس فیش پرداختی را در تیکت برای ادمین بفرستید.(شماره پذیرش مربوطه را
          در تیکت مشخص کنید)</strong
        >
        <nuxt-link
          :to="{
            name: 'account-guarantee-paymentFactor',
            query: { atn: $route.query.atn, host: host, db_name: $route.query.db_name }
          }"
          class="btn btn-primary"
          >مشاهده فاکتور تعمیرات
        </nuxt-link>
      </div>
    </template>
  </user-dashboard-container>
</template>

<script>
export default {
  name: 'AccountGuaranteeDetails',
  layout: 'user',
  async asyncData({ $axios, $auth, query, error }) {
    try {
      const tempTN = query?.ttn
      const acceptedTN = query?.atn
      const host = query?.host
      const db_name = query?.db_name
      const user = $auth.user

      function businessCode() {
        if (db_name === 'verity') return user.verity_businessCode
        else if (db_name === 'panatech') return user.panatech_businessCode
        else return null
      }

      if (host === 'ar') {
        // fetch data from arpa
        const transactionItemsData = {
          url: `/api/GetTransactionDetails?BusinessCode=${businessCode()}&TransNumber=${
            acceptedTN || tempTN
          }&DocAliasID=${acceptedTN ? 63 : 144}&WithSerials=1`,
          db: db_name
        }

        const transactionItems = await $axios.post('/api/cross/getRouteManager', transactionItemsData)
        if (transactionItems.data.error || !transactionItems.data.data.length) throw new Error('invalid params')
        return {
          transactionItems: transactionItems.data.data
        }
      } else if (host === 'as') {
        // fetch data from asan-service
        const transaction = await $axios.get(`/api/user/transaction/${tempTN}`)
        return {
          transaction: transaction.data
        }
      } else throw new Error('invalid params')
    } catch (e) {
      error({ status: 404, message: 'Page not found' })
    }
  },
  data() {
    return {
      transactionItems: null,
      transaction: null,
      factor: null,
      paymentFactor: null
    }
  },
  computed: {
    products() {
      if (this.$route.query.db_name === 'verity') return this.$store.state.front.verityProducts
      else if (this.$route.query.db_name === 'panatech') return this.$store.state.front.panatechProducts
      else return []
    },
    host() {
      return this.$route.query?.host
    },
    items() {
      if (this.host === 'ar') return this.transactionItems
      else if (this.host === 'as') return this.transaction.items
      else return []
    },
    transactionInfo() {
      if (this.host === 'ar') return this.transactionItems[0]
      else if (this.host === 'as') return this.transaction
      else return {}
    }
  },
  mounted() {
    const host = this.host
    const user = this.$auth.user
    const db_name = this.$route.query?.db_name
    const acceptedTN = this.$route.query?.atn

    if (host === 'ar') {
      // fetch data from arpa
      const paymentData = {
        url: `/api/GetCustomizedRepairInfo?BusinessCode=${
          db_name === 'verity' ? user.verity_businessCode : db_name === 'panatech' ? user.panatech_businessCode : ''
        }&TransNumber=${acceptedTN}`,
        db: db_name
      }

      const factorData = {
        url: `/api/GetItemReceptionDetails?BusinessCode=${
          db_name === 'verity' ? user.verity_businessCode : db_name === 'panatech' ? user.panatech_businessCode : ''
        }&ItemReceptionTransNumber=${acceptedTN}`,
        db: db_name
      }
      if (acceptedTN) {
        this.$axios
          .post('/api/cross/getRouteManager', factorData)
          .then(res => {
            this.factor = res.data.data
          })
          .catch(err => {
            console.log(err)
          })
        this.$axios
          .post('/api/cross/getRouteManager', paymentData)
          .then(res => {
            this.paymentFactor = res.data.data
          })
          .catch(err => {
            console.log(err)
          })
      }
    } else if (host === 'as') {
      // fetch data from asan-service
    }
  },
  methods: {
    getItemName(ItemID) {
      return this.products.find(item => item.ItemID === ItemID)?.ItemName
    }
  }
}
</script>
