<template>
  <user-dashboard-container page-class="factor" panel-title="فاکتور">
    <div id="factor-layout">
      <div class="pageHeader">
        <div class="row1">
          <h2>
            <span>سیستم جاری</span>
            <br />
            <span>فاکتور تعمیرات</span>
          </h2>
        </div>
        <div class="row2">
          <p>
            <span>شماره حواله: </span>
            <span>{{ factorInfo.TransNumber }}</span>
          </p>
          <p>
            <span>تاریخ حواله: </span>
            <span>{{ $jDate(factorInfo.TransDate) }}</span>
          </p>
        </div>
      </div>

      <div class="factor">
        <div class="factorInfo">
          <div class="row1">
            <p>
              <span>کد شخص: </span>
              <span>{{ userBusinessCode }}</span>
            </p>
            <p>
              <span>طرف حساب: </span>
              <span>{{ user.first_name + ' ' + user.last_name }}</span>
            </p>
            <p>
              <span>شماره پذیرش: </span>
              <span>{{ $route.query.atn }}</span>
            </p>
          </div>
          <div class="row2">
            <p>
              <span>آدرس: </span>
              <span>{{ factorInfo.cAddress1 }}</span>
            </p>
          </div>
          <div class="row3">
            <p>
              <span>شماره تماس: </span>
              <span>{{ factorInfo.cTel1 }}</span>
            </p>
          </div>
          <div class="row4">
            <p>
              <span>شرح حواله: </span>
              <span>{{ factorInfo.Description || '---' }}</span>
            </p>
          </div>
        </div>
        <div class="table">
          <table>
            <thead>
              <tr>
                <th>ردیف</th>
                <th>کد کالا</th>
                <th>نام کالا</th>
                <th>تعداد کالا</th>
                <th>مبلغ اجرت (ريال)</th>
                <th>مبلغ کل (ريال)</th>
                <th>معایب</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, index) in factor" :key="index + '_tableItem_g_ar_f'">
                <td>{{ index + 1 }}</td>
                <td>{{ item.ItemCode }}</td>
                <td>{{ item.ItemName }}</td>
                <td>{{ item.Repair_Self }}</td>
                <td>{{ item.TASPrice.toLocaleString() || '-' }}</td>
                <td>{{ totalPrice(item).toLocaleString() }}</td>
                <td>{{ item.Note || '-' }}</td>
              </tr>

              <!-- table footer -->
              <tr>
                <td colspan="3">جمع</td>
                <td>{{ sum('Repair_Self') }}</td>
                <!--              <td>{{ sum('TASPrice').toLocaleString() }}</td>-->
                <td>-</td>
                <td>{{ totalPriceSum().toLocaleString() }}</td>
                <td></td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
    <table-notice />
    <button class="btn btn-primary mt-3" @click="print('factor-layout')">چاپ فاکتور</button>
  </user-dashboard-container>
</template>

<script>
export default {
  name: 'AccountGuaranteePaymentFactor',
  layout: 'user',
  async asyncData({ $axios, $auth, query, error }) {
    try {
      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') {
        const guaranteeFactorData = {
          url: `/api/GetItemReceptionDetails?BusinessCode=${businessCode()}&ItemReceptionTransNumber=${acceptedTN}`,
          db: db_name
        }
        const factorData = {
          url: `/api/GetCustomizedRepairInfo?BusinessCode=${businessCode()}&TransNumber=${acceptedTN}`,
          db: db_name
        }

        const allData = await Promise.all([
          // fetch guaranteeFactor
          $axios.post('/api/cross/getRouteManager', guaranteeFactorData),
          // fetch factor
          $axios.post('/api/cross/getRouteManager', factorData)
        ])

        const guaranteeFactor = allData[0]
        const factor = allData[1]

        // validate data
        if (guaranteeFactor.data.error || !guaranteeFactor.data.data.length) throw new Error('invalid params')
        if (factor.data.error || !factor.data.data.length) throw new Error('invalid params')

        return {
          factor: factor.data.data,
          guaranteeFactor: guaranteeFactor.data.data
        }
      } else if (host === 'as') {
        /// functions go here
      } else throw new Error('invalid params')
    } catch (e) {
      error({ status: 404, message: 'Page not found' })
    }
  },
  data() {
    return {
      transactionItems: null,
      factor: null,
      guaranteeFactor: null
    }
  },
  computed: {
    user() {
      return this.$auth.user
    },
    userBusinessCode() {
      const db_name = this.$route.query.db_name
      if (db_name === 'verity') return this.user.verity_businessCode
      else if (db_name === 'panatech') return this.user.panatech_businessCode
      else return '-'
    },
    factorInfo() {
      return this.guaranteeFactor[0]
    }
  },
  methods: {
    print(id) {
      $(`#${id}`).print()
    },
    totalPrice(item) {
      return Number(item.TASPrice) * Number(item.Repair_Self)
    },
    sum(param) {
      let sum = 0
      let index = -1
      for (const item of this.factor) {
        index++
        sum += Number(item[param])
        if (index === this.factor.length - 1) return sum
      }
    },
    totalPriceSum() {
      let sum = 0
      let index = -1
      for (const item of this.factor) {
        index++
        sum += Number(this.totalPrice(item))
        if (index === this.factor.length - 1) return sum
      }
    }
  }
}
</script>
