<template>
  <div>
    <CustomSubHeader>
      <CBreadcrumb class="border-0 mb-0"> دستگاه های نصب شده</CBreadcrumb>
    </CustomSubHeader>

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

          <CCardBody>
            <CRow>
              <CCol sm="12">
                <CButtonGroup>
                  <CButton color="primary" :class="filterType === 'all' && 'selected'" @click="filterType = 'all'"
                    >همه</CButton
                  >
                  <CButton color="danger" :class="filterType === 'rej' && 'selected'" @click="filterType = 'rej'"
                    >رد شده</CButton
                  >
                  <CButton color="success" :class="filterType === 'accept' && 'selected'" @click="filterType = 'accept'"
                    >تایید شده</CButton
                  >
                  <CButton color="warning" :class="filterType === 'pend' && 'selected'" @click="filterType = 'pend'"
                    >درانتظار تایید</CButton
                  >
                </CButtonGroup>
              </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>
      </CCol>
    </CRow>

    <CCard>
      <CCardHeader>
        <slot name="header">
          <CIcon name="cil-grid" />
          دستگاه های نصب شده
        </slot>
      </CCardHeader>

      <CCardBody>
        <el-table :data="devices" :row-class-name="hasUnread" style="width: 100%" v-loading="loading">
          <el-table-column type="index" label="#"> </el-table-column>

          <el-table-column label="مدل" width="150px">
            <template slot-scope="scope">
              {{ scope?.row?.deviceId?.model }}
              {{ scope?.row?.deviceType }}
            </template>
          </el-table-column>
          <el-table-column prop="IMEI" label=" IMEI" width="150px"> </el-table-column>

          <el-table-column label="نام فروشگاه" width="">
            <template slot-scope="scope">
              {{ scope?.row?.userId?.shopName }}
            </template>
          </el-table-column>
          <el-table-column label="کدملی فروشنده" width="">
            <template slot-scope="scope">
              {{ scope?.row?.userId?.national_code }}
            </template>
          </el-table-column>
          <el-table-column label=" نام و نام خانوادگی" width="">
            <template slot-scope="scope">
              {{ scope?.row?.userId?.first_name + ' ' + scope?.row?.userId?.last_name }}
            </template>
          </el-table-column>
          <el-table-column label=" شماره همراه" width="">
            <template slot-scope="scope">
              {{ scope?.row?.userId?.mobile_number }}
            </template>
          </el-table-column>

          <el-table-column label="محل سکونت" width="">
            <template slot-scope="scope">
              {{ getLocationText(scope?.row?.userId) }}
            </template>
          </el-table-column>

          <el-table-column label="وضعیت" width="">
            <template slot-scope="scope">
              <el-tag v-if="scope?.row?.status == 2" type="danger"> رد شده</el-tag>
              <el-tag v-if="scope?.row?.status == 1" type="success">تایید شده</el-tag>

              <el-tag v-if="scope?.row?.status == 0" type="warning"> درانتظار تایید</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="تایید" width="110" align="center">
            <template slot-scope="scope">
              <!-- <CButton
                v-if="scope?.row?.status == 0 || scope?.row?.status == 2"
                :key="scope?.row?._id"
                color="success"
                variant="outline"
                @click="post(scope?.row?._id, 'accept')"
              >
                <i class="fa fa-check-square"></i>
              </CButton> -->
              <CButton
                v-if="scope?.row?.status == 0 || scope?.row?.status == 1"
                :key="scope?.row?._id"
                color="danger"
                variant="outline"
                @click="post(scope?.row?._id, 'reject')"
              >
                <i class="fa fa-window-close"></i>
              </CButton>
            </template>
          </el-table-column>
        </el-table>
        <div style="direction:ltr; textAlign:center; marginTop:20px;">
          <el-pagination
            v-if="paginate"
            background
            layout="prev, pager, next"
            :current-page="currentPage"
            :page-count="totalPages"
            @current-change="handlePageChange"
          >
          </el-pagination>
        </div>
      </CCardBody>
    </CCard>
  </div>
</template>

<script>
export default {
  name: 'AdminGpsInstalledDevicesList',
  layout: 'admin',
  async asyncData({ $axios, error, query }) {
    try {
      const page = parseInt(query.page) || 1
      const rows = parseInt(query.rows) || 10
      
      const params = {
        page,
        rows
      }
      if (query.filter) params.filter = query.filter
      if (query.search) params.search = query.search

      const { data } = await $axios.get('/api/admin/gps/register-device', { params })

      return {
        devices: data.data || [],
        totalDocuments: data.totalDocuments || 0,
        totalPages: data.totalPages || 1
      }
    } catch (error) {
      console.log(error)
      return {
        devices: [],
        totalDocuments: 0,
        totalPages: 1
      }
    }
  },
  data() {
    return {
      devices: [],
      device: {},
      filterText: this.$route.query?.search || '',
      loading: false,
      searchTimeout: null,
      pageSize: 10,
      totalDocuments: 0,
      totalPages: 1
    }
  },

  computed: {
    config() {
      return this.$config
    },
    currentPage() {
      return parseInt(this.$route.query?.page) || 1
    },
    paginate() {
      return this.totalPages > 1
    },
    filterType: {
      get() {
        return this.$route.query?.filter || 'all'
      },
      set(val) {
        const query = { ...this.$route.query, filter: val, page: 1 }
        if (!this.filterText) delete query.search
        else query.search = this.filterText
        this.$router.push({ name: 'admin-gps-installed-device', query })
      }
    }
  },
  watch: {
    '$route.query': {
      handler(newQuery, oldQuery) {
        // Sync filterText with route query
        if (newQuery.search !== this.filterText) {
          this.filterText = newQuery.search || ''
        }
        // Only fetch if query actually changed (not on initial mount)
        if (oldQuery && (
          newQuery.filter !== oldQuery.filter || 
          newQuery.search !== oldQuery.search ||
          newQuery.page !== oldQuery.page
        )) {
          this.fetchData()
        }
      },
      deep: true,
      immediate: false
    },
    filterText(newVal) {
      // Debounce search to avoid too many requests
      if (this.searchTimeout) {
        clearTimeout(this.searchTimeout)
      }
      this.searchTimeout = setTimeout(() => {
        const query = { ...this.$route.query, page: 1 }
        if (newVal) {
          query.search = newVal
        } else {
          delete query.search
        }
        // Only update route if it's different to avoid unnecessary navigation
        if (query.search !== this.$route.query.search || query.page !== this.$route.query.page) {
          this.$router.push({ name: 'admin-gps-installed-device', query })
        }
      }, 500) // 500ms debounce
    }
  },
  methods: {
    getLocationText(user) {
      if (!user) return ''
      
      const province = typeof user.province_name === 'string' 
        ? user.province_name 
        : user.province_name?.provinceName || ''
      
      const city = typeof user.city_name === 'string' 
        ? user.city_name 
        : user.city_name?.cityName || ''
      
      return [province, city].filter(Boolean).join(', ') || '-'
    },
    async fetchData() {
      this.loading = true
      try {
        const page = this.currentPage
        const params = {
          page,
          rows: this.pageSize
        }
        if (this.$route.query.filter) params.filter = this.$route.query.filter
        if (this.$route.query.search) params.search = this.$route.query.search

        const { data } = await this.$axios.get('/api/admin/gps/register-device', { params })
        this.devices = data.data || []
        this.totalDocuments = data.totalDocuments || 0
        this.totalPages = data.totalPages || 1
      } catch (error) {
        console.error('Error fetching devices:', error)
        this.$message({
          type: 'error',
          message: 'خطا در دریافت اطلاعات'
        })
      } finally {
        this.loading = false
      }
    },
    handlePageChange(page) {
      this.$router.push({
        name: 'admin-gps-installed-device',
        query: {
          ...this.$route.query,
          page
        }
      })
    },
    hasUnread({ row, rowIndex }) {
      return row.status === 0 ? 'unreadMsgInCv' : null
    },
    post(id, status) {
      this.$axios
        .patch(`/api/admin/gps/register-device/${id}/${status}`, {})
        .then(res => {
          this.$message({
            type: 'success',
            message: res.data.msg
          })
          this.fetchData()
        })
        .catch(err => {
          if (err.response && err.response.data && err.response.data.status === 401) {
            return this.$message({
              type: 'warning',
              message: 'لطفا دوباره وارد حساب خود شوید'
            })
          }
          if (err.response && err.response.status === 422) this.validation = err.response.data.validation
          else {
            console.log(err)
            return this.$message({
              type: 'warning',
              message: err.msg || 'خطا در انجام عملیات'
            })
          }
        })
    }
  }
}
</script>
<style>
.unreadMsgInCv {
  background: rgba(orange, 0.1) !important;
}
</style>
