<template>
  <div>
    <CustomSubHeader>
      <CBreadcrumb class="border-0 mb-0">{{ title }}</CBreadcrumb>
      <CButton size="sm" color="success" class="mr-auto" @click="addAgentModal = true">
        <span style="color: #fff"> افزودن نماینده </span>
      </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" />
          {{ list_title }}
        </slot>
      </CCardHeader>

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

          <el-table-column prop="full_name" label="نام" width=""> </el-table-column>

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

          <el-table-column label="نوع نماینده" width="300">
            <template slot-scope="scope">
              <span v-if="scope.row.representation_type === 'both'">نماینده هر دو نوع لوازم</span>
              <span v-if="scope.row.representation_type === 'verity'">نماینده لوازم جانبی کامپیوتر و موبایل</span>
              <span v-if="scope.row.representation_type === 'panatech'">نماینده لوازم صوتی تصویری خودرو</span>
            </template>
          </el-table-column>

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

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

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

          <el-table-column label="مشاهده" width="70" align="center">
            <template slot-scope="scope">
              <CButton
                :key="scope.row._id"
                color="success"
                variant="outline"
                :to="{ name: 'admin-agents-agent', params: { agent: scope.row._id }, query: { ...$route.query } }"
              >
                <i class="fal fa-eye"></i>
              </CButton>
            </template>
          </el-table-column>
        </el-table>
      </CCardBody>
    </CCard>

    <el-dialog :visible.sync="addAgentModal">
      <CRow>
        <CCol lg="12" xl="12" md="12" style="margin-bottom: 10px">
          <h4>اضافه کردن نماینده با اکانت قبلی</h4>
          <el-select v-model="selectedUserForNewAgent" style="width: 100%" label="کاربر را انتخاب کنید" filterable>
            <el-option
              v-for="item in users"
              :key="item._id"
              :label="item.first_name + ' ' + item.last_name + ' (' + item.national_code + ')'"
              :value="item._id"
            ></el-option>
          </el-select>
          <br />
          <br />
          <el-button type="success" :disabled="!selectedUserForNewAgent" @click="addAgent">
            <span style="color: #fff">افزودن</span>
          </el-button>
        </CCol>
        <el-divider></el-divider>
        <CCol>
          <h4>اضافه کردن نماینده با اکانت جدید</h4>
          <CForm>
            <CInput
              v-model="registerData.first_name"
              label="نام"
              horizontal
              :description="validation.first_name ? validation.first_name.msg : null"
              :class="validation.first_name ? 'err' : null"
            />
            <CInput
              v-model="registerData.last_name"
              label="نام خانوادگی"
              horizontal
              :description="validation.last_name ? validation.last_name.msg : null"
              :class="validation.last_name ? 'err' : null"
            />
            <CInput
              v-model="registerData.national_code"
              label="کد ملی"
              horizontal
              :description="validation.national_code ? validation.national_code.msg : null"
              :class="validation.national_code ? 'err' : null"
            />
            <CInput
              v-model="registerData.mobile_number"
              label="شماره همراه"
              horizontal
              :description="validation.mobile_number ? validation.mobile_number.msg : null"
              :class="validation.mobile_number ? 'err' : null"
            />
            <CInput
              v-model="registerData.tel_number"
              label="شماره ثابت"
              horizontal
              :description="validation.tel_number ? validation.tel_number.msg : null"
              :class="validation.tel_number ? 'err' : null"
            />
            <CInput
              v-model="registerData.email"
              label="ایمیل "
              horizontal
              :description="validation.email ? validation.email.msg : null"
              :class="validation.email ? 'err' : null"
            />
            <CInput
              v-model="registerData.store_name"
              label="نام فروشگاه"
              horizontal
              :description="validation.store_name ? validation.store_name.msg : null"
              :class="validation.store_name ? 'err' : null"
            />
            <div
              style="
                display: flex;
                align-content: center;
                align-items: center;
                justify-content: space-between;
                margin-bottom: 15px;
              "
            >
              <label>استان</label>
              <el-select
                v-model="registerData.province_id"
                filterable
                placeholder="استان را انتخاب کنید"
                style="width: 75%"
              >
                <el-option
                  v-for="item in iranProvinces"
                  :key="item.ProvinceID"
                  :label="item.ProvinceName"
                  :value="item.ProvinceID"
                >
                </el-option>
              </el-select>
            </div>
            <p v-if="validation.province_id">{{ validation.province_id.msg }}</p>
            <div
              style="
                display: flex;
                align-content: center;
                align-items: center;
                justify-content: space-between;
                margin-bottom: 15px;
              "
            >
              <label style="padding-left: 10px">شهر </label>
              <el-select
                v-model="registerData.city_id"
                filterable
                :placeholder="provinceCities ? 'شهر را انتخاب کنید' : 'ابتدا استان را انتخاب کنید'"
                style="width: 75%"
              >
                <el-option
                  v-for="item in provinceCities"
                  :key="item.CityID"
                  :label="item.CityName"
                  :value="item.CityID"
                >
                </el-option>
              </el-select>
            </div>
            <p v-if="validation.city_id">{{ validation.city_id.msg }}</p>
            <CInput
              v-model="registerData.address"
              label="آدرس "
              horizontal
              :description="validation.address ? validation.address.msg : null"
              :class="validation.address ? 'err' : null"
            />
            <CInput
              v-model="registerData.postal_code"
              label="کد پستی "
              horizontal
              :description="validation.postal_code ? validation.postal_code.msg : null"
              :class="validation.postal_code ? 'err' : null"
            />

            <CInput
              v-model="registerData.password"
              label="کلمه عبور"
              horizontal
              type="password"
              :description="validation.password ? validation.password.msg : null"
              :class="validation.password ? 'err' : null"
            />
            <CInput
              v-model="registerData.password_confirmation"
              label="تکرار کلمه عبور"
              horizontal
              type="password"
              :description="validation.password_confirmation ? validation.password_confirmation.msg : null"
              :class="validation.password_confirmation ? 'err' : null"
            />
          </CForm>
          <el-button type="success" :disabled="!registerData" @click="addUserAndAgent">
            <span style="color: #fff">افزودن</span>
          </el-button>
        </CCol>
      </CRow>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'AdminAgentsList',
  layout: 'admin',
  async asyncData({ $axios, query, error }) {
    try {
      let agents
      if (query?.revoked) {
        agents = await $axios.get('/api/admin/revokedAgents')
      } else {
        agents = await $axios.get('/api/public/agents')
      }

      return {
        agents: agents.data
      }
    } catch (err) {
      error({ status: 404, message: 'There is a problem here' })
    }
  },
  data() {
    return {
      list_title: 'لیست',
      agents: null,
      users: [],
      filterText: '',
      addAgentModal: false,
      selectedUserForNewAgent: null,
      registerData: {
        userID: '',
        first_name: '',
        last_name: '',
        national_code: '',
        province_id: '',
        province_name: '',
        city_id: '',
        city_name: '',
        address: '',
        postal_code: '',
        tel_number: '',
        mobile_number: '',
        email: '',
        store_name: '',
        password: '',
        password_confirmation: ''
      },
      iranCities: [],
      iranProvinces: [],
      provinceCities: null,
      validation: {}
    }
  },
  head() {
    return {
      title: this.title
    }
  },
  computed: {
    selectedProvince() {
      return this.registerData.province_id
    },
    selectedCity() {
      return this.registerData.city_id
    },
    revokedAgentsList() {
      return this.$route.query?.revoked
    },
    title() {
      if (this.revokedAgentsList) return 'لیست نمایندگان صلب امتیاز شده'
      else return 'لیست نمایندگان'
    },
    filteredItems() {
      const filterText = this.filterText.toLowerCase()
      if (!filterText.length) return this.agents
      else
        return this.agents.filter(item => {
          return (
            item.agent_code.toLowerCase().includes(filterText) ||
            item.full_name.toLowerCase().includes(filterText) ||
            item.mobile_number.toLowerCase().includes(filterText) ||
            item.province_name.toLowerCase().includes(filterText) ||
            item.city_name.toLowerCase().includes(filterText)
          )
        })
    }
  },
  watch: {
    revokedAgentsList(newVal, oldVal) {
      this.$nuxt.refresh()
    },
    addAgentModal(newVal, oldVal) {
      this.selectedUserForNewAgent = null
    },
    selectedProvince(newVal, oldVal) {
      // step 1
      this.registerData.city_id = ''
      // step 2
      if (newVal)
        this.registerData.province_name = this.iranProvinces.filter(item => item.ProvinceID === newVal)[0].ProvinceName
      else this.registerData.province_name = ''
      // step 3
      if (newVal) this.provinceCities = this.iranCities.filter(item => item.ProvinceID === newVal)
      else this.provinceCities = null
    },
    selectedCity(newVal, oldVal) {
      if (newVal) this.registerData.city_name = this.iranCities.filter(item => item.CityID === newVal)[0].CityName
      else this.registerData.city_name = ''
    }
  },
  mounted() {
    this.$axios.$get('/api/admin/users').then(res => {
      this.users = res
    })
    this.$axios
      .post('/api/cross/getRouteManager', {
        url: '/api/GetProvince',
        db: 'verity'
      })
      .then(res => {
        this.iranProvinces = res.data.data
      })
      .catch(err => {
        this.$arpaError()
        console.log('provinces list fetch error -- ', err)
      })

    this.$axios
      .post('/api/cross/getRouteManager', {
        url: '/api/GetCity',
        db: 'verity'
      })
      .then(res => {
        this.iranCities = res.data.data
      })
      .catch(err => {
        this.$arpaError()
        console.log('cities list fetch error -- ', err)
      })
  },
  methods: {
    addUserAndAgent() {
      this.validation = {}

      this.$axios
        .post('/api/admin/user', this.registerData)
        .then(response => {
          this.registerData = {
            userID: response.data.user._id,
            first_name: '',
            last_name: '',
            national_code: '',
            province_id: '',
            province_name: '',
            city_id: '',
            city_name: '',
            address: '',
            postal_code: '',
            tel_number: '',
            mobile_number: '',
            email: '',
            store_name: '',
            password: '',
            password_confirmation: ''
          }
          console.log(this.registerData)

          this.$axios
            .$post('/api/admin/addAgentByAdmin', { user: response.data.user._id })
            .then(res => {
              this.$router.push({
                name: 'admin-agents-agent',
                params: { agent: res.representationId },
                query: { ...this.$route.query }
              })
            })
            .catch(err => {
              this.$message({
                type: 'error',
                message: err.response.data.message
              })
            })
        })
        .catch(error => {
          if (error.response.status === 422) {
            this.validation = error.response.data.validation
          } else
            this.$message({
              type: 'error',
              message: error.response.data.message
            })
        })
    },
    addAgent() {
      if (!this.selectedUserForNewAgent) {
        return this.$message({
          type: 'error',
          message: 'ابتدا کاربر مورد نظر را انتخاب نمایید'
        })
      }
      this.$axios
        .$post('/api/admin/addAgentByAdmin', { user: this.selectedUserForNewAgent })
        .then(res => {
          this.$router.push({
            name: 'admin-agents-agent',
            params: { agent: res.representationId },
            query: { ...this.$route.query }
          })
        })
        .catch(err => {
          this.$message({
            type: 'error',
            message: err.response.data.message
          })
        })
    }
  }
}
</script>
