
<template>
  <div>
    <el-dialog dir="rtl" title="اطلاعات کاربر" :visible.sync="centerDialogVisible" width="40%" center>
      <el-descriptions title=""  direction="vertical" :column="4" border>
        <el-descriptions-item label="نام">
          <input class="editInput" type="text" v-model="newUser.first_name" />
        </el-descriptions-item>
        <el-descriptions-item label="نام خانودگی">
          <input class="editInput" type="text" v-model="newUser.last_name" />
        </el-descriptions-item>
        <el-descriptions-item label="شماره همراه">
          <input class="editInput" type="text" v-model="newUser.mobile_number" />
        </el-descriptions-item>
        <el-descriptions-item label="استان">{{ user.province_name?.provinceName }}</el-descriptions-item>
        <el-descriptions-item label="شهر">{{ user.city_name?.cityName }}</el-descriptions-item>
        <el-descriptions-item label="کد ملی ">
          <input class="editInput" type="text" v-model="newUser.national_code" />
          </el-descriptions-item>
        <el-descriptions-item label="نام فروشگاه">
          <input class="editInput" type="text" v-model="newUser.shopName" />
        </el-descriptions-item>
        <el-descriptions-item label="شماره ثابت">
          <input class="editInput" type="text" v-model="newUser.cell_number" />
        </el-descriptions-item>
        <el-descriptions-item label="تاریخ تولد">
          <input class="editInput" type="text" v-model="newUser.birthDate" />
        </el-descriptions-item>
        <el-descriptions-item label="آدرس">
          <input class="editInput" type="text" v-model="newUser.address" />
          </el-descriptions-item>
      </el-descriptions>
      <CCardBody>
        <el-table :data="user.cardBank" style="width: 100%">
          <el-table-column type="index" label="#"> </el-table-column>
          <el-table-column prop="holderName" label="نام صاحب کارت" width="200px"> </el-table-column>
          <el-table-column prop="PAN" label="شماره حساب" width="200px"> </el-table-column>
          <el-table-column prop="IBAN" label="شماره شبا" width=""> </el-table-column>
        </el-table>
      </CCardBody>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">{{ $route.query?.type == 'req' ? 'بستن' : 'بستن' }}</el-button>
        <el-button @click="update_user">{{ $route.query?.type == 'req' ? 'ذخیره' : 'ذخیره' }}</el-button>
        <el-button v-if="$route.query?.type == 'req'" type="primary" @click="confirmUser(user._id)">تایید</el-button>
      </span>
    </el-dialog>

    <CustomSubHeader>
      <CBreadcrumb class="border-0 mb-0"> کاربران جی پی اس </CBreadcrumb>
      <CButton size="sm" color="success" :to="{ name: 'admin-gps-users-user', params: { user: 'new' } }" class="mr-auto"
        >افزودن</CButton
      >
    </CustomSubHeader>

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

      <CCardBody>
        <CRow>
          <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" />
          کاربران
        </slot>
      </CCardHeader>

      <CCardBody>
        <el-table :data="filteredItems" style="width: 100%">
          <el-table-column type="index" label="#"> </el-table-column>

          <el-table-column prop="first_name" label="نام" width="200px"> </el-table-column>
          <el-table-column prop="last_name" label="نام خانوادگی" width="200px"> </el-table-column>

          <el-table-column prop="national_code" label="کدملی" width=""> </el-table-column>

          <el-table-column prop="mobile_number" label="شماره همراه" width=""> </el-table-column>

          <el-table-column label="وضعیت" width="">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.active" type="success">فعال</el-tag>
              <el-tag v-else type="danger">غیر فعال</el-tag>
            </template>
          </el-table-column>

          <el-table-column label="نمایش" width="110" align="center">
            <template slot-scope="scope">
              <CButton :key="scope.row._id" color="info" variant="outline" @click="showUserDialog(scope.row._id)">
                <i class="fal fa-eye"></i>
              </CButton>
            </template>
          </el-table-column>
        </el-table>
      </CCardBody>
    </CCard>
  </div>
</template>


<script>
export default {
  name: 'AdminGpsUsersList',
  layout: 'admin',
  async asyncData({ $axios, error, query }) {
    try {
      let users
      // eslint-disable-next-line eqeqeq
      if (query?.type == 'req') {
        users = await $axios.get('/api/admin/gps/users/pending')
      } else {
        users = await $axios.get('/api/admin/gps/users')
      }
      return {
        users: users.data
      }
    } catch (error) {
      console.log(error)
    }
  },
  data() {
    return {
      users: [],
      centerDialogVisible: false,
      user: {},
      filterText: '',
      newUser: {}
    }
  },

  computed: {
    config() {
      return this.$config
    },
    usersTypeList() {
      return this.$route.query?.type
    },
    filteredItems() {
      const filterText = this.filterText
      if (!this.filterText.length) return this.users
      else {
        return this.users.filter(item => {
          return (
            item.first_name.includes(filterText) ||
            item.last_name.includes(filterText) ||
            item.mobile_number.includes(filterText) ||
            item.national_code.includes(filterText) ||
            item.province_name?.includes(filterText) ||
            item.city_name?.includes(filterText) ||
            (item.first_name + ' ' + item.last_name).includes(filterText)
          )
        })
      }
    }
  },
  watch: {
    async usersTypeList(newVal, oldVal) {
      try {
        let users
        // eslint-disable-next-line eqeqeq
        if (this.$route.query?.type == 'req') {
          users = await this.$axios.get('/api/admin/gps/users/pending')
        } else {
          users = await this.$axios.get('/api/admin/gps/users')
        }

        this.users = users.data
      } catch (error) {
        console.log(error)
      }
    }
  },
  methods: {
    //  edit_form() {
    //   this.newUser = 'this.user.first_name'
    //   console.log(this.user.first_name);
    //   console.log(this.newUser);

    // },

    async showUserDialog(id) {
      const { data } = await this.$axios.get(`/api/admin/gps/users/${id}`)
      console.log(data)

      this.user = data
      this.centerDialogVisible = true
      this.newUser = {
        first_name: data?.first_name ?? '',
        last_name: data?.last_name ?? '',
        national_code: data?.national_code ?? '',
        shopName: data?.shopName ?? '',
        mobile_number: data?.mobile_number ?? '',
        birthDate: data?.birthDate ?? '',
        cell_number: data?.cell_number ?? '',
        address: data?.address ?? ''
      }
    },
    async update_user() {
      try {
        const { data, status } = await this.$axios.put(`/api/admin/gps/users/${this.user.id}`, this.newUser)
        console.log('after changed', data, status)
        if(status === 200 || status === 201){
          this.$nuxt.refresh()
          this.centerDialogVisible = false
        }else{
           alert('خطا در برقراری ارتباط با سرور')
        }
      } catch (error) {
        alert(Object.values(error?.response?.data?.validation)[0]?.msg)
      //  console.log('after log', Object.values(error.response.data.validation)[0].msg)
      }
    },
    async confirmUser(id) {
      try {
        await this.$axios.patch(`/api/admin/gps/users/${id}/true`)
        this.$nuxt.refresh()
        this.centerDialogVisible = false
      } catch (err) {
        this.$message({
          type: 'error',
          message: err.response.data.message
        })
      }
    }
  }
}
</script>

<style>
.editInput {
  width: 100% !important;
  border: 1px solid rgb(214, 214, 214);
  padding: 2px;
  border-radius: 3px;
}

</style>