<template>
  <user-dashboard-container page-class="agent-reports" panel-title="گزارش گیری">
    <div class="filter mb-5">
      <div class="mb-3">
        <h4>تهیه گزارش از:</h4>
      </div>
      <div class="reportTypes">
        <button class="switchBtns btn" :class="type === 'inbox' && 'btn-primary'" @click="type = 'inbox'">
          صندوق ورودی گارانتی
        </button>
        <button class="switchBtns btn" :class="type === 'pr' && 'btn-primary'" @click="type = 'pr'">
          درخواست های قطعه
        </button>
        <button class="switchBtns btn" :class="type === 'opr' && 'btn-primary'" @click="type = 'opr'">
          درخواست های قطعه داغی
        </button>
        <button class="switchBtns btn" :class="type === 'br' && 'btn-primary'" @click="type = 'br'">
          درخواست های کالای بافر
        </button>
        <button class="switchBtns btn" :class="type === 'gr' && 'btn-primary'" @click="type = 'gr'">
          گزارش های عملکرد گارانتی
        </button>
      </div>
    </div>

    <div v-if="type" v-loading="fetchingData" class="reportOptions">
      <el-form :model="reportParams" :class="type">
        <div class="seprator">
          <p>فیلتر مربوط به فرم ها</p>
        </div>

        <el-form-item label="از تاریخ (تاریخ ارسال فرم)" class="fromDate">
          <div class="datePickerWrapper">
            <persian-date-picker
              v-model="reportParams.fromDate"
              display-format="jYYYY/jMM/jDD"
              format="YYYY-MM-DD HH:mm:ss"
              placeholder="اختیاری"
              color="#065495"
              clearable
              append-to="body"
            />
          </div>
        </el-form-item>

        <el-form-item label="تا تاریخ (تاریخ ارسال فرم)" class="toDate">
          <div class="datePickerWrapper">
            <persian-date-picker
              v-model="reportParams.toDate"
              display-format="jYYYY/jMM/jDD"
              :min="reportParams.fromDate"
              format="YYYY-MM-DD HH:mm:ss"
              placeholder="اختیاری"
              color="#065495"
              clearable
              append-to="body"
              @change="validateDateRange('toDate')"
            />
          </div>
        </el-form-item>

        <el-form-item v-if="type !== 'gr'" label="وضعیت فرم" class="formStatus">
          <el-select v-model="reportParams.formStatus" filterable clearable style="width: 100%" placeholder="اختیاری">
            <template v-if="type === 'inbox'">
              <el-option value="saved" label="دریافتی"></el-option>
              <el-option value="recieved" label="پذیرش شده"></el-option>
            </template>
            <template v-else>
              <el-option value="sent" label="ارسال شده"></el-option>
            </template>
            <el-option value="ongoing" label="در دست اقدام"></el-option>
            <el-option value="waiting" label="در انتظار قطعه"></el-option>
            <el-option value="delivered" label="تحویل شده"></el-option>
          </el-select>
        </el-form-item>

        <div class="seprator">
          <p>فیلتر مربوط به آیتم ها</p>
        </div>
        <el-form-item label="نام کالا" class="selectedItem">
          <el-select v-model="selectedItem" filterable clearable style="width: 100%" placeholder="اختیاری">
            <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>
        </el-form-item>

        <el-form-item v-if="type === 'pr'" label="وضعیت گارانتی" class="gStatus">
          <el-select v-model="reportParams.gStatus" style="width: 100%" clearable placeholder="اختیاری">
            <el-option :value="true" label="دارد"></el-option>
            <el-option :value="false" label="ندارد"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item v-if="type === 'pr' || type === 'opr'" label="نام قطعه" class="pieceId">
          <el-select v-model="reportParams.pieceId" filterable clearable style="width: 100%" placeholder="اختیاری">
            <el-option
              v-for="item in pieces"
              :key="item._id"
              :value="item._id"
              :label="item.name + ` ( کد: ${item.code} ) `"
            ></el-option>
          </el-select>
        </el-form-item>

        <template v-if="type === 'pr' || type === 'opr'">
          <el-form-item label="از تاریخ (تاریخ پذیرش کالا)" class="fromItemReceptionTransDate">
            <div class="datePickerWrapper">
              <persian-date-picker
                v-model="reportParams.fromItemReceptionTransDate"
                display-format="jYYYY/jMM/jDD"
                format="YYYY-MM-DD HH:mm:ss"
                placeholder="اختیاری"
                color="#065495"
                clearable
                append-to="body"
              />
            </div>
          </el-form-item>

          <el-form-item label="تا تاریخ (تاریخ پذیرش کالا)" class="toItemReceptionTransDate">
            <div class="datePickerWrapper">
              <persian-date-picker
                v-model="reportParams.toItemReceptionTransDate"
                display-format="jYYYY/jMM/jDD"
                :min="reportParams.fromItemReceptionTransDate"
                format="YYYY-MM-DD HH:mm:ss"
                placeholder="اختیاری"
                color="#065495"
                clearable
                append-to="body"
                @change="validateDateRange('toItemReceptionTransDate')"
              />
            </div>
          </el-form-item>
        </template>

        <template v-if="type === 'gr'">
          <el-form-item label="از تاریخ (تاریخ دریافت از مشتری)" class="fromRecieveDate">
            <div class="datePickerWrapper">
              <persian-date-picker
                v-model="reportParams.fromRecieveDate"
                display-format="jYYYY/jMM/jDD"
                format="YYYY-MM-DD HH:mm:ss"
                placeholder="اختیاری"
                color="#065495"
                clearable
                append-to="body"
              />
            </div>
          </el-form-item>

          <el-form-item label="تا تاریخ (تاریخ دریافت از مشتری)" class="toRecieveDate">
            <div class="datePickerWrapper">
              <persian-date-picker
                v-model="reportParams.toRecieveDate"
                display-format="jYYYY/jMM/jDD"
                :min="reportParams.fromRecieveDate"
                format="YYYY-MM-DD HH:mm:ss"
                placeholder="اختیاری"
                color="#065495"
                clearable
                append-to="body"
                @change="validateDateRange('toRecieveDate')"
              />
            </div>
          </el-form-item>

          <el-form-item label="از تاریخ (تاریخ تحویل به مشتری)" class="fromDeliverDate">
            <div class="datePickerWrapper">
              <persian-date-picker
                v-model="reportParams.fromDeliverDate"
                display-format="jYYYY/jMM/jDD"
                format="YYYY-MM-DD HH:mm:ss"
                placeholder="اختیاری"
                color="#065495"
                clearable
                append-to="body"
              />
            </div>
          </el-form-item>

          <el-form-item label="تا تاریخ (تاریخ تحویل به مشتری)" class="toDeliverDate">
            <div class="datePickerWrapper">
              <persian-date-picker
                v-model="reportParams.toDeliverDate"
                display-format="jYYYY/jMM/jDD"
                :min="reportParams.fromDeliverDate"
                format="YYYY-MM-DD HH:mm:ss"
                placeholder="اختیاری"
                color="#065495"
                clearable
                append-to="body"
                @change="validateDateRange('toDeliverDate')"
              />
            </div>
          </el-form-item>
        </template>
      </el-form>

      <div v-if="type" class="btnRow">
        <el-button class="btn btn-primary custom-el-button" :loading="reporting" @click="getReport"
          >تهیه گزارش</el-button
        >
      </div>
    </div>

    <div v-if="reportIsReady" class="reportResult mt-5">
      <el-divider></el-divider>
      <div class="infoCharts mb-5 mt-3">
        <div class="container-fluid">
          <div class="row">
            <!-- forms -->
            <div class="col-6">
              <CChartDoughnut :datasets="formsChartData.datasets" :labels="formsChartData.labels" />
              <div class="mt-3">
                <p>
                  <span>تعداد کل فرم ها:</span>
                  <b>{{ result.totalFormsCount }}</b>
                </p>
                <p>
                  <span>تعداد فرم های فیلتر شده:</span>
                  <b>{{ result.filteredFormsCount }}</b>
                </p>
              </div>
            </div>
            <!-- items -->
            <div class="col-6">
              <CChartDoughnut :datasets="itemsChartData.datasets" :labels="itemsChartData.labels" />
              <div class="mt-3">
                <p>
                  <span>تعداد کل آیتم های داخل فرم ها:</span>
                  <b>{{ result.totalItemsCount }}</b>
                </p>
                <p>
                  <span>تعداد آیتم های فیلتر شده داخل فرم ها:</span>
                  <b>{{ result.filteredItemsCount }}</b>
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="resultList">
        <el-divider></el-divider>
        <div class="filter mb-5">
          <h4 style="display: inline-block; margin-left: 15px">مشاهده لیست:</h4>
          <button class="switchBtns btn" :class="result.mode === 'item' && 'btn-primary'" @click="result.mode = 'item'">
            آیتم ها
          </button>
          <button class="switchBtns btn" :class="result.mode === 'form' && 'btn-primary'" @click="result.mode = 'form'">
            فرم ها
          </button>
        </div>

        <el-table v-if="result.mode === 'form'" key="ffsTable" :data="result.ffs" :lazy="true" style="width: 100%">
          <el-table-column type="index" label="#"> </el-table-column>

          <template v-if="type === 'inbox'">
            <el-table-column prop="Description" label="توضیحات" width="">
              <template slot-scope="scope">
                <span class="singleLineTxt" :title="scope.row.Description"> {{ scope.row.Description || '-' }} </span>
              </template>
            </el-table-column>

            <el-table-column
              prop="TempReceiptTransNumber"
              label="شماره پذیرش موقت"
              width=""
              align="center"
            ></el-table-column>

            <el-table-column prop="ItemReceptionTransNumber" label="شماره پذیرش دائم" width="" align="center">
              <template slot-scope="scope">
                <span> {{ scope.row.ItemReceptionTransNumber || '-' }} </span>
              </template>
            </el-table-column>

            <el-table-column prop="TempReceiptTransDate" label="تاریخ ارسال فرم" width="" align="center">
              <template slot-scope="scope">
                <span> {{ $jDate(scope.row.TempReceiptTransDate) }} </span>
              </template>
            </el-table-column>

            <el-table-column prop="ItemReceptionTransDate" label="تاریخ پذیرش" width="" align="center">
              <template slot-scope="scope">
                <span> {{ $jDate(scope.row.ItemReceptionTransDate) }} </span>
              </template>
            </el-table-column>

            <el-table-column prop="db_name" label="برند" width="" align="center">
              <template slot-scope="scope">
                <i
                  v-if="scope.row.db_name === 'verity'"
                  class="fas fa-phone-laptop"
                  title="لوازم جانبی کامپیوتر و موبایل"
                ></i>
                <i
                  v-if="scope.row.db_name === 'panatech'"
                  class="fas fa-photo-video"
                  title="لوازم صوتی و تصویری خودرو"
                ></i>
              </template>
            </el-table-column>

            <el-table-column prop="status" label="وضعیت" width="" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.status === 'saved'">دریافتی</span>
                <span v-if="scope.row.status === 'recieved'">پذیرش شده</span>
                <span v-if="scope.row.status === 'ongoing'">در دست اقدام</span>
                <span v-if="scope.row.status === 'waiting'">در انتظار قطعه</span>
                <span v-if="scope.row.status === 'delivered'">تحویل شده</span>
              </template>
            </el-table-column>
          </template>

          <template v-else>
            <el-table-column prop="description" label="توضیحات" width="">
              <template slot-scope="scope">
                <span class="singleLineTxt"> {{ scope.row.description || '-' }} </span>
              </template>
            </el-table-column>

            <el-table-column prop="trackingCode" label="کد پیگیری" width="" align="center"> </el-table-column>
            <el-table-column prop="sendDate" label="کد پیگیری" width="" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.trackingCode }}</span>
              </template>
            </el-table-column>

            <el-table-column prop="sendDate" label="تاریخ ارسال" width="" align="center">
              <template slot-scope="scope">
                <span>{{ $jDate(scope.row.sendDate) }}</span>
              </template>
            </el-table-column>

            <el-table-column prop="status" label="وضعیت" width="" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.status === 'sent'">ارسال شده</span>
                <span v-if="scope.row.status === 'ongoing'">در دست اقدام</span>
                <span v-if="scope.row.status === 'waiting'">در انتظار قطعه</span>
                <span v-if="scope.row.status === 'delivered'">تحویل شده</span>
              </template>
            </el-table-column>
          </template>

          <el-table-column label="اطلاعات" width="70" align="center">
            <template slot-scope="scope">
              <nuxt-link :to="formViewLink(type === 'inbox' ? scope.row : scope.row._id)" target="_blank">
                <button class="showDetailsBtn" title="مشاهده فرم">
                  <i class="fas fa-info"></i>
                </button>
              </nuxt-link>
            </template>
          </el-table-column>
        </el-table>
        <!-- item table -->
        <el-table
          v-if="result.mode === 'item'"
          key="itemsListTable"
          :data="result.list"
          :lazy="true"
          style="width: 100%"
        >
          <el-table-column type="index" label="#"> </el-table-column>

          <template v-if="type === 'inbox'">
            <el-table-column prop="ItemName" label="نام کالا" width="">
              <template slot-scope="scope">
                <span> {{ getItemName(scope.row.ItemID, scope.row.db_name) }} </span>
              </template>
            </el-table-column>

            <el-table-column prop="MjQty" label="تعداد" width=""> </el-table-column>
          </template>

          <template v-if="type !== 'inbox'">
            <el-table-column prop="ItemName" label="نام کالا" width="450px"></el-table-column>
          </template>

          <template v-if="type === 'br'">
            <el-table-column prop="bufferQuantity" label="تعداد" width="" align="center"> </el-table-column>
          </template>

          <template v-if="type === 'pr'">
            <el-table-column prop="gStatus" label="وضعیت گارانتی" width="" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.gStatus">دارد</span>
                <span v-else>ندارد</span>
              </template>
            </el-table-column>
          </template>

          <template v-if="type === 'pr' || type === 'opr'">
            <el-table-column prop="ItemReceptionTransDate" label="تاریخ پذیرش" width="">
              <template slot-scope="scope">
                <span>{{ $jDate(scope.row.ItemReceptionTransDate) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="pieceName" label="نام قطعه" width="" align="center"> </el-table-column>
            <el-table-column prop="pieceCode" label="کد قطعه" width="" align="center"> </el-table-column>
          </template>

          <template v-if="type === 'pr'">
            <el-table-column prop="pieceQuantity" label="تعداد قطعه" width="" align="center"> </el-table-column>
          </template>

          <template v-if="type === 'gr'">
            <el-table-column prop="recieveDate" label="تاریخ دریافت" width="" align="center">
              <template slot-scope="scope">
                <span>{{ $jDate(scope.row.recieveDate) }}</span>
              </template>
            </el-table-column>

            <el-table-column prop="deliverDate" label="تاریخ تحویل" width="" align="center">
              <template slot-scope="scope">
                <span>{{ $jDate(scope.row.deliverDate) }}</span>
              </template>
            </el-table-column>
          </template>

          <el-table-column label="اطلاعات" width="70" align="center">
            <template slot-scope="scope">
              <nuxt-link :to="formViewLink(type === 'inbox' ? scope.row : scope.row.formId)" target="_blank">
                <button class="showDetailsBtn" title="مشاهده فرم مربوطه">
                  <i class="fas fa-info"></i>
                </button>
              </nuxt-link>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </user-dashboard-container>
</template>

<script>
import moment from 'moment-jalaali'
export default {
  name: 'AccountAgentReports',
  layout: 'user',
  data() {
    return {
      type: '',
      reporting: false,
      reportIsReady: false,
      fetchingData: false,
      rawData: [],
      pieces: [],
      result: {
        mode: 'item',
        list: [],
        ffs: [],
        totalFormsCount: 0,
        filteredFormsCount: 0,
        totalItemsCount: 0,
        filteredItemsCount: 0
      },
      selectedItem: '',
      reportParams: {
        // form filters
        fromDate: '',
        toDate: '',
        formStatus: '',

        // items filters
        ItemID: '',
        ItemCode: '',
        pieceId: '',
        gStatus: '',

        // pr | opr
        fromItemReceptionTransDate: '',
        toItemReceptionTransDate: '',

        // gr
        fromRecieveDate: '',
        toRecieveDate: '',
        fromDeliverDate: '',
        toDeliverDate: ''
      }
    }
  },
  computed: {
    formsChartData() {
      const totalFormsLabel = 'کل فرم ها'
      const filteredFormsLabel = 'فرم های فیلتر شده'

      const totalFormsPercentage = 100
      const filteredFormsPercentage = Number(
        ((this.result.filteredFormsCount * 100) / this.result.totalFormsCount).toFixed(2)
      )
      return {
        labels: [totalFormsLabel, filteredFormsLabel],
        datasets: [
          {
            backgroundColor: ['#4e80a9', '#79aeba'],
            data: [totalFormsPercentage - filteredFormsPercentage, filteredFormsPercentage]
          }
        ]
      }
    },
    itemsChartData() {
      const totalFormsLabel = 'کل آیتم ها'
      const filteredFormsLabel = 'آیتم های فیلتر شده'

      const totalItemsPercentage = 100
      const filteredItemsPercentage = Number(
        ((this.result.filteredItemsCount * 100) / this.result.totalItemsCount).toFixed(2)
      )
      return {
        labels: [totalFormsLabel, filteredFormsLabel],
        datasets: [
          {
            backgroundColor: ['#4e80a9', '#79aeba'],
            data: [totalItemsPercentage - filteredItemsPercentage, filteredItemsPercentage]
          }
        ]
      }
    },
    verityProducts() {
      return this.$store.state.front.verityProducts
    },
    panatechProducts() {
      return this.$store.state.front.panatechProducts
    },
    /// ///// 'from' range dates for watch and reset 'to' dates
    fromDate() {
      return this.reportParams.fromDate
    },
    fromItemReceptionTransDate() {
      return this.reportParams.fromItemReceptionTransDate
    },
    fromRecieveDate() {
      return this.reportParams.fromRecieveDate
    },
    fromDeliverDate() {
      return this.reportParams.fromDeliverDate
    }
  },
  watch: {
    async type(newVal, oldVal) {
      try {
        // change states
        this.fetchingData = true
        // reset report params
        this.reportParams.fromDate = ''
        this.reportParams.toDate = ''
        this.reportParams.formStatus = ''

        this.reportParams.ItemID = ''
        this.reportParams.ItemCode = ''
        this.reportParams.pieceId = ''
        this.reportParams.gStatus = ''

        this.reportParams.fromItemReceptionTransDate = ''
        this.reportParams.toItemReceptionTransDate = ''
        this.reportParams.fromRecieveDate = ''
        this.reportParams.toRecieveDate = ''
        this.reportParams.fromDeliverDate = ''
        this.reportParams.toDeliverDate = ''

        // reset results
        this.reportIsReady = false
        this.result.mode = 'item'
        this.result.list = []
        this.result.ffs = []
        this.result.totalFormsCount = 0
        this.result.filteredFormsCount = 0
        this.result.totalItemsCount = 0
        this.result.filteredItemsCount = 0

        // fetch data
        if (newVal === 'inbox') {
          const transactions = await this.$axios.get('/api/agent/inbox')
          this.rawData = transactions.data
        }
        if (newVal === 'pr') {
          const pieceRequests = await this.$axios.get('/api/agent/prList')
          const sentForms = []
          for await (const item of pieceRequests.data) {
            if (item.status !== 'temp') sentForms.push(item)
          }
          this.rawData = sentForms
        }
        if (newVal === 'opr') {
          const oldPieceRequests = await this.$axios.get('/api/agent/oprList')
          const sentForms = []
          for await (const item of oldPieceRequests.data) {
            if (item.status !== 'temp') sentForms.push(item)
          }
          this.rawData = sentForms
        }
        if (newVal === 'br') {
          const bufferRequests = await this.$axios.get('/api/agent/brList')
          const sentForms = []
          for await (const item of bufferRequests.data) {
            if (item.status !== 'temp') sentForms.push(item)
          }
          this.rawData = sentForms
        }
        if (newVal === 'gr') {
          const guaranteeReports = await this.$axios.get('/api/agent/grList')
          const sentForms = []
          for await (const item of guaranteeReports.data) {
            if (item.status !== 'temp') sentForms.push(item)
          }
          this.rawData = sentForms
        }
        this.fetchingData = false
      } catch (e) {
        console.log(e)
      }
    },
    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 {
        this.reportParams.ItemID = ''
        this.reportParams.ItemCode = ''
        return
      }

      // 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.reportParams.ItemID = item?.ItemID
      this.reportParams.ItemCode = item?.ItemCode
    },
    /// /// watch these to reset 'to' patam
    fromDate() {
      this.reportParams.toDate = ''
    },
    fromItemReceptionTransDate() {
      this.reportParams.toItemReceptionTransDate = ''
    },
    fromRecieveDate() {
      this.reportParams.toRecieveDate = ''
    },
    fromDeliverDate() {
      this.reportParams.toDeliverDate = ''
    }
  },
  mounted() {
    this.$axios
      .get('/api/agent/pieces')
      .then(res => {
        this.fetchingPieces = false
        this.pieces = res.data
      })
      .catch(err => {
        console.log(err)
      })
  },
  methods: {
    getItemName(ItemID, db_name) {
      let products
      if (db_name === 'verity') products = this.verityProducts
      if (db_name === 'panatech') products = this.panatechProducts
      return products.find(item => item.ItemID === ItemID)?.ItemName
    },
    async getReport() {
      try {
        this.reporting = true
        this.reportIsReady = false

        // converts date to timeStamp
        async function timeStamp(date) {
          try {
            return Number(await moment(date).format('x'))
          } catch (e) {
            console.log(e)
          }
        }

        // report params reference
        const rep = this.reportParams

        /// ///////////////// filter date ranges
        // form date ranges
        const fromDate = await timeStamp(rep.fromDate)
        const toDate = (await timeStamp(rep.toDate)) + 1000 * 60 * 60 * 24

        // trnx item date ranges
        const fromRTRXDate = await timeStamp(rep.fromItemReceptionTransDate)
        const toRTRXDate = (await timeStamp(rep.toItemReceptionTransDate)) + 1000 * 60 * 60 * 24

        // gr item date ranges
        const fromGrR_Date = await timeStamp(rep.fromRecieveDate)
        const toGrR_Date = (await timeStamp(rep.toRecieveDate)) + 1000 * 60 * 60 * 24

        const fromGrD_Date = await timeStamp(rep.fromDeliverDate)
        const toGrD_Date = (await timeStamp(rep.toDeliverDate)) + 1000 * 60 * 60 * 24

        // filtered forms & items at the beginning
        let filteredForms = this.rawData
        let formFilteredItems = []

        // calculate total forms & items counts
        this.result.totalFormsCount = this.rawData.length
        let totalItemsCount = 0
        for await (const _form of this.rawData) {
          /* eslint-disable-next-line no-unused-vars */
          for await (const item of _form.items) {
            totalItemsCount++
          }
        }
        this.result.totalItemsCount = totalItemsCount

        // filtered forms count
        const FFS = new Set()

        /// ////////////////////////////////////////////////////////////////////////////////////

        /// ///////////////////////////////////// forms
        // filter forms by transaction status
        if (rep.formStatus) {
          const temp = [...filteredForms]
          filteredForms = []
          for await (const item of temp) {
            if (item.status === rep.formStatus) filteredForms.push(item)
          }
        }

        // filter forms grater than fromDate
        if (rep.fromDate) {
          const temp = [...filteredForms]
          filteredForms = []
          for await (const item of temp) {
            const sendDate = this.type === 'inbox' ? item.TempReceiptTransDate : item.sendDate
            if ((await timeStamp(sendDate)) >= fromDate) filteredForms.push(item)
          }
        }

        // filter forms less than toDate
        if (rep.toDate) {
          const temp = [...filteredForms]
          filteredForms = []
          for await (const item of temp) {
            const sendDate = this.type === 'inbox' ? item.TempReceiptTransDate : item.sendDate
            if ((await timeStamp(sendDate)) < toDate) filteredForms.push(item)
          }
        }

        /// ///////////////////////////////////// items
        /// ////////// generate report for inbox
        if (this.type === 'inbox') {
          /// ///////////////// items in forms
          // create array of individual items from all filtered forms
          for await (const trsx of filteredForms) {
            FFS.add(trsx._id)
            for await (const item of trsx.items) {
              formFilteredItems.push({
                ItemID: item.ItemID,
                ItemCode: item.ItemCode,
                MjQty: item.MjQty,
                db_name: trsx.db_name,
                tid: trsx._id,
                ttn: trsx.TempReceiptTransNumber,
                atn: trsx.ItemReceptionTransNumber
              })
            }
          }

          // filter items array by selectedItem
          if (rep.ItemID && rep.ItemCode) {
            const temp = [...formFilteredItems]
            formFilteredItems = []
            FFS.clear()
            for await (const item of temp) {
              if (item.ItemID === rep.ItemID && item.ItemCode === rep.ItemCode) {
                formFilteredItems.push(item)
                FFS.add(item.tid)
              }
            }
          }
        }
        /// ////////// genereate report for others
        else {
          /// ///////////////// items in forms
          // create array of individual items from all filtered forms
          for await (const form of filteredForms) {
            FFS.add(form._id)
            for await (const item of form.items) {
              const data = {
                ItemName: item.ItemName,
                ItemID: item.ItemID,
                ItemCode: item.ItemCode,
                formId: form._id
              }
              if (this.type === 'pr' || this.type === 'opr') {
                data.pieceName = item.pieceName
                data.pieceCode = item.pieceCode
                data.pieceQuantity = item.pieceQuantity
                data.pieceId = item.pieceId
                data.ItemReceptionTransDate = item.ItemReceptionTransDate
              }
              if (this.type === 'pr') {
                data.gStatus = item.gStatus
              }
              if (this.type === 'br') {
                data.bufferQuantity = item.bufferQuantity
              }
              if (this.type === 'gr') {
                data.recieveDate = item.recieveDate
                data.deliverDate = item.deliverDate
              }

              formFilteredItems.push(data)
            }
          }

          // filter items array by selectedItem
          if (rep.ItemID && rep.ItemCode) {
            const temp = [...formFilteredItems]
            formFilteredItems = []
            FFS.clear()
            for await (const item of temp) {
              if (item.ItemID === rep.ItemID && item.ItemCode === rep.ItemCode) {
                formFilteredItems.push(item)
                FFS.add(item.formId)
              }
            }
          }

          // filter items array by selected piece
          if (rep.pieceId) {
            const temp = [...formFilteredItems]
            formFilteredItems = []
            FFS.clear()
            for await (const item of temp) {
              if (item.pieceId === rep.pieceId) {
                formFilteredItems.push(item)
                FFS.add(item.formId)
              }
            }
          }

          // filter items array by selected item gStatus
          if (rep.gStatus !== '') {
            const temp = [...formFilteredItems]
            formFilteredItems = []
            FFS.clear()
            for await (const item of temp) {
              if (item.gStatus === rep.gStatus) {
                formFilteredItems.push(item)
                FFS.add(item.formId)
              }
            }
          }

          // filter items array by selected fromItemReceptionTransDate
          if (rep.fromItemReceptionTransDate) {
            const temp = [...formFilteredItems]
            formFilteredItems = []
            FFS.clear()
            for await (const item of temp) {
              if ((await timeStamp(item.ItemReceptionTransDate)) >= fromRTRXDate) {
                formFilteredItems.push(item)
                FFS.add(item.formId)
              }
            }
          }

          // filter items array by selected toItemReceptionTransDate
          if (rep.toItemReceptionTransDate) {
            const temp = [...formFilteredItems]
            formFilteredItems = []
            FFS.clear()
            for await (const item of temp) {
              if ((await timeStamp(item.ItemReceptionTransDate)) < toRTRXDate) {
                formFilteredItems.push(item)
                FFS.add(item.formId)
              }
            }
          }

          // filter items array by selected fromRecieveDate
          if (rep.fromRecieveDate) {
            const temp = [...formFilteredItems]
            formFilteredItems = []
            FFS.clear()
            for await (const item of temp) {
              if ((await timeStamp(item.recieveDate)) >= fromGrR_Date) {
                formFilteredItems.push(item)
                FFS.add(item.formId)
              }
            }
          }

          // filter items array by selected toRecieveDate
          if (rep.toRecieveDate) {
            const temp = [...formFilteredItems]
            formFilteredItems = []
            FFS.clear()
            for await (const item of temp) {
              if ((await timeStamp(item.recieveDate)) < toGrR_Date) {
                formFilteredItems.push(item)
                FFS.add(item.formId)
              }
            }
          }

          // filter items array by selected fromDeliverDate
          if (rep.fromDeliverDate) {
            const temp = [...formFilteredItems]
            formFilteredItems = []
            FFS.clear()
            for await (const item of temp) {
              if ((await timeStamp(item.deliverDate)) >= fromGrD_Date) {
                formFilteredItems.push(item)
                FFS.add(item.formId)
              }
            }
          }

          // filter items array by selected toDeliverDate
          if (rep.toDeliverDate) {
            const temp = [...formFilteredItems]
            formFilteredItems = []
            FFS.clear()
            for await (const item of temp) {
              if ((await timeStamp(item.deliverDate)) < toGrD_Date) {
                formFilteredItems.push(item)
                FFS.add(item.formId)
              }
            }
          }
        }

        // filter forms by IDs in FFS
        const ffsDetails = [...filteredForms]
        filteredForms = []
        for await (const _form of ffsDetails) {
          if (FFS.has(_form._id)) filteredForms.push(_form)
        }

        /// ////////////////////////////////////////////////////////////////////////////////////
        this.result.filteredFormsCount = FFS.size
        this.result.filteredItemsCount = formFilteredItems.length
        this.result.list = formFilteredItems
        this.result.ffs = filteredForms
        this.reporting = false
        this.reportIsReady = true
      } catch (e) {
        console.log(e)
      }
    },
    formViewLink(id) {
      if (this.type === 'inbox') {
        if (this.result.mode === 'item') {
          return {
            name: 'account-agents-inbox-view',
            query: {
              tid: id.tid,
              ttn: id.ttn,
              atn: id.atn || undefined,
              db_name: id.db_name
            }
          }
        }
        if (this.result.mode === 'form') {
          return {
            name: 'account-agents-inbox-view',
            query: {
              tid: id._id,
              ttn: id.TempReceiptTransNumber,
              atn: id.ItemReceptionTransNumber || undefined,
              db_name: id.db_name
            }
          }
        }
      }

      if (this.type === 'pr') {
        return {
          name: 'account-agents-pieces-pr',
          params: {
            pr: id
          }
        }
      }
      if (this.type === 'opr') {
        return {
          name: 'account-agents-ops-op',
          params: {
            op: id
          }
        }
      }
      if (this.type === 'br') {
        return {
          name: 'account-agents-buffer-br',
          params: {
            br: id
          }
        }
      }
      if (this.type === 'gr') {
        return {
          name: 'account-agents-guaranteeReports-gr',
          params: {
            gr: id
          }
        }
      }
    },
    async validateDateRange(type) {
      async function timeStamp(date) {
        try {
          return Number(await moment(date).format('x'))
        } catch (e) {
          console.log(e)
        }
      }
      try {
        if (type === 'toDate') {
          if (this.reportParams.fromDate) {
            const start = await timeStamp(this.reportParams.fromDate)
            const end = await timeStamp(this.reportParams.toDate)
            if (end < start) {
              this.reportParams.toDate = ''
              this.$message({
                type: 'warning',
                message: 'تاریخ پایان بازه نباید از شروع بازه بزرگتر باشد"'
              })
            }
          }
        }

        if (type === 'toItemReceptionTransDate') {
          if (this.reportParams.fromItemReceptionTransDate) {
            const start = await timeStamp(this.reportParams.fromItemReceptionTransDate)
            const end = await timeStamp(this.reportParams.toItemReceptionTransDate)
            if (end < start) {
              this.reportParams.toItemReceptionTransDate = ''
              this.$message({
                type: 'warning',
                message: 'تاریخ پایان بازه نباید از شروع بازه بزرگتر باشد"'
              })
            }
          }
        }

        if (type === 'toRecieveDate') {
          if (this.reportParams.fromRecieveDate) {
            const start = await timeStamp(this.reportParams.fromRecieveDate)
            const end = await timeStamp(this.reportParams.toRecieveDate)
            if (end < start) {
              this.reportParams.toRecieveDate = ''
              this.$message({
                type: 'warning',
                message: 'تاریخ پایان بازه نباید از شروع بازه بزرگتر باشد"'
              })
            }
          }
        }

        if (type === 'toDeliverDate') {
          if (this.reportParams.fromDeliverDate) {
            const start = await timeStamp(this.reportParams.fromDeliverDate)
            const end = await timeStamp(this.reportParams.toDeliverDate)
            if (end < start) {
              this.reportParams.toDeliverDate = ''
              this.$message({
                type: 'warning',
                message: 'تاریخ پایان بازه نباید از شروع بازه بزرگتر باشد"'
              })
            }
          }
        }
      } catch (e) {
        console.log(e)
      }
    }
  }
}
</script>
