<template>
  <div>
    <CustomSubHeader>
      <CBreadcrumb class="border-0 mb-0">{{ title }}</CBreadcrumb>
    </CustomSubHeader>

    <CCard>
      <CCardHeader>
        <slot name="header">
          <i class="fas fa-filter"></i>
          <b>فیلتر ها</b>
        </slot>
      </CCardHeader>

      <CCardBody>
        <CRow>
          <CCol sm="12">
            <div class="mb-5">
              <el-select v-model="selectedAgent" style="" clearable filterable placeholder="فیلتر بر اساس نماینده">
                <el-option-group label="نمایندگان فعال">
                  <el-option
                    v-for="item of agents"
                    :key="item._id"
                    :value="item._id"
                    :label="item.full_name + ' ' + `(نمایندگی ${item.city_name} - کد ${item.agent_code})`"
                  ></el-option>
                </el-option-group>

                <el-option-group label="نمایندگان صلب امتیاز شده">
                  <el-option
                    v-for="item of revokedAgents"
                    :key="item._id"
                    :value="item._id"
                    :label="item.full_name + ' ' + `(نمایندگی ${item.city_name} - کد ${item.agent_code})`"
                  ></el-option>
                </el-option-group>
              </el-select>

              <el-select
                v-model="selectedProvince"
                style=""
                :disabled="Boolean(selectedAgent)"
                clearable
                filterable
                placeholder="فیلتر بر اساس استان"
              >
                <el-option
                  v-for="item of iranProvinces"
                  :key="item.ProvinceID"
                  :value="item.ProvinceID"
                  :label="item.ProvinceName"
                ></el-option>
              </el-select>

              <el-select
                v-model="selectedCity"
                style=""
                :disabled="Boolean(selectedAgent)"
                clearable
                filterable
                placeholder="فیلتر بر اساس شهر"
              >
                <el-option
                  v-for="item of filteredCities"
                  :key="item.CityID"
                  :value="item.CityID"
                  :label="item.CityName"
                ></el-option>
              </el-select>
            </div>
            <div class="statusBtns">
              <CButtonGroup>
                <CButton
                  :color="filterType === 'all' ? 'primary' : 'light'"
                  :class="filterType === 'all' && 'selected'"
                  @click="filterType = 'all'"
                >
                  <span>همه</span>
                  <span> ({{ filteredItems.length }}) </span>
                </CButton>

                <CButton
                  :color="filterType === 'saved' ? 'primary' : 'light'"
                  :class="filterType === 'saved' && 'selected'"
                  @click="filterType = 'saved'"
                >
                  <span>جدید</span>
                  <span> ({{ getListCountByStatus('saved') }}) </span>
                </CButton>

                <CButton
                  :color="filterType === 'recieved' ? 'primary' : 'light'"
                  :class="filterType === 'recieved' && 'selected'"
                  @click="filterType = 'recieved'"
                >
                  <span>پذیرش شده</span>
                  <span> ({{ getListCountByStatus('recieved') }}) </span>
                </CButton>

                <CButton
                  :color="filterType === 'ongoing' ? 'primary' : 'light'"
                  :class="filterType === 'ongoing' && 'selected'"
                  @click="filterType = 'ongoing'"
                >
                  <span>در دست اقدام</span>
                  <span> ({{ getListCountByStatus('ongoing') }}) </span>
                </CButton>

                <CButton
                  :color="filterType === 'waiting' ? 'primary' : 'light'"
                  :class="filterType === 'waiting' && 'selected'"
                  @click="filterType = 'waiting'"
                >
                  <span>در انتظار قطعه</span>
                  <span> ({{ getListCountByStatus('waiting') }} )</span>
                </CButton>

                <CButton
                  :color="filterType === 'delivered' ? 'primary' : 'light'"
                  :class="filterType === 'delivered' && 'selected'"
                  @click="filterType = 'delivered'"
                >
                  <span>تحویل شده</span>
                  <span> ({{ getListCountByStatus('delivered') }}) </span>
                </CButton>
              </CButtonGroup>
            </div>
          </CCol>
          <CCol sm="12">
            <el-divider></el-divider>
          </CCol>
          <CCol sm="12">
            <h4>جستجو در لیست:</h4>
            <el-input
              v-model="filterText"
              clearable
              placeholder="کد پذیرش موقت - کد پذیرش دائم - کد مشتری"
              style="display: inline-block; max-width: 500px; margin-top: 8px"
            ></el-input>
          </CCol>
        </CRow>
      </CCardBody>
    </CCard>

    <CCard>
      <CCardHeader>
        <slot name="header">
          <CIcon name="cil-grid" />
          {{ list_title }}
        </slot>
      </CCardHeader>

      <CCardBody>
        <el-table
          :data="filteredItems"
          style="width: 100%"
          :row-class-name="({ row, rowIndex }) => row.status === 'saved' && 'unread'"
        >
          <el-table-column type="index" label="#"> </el-table-column>

          <el-table-column label="تاریخ ثبت درخواست" width="">
            <template slot-scope="scope">
              <span> {{ $jDate(scope.row.created_at) }} </span>
            </template>
          </el-table-column>

          <el-table-column prop="TempReceiptTransNumber" label="کد پذیرش موقت" width=""> </el-table-column>

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

          <el-table-column prop="user_id.province_name" label="استان" width=""> </el-table-column>

          <el-table-column prop="user_id.city_name" label="شهر" width=""> </el-table-column>

          <el-table-column prop="agent_id.agent_code" label="کد نماینده" width=""> </el-table-column>

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

          <el-table-column label="بررسی" width="65" align="center">
            <template slot-scope="scope">
              <CButton
                :key="scope.row._id"
                color="success"
                variant="outline"
                :to="{ name: 'admin-agentsInbox-tr', params: { tr: scope.row._id } }"
              >
                <i class="fal fa-eye"></i>
              </CButton>
            </template>
          </el-table-column>
        </el-table>
      </CCardBody>
    </CCard>
  </div>
</template>

<script>
export default {
  name: 'AdminAgentsInboxList',
  layout: 'admin',
  async asyncData({ $axios, error }) {
    try {
      const transactions = await $axios.get('/api/admin/allAgentsInbox')
      const agents = await $axios.get('/api/public/agents')
      const revokedAgents = await $axios.get('/api/admin/revokedAgents')
      return {
        transactions: transactions.data,
        agents: agents.data,
        revokedAgents: revokedAgents.data
      }
    } catch (err) {
      error({ status: 404, message: 'There is a problem here' })
    }
  },
  data() {
    return {
      title: 'صندوق ورودی نمایندگان',
      list_title: 'لیست',
      transactions: null,
      agents: null,
      revokedAgents: null,
      filterText: '',
      selectedAgent: '',
      selectedProvince: '',
      selectedCity: ''
    }
  },
  head() {
    return {
      title: this.title
    }
  },
  computed: {
    iranProvinces() {
      return this.$store.state.admin.iranProvinces
    },
    iranCities() {
      return this.$store.state.admin.iranCities
    },
    filteredCities() {
      if (this.selectedProvince) {
        return this.iranCities.filter(item => item.ProvinceID === this.selectedProvince)
      } else return this.iranCities
    },
    filteredItems() {
      const filterStep1 = this.transactions.filter(item => {
        if (this.selectedAgent) {
          if (this.selectedAgent === item.agent_id?._id) return item
          return false
        } else return item
      })

      const filterStep2 = filterStep1.filter(item => {
        if (this.selectedProvince) {
          if (this.selectedProvince === item.user_id?.province_id) return item
          return false
        } else return item
      })

      const filterStep3 = filterStep2.filter(item => {
        if (this.selectedCity) {
          if (this.selectedCity === item.user_id?.city_id) return item
          return false
        } else return item
      })

      const filterByStatus = filterStep3.filter(item =>
        this.filterType === 'all' ? item : item.status === this.filterType
      )
      const filterText = this.filterText
      if (!this.filterText.length) return filterByStatus
      else
        return filterByStatus.filter(item => {
          return (
            item.TempReceiptTransNumber.includes(filterText) ||
            item.ItemReceptionTransNumber.includes(filterText) ||
            item.user_id.verity_businessCode.includes(filterText) ||
            item.user_id.panatech_businessCode.includes(filterText)
          )
        })
    },
    filterType: {
      get() {
        return this.$route.query.status
      },
      set(val) {
        this.$router.push({ name: 'admin-agentsInbox', query: { status: val } })
      }
    }
  },
  watch: {
    selectedProvince(newVal, oldVal) {
      this.selectedCity = ''
    },
    selectedAgent(newVal, oldVal) {
      this.selectedProvince = ''
      this.selectedCity = ''
    }
  },
  methods: {
    getListCountByStatus(status) {
      return this.filteredItems.filter(item => item.status === status).length
    }
  }
}
</script>

<style lang="scss" scopped>
.statusBtns {
  .selected {
    -webkit-transform: scale(1.1);
    -moz-transform: scale(1.1);
    -ms-transform: scale(1.1);
    -o-transform: scale(1.1);
    transform: scale(1.1);
    z-index: 2;

    span {
      color: #fff;
    }
  }
}

.unread {
  background: rgba(orange, 0.1) !important;
}
</style>
