<template>
  <div>
    <CustomSubHeader>
      <CBreadcrumb class="border-0 mb-0">{{ title }}</CBreadcrumb>
      <CButton
          size="sm"
          color="primary"
          class="mr-auto"
          :to="{ name: 'admin-users' }"
      >برگشت به صفحه قبل
      </CButton
      >
      <CButton
          v-if="$route.params.profile === 'new'"
          size="sm"
          color="success"
          class="mr-1"
          @click="post"
      >افزودن
      </CButton>
      <CButton v-else size="sm" color="success" class="mr-1" @click="update"
      >بروزرسانی
      </CButton
      >
    </CustomSubHeader>
    <CRow>
      <CCol>
        <CCard>
          <CCardBody>
            <CRow>
              <CCol lg="6">
                <CForm>
                  <CRow v-if="$route.params.profile !== 'profile'">
                    <CCol sm="12">
                      <el-checkbox
                          v-model="user.registration_done"
                          label="کاربر فعال باشد"
                      />
                    </CCol>
                    <el-divider></el-divider>
                  </CRow>
                  <template v-if="$route.params.profile !== 'new'">
                    <h4>مشخصات کاربر</h4>
                    <el-divider/>
                  </template>
                  <CRow>
                    <CCol sm="12">
                      <CInput
                          :class="validation.firstName ? 'err' : null"
                          label="نام"
                          :description="
                          validation.firstName ? validation.firstName.msg : null
                        "
                          v-model="user.firstName"
                      />
                    </CCol>

                    <CCol sm="12">
                      <CInput
                          :class="validation.lastName ? 'err' : null"
                          label="نام خانوادگی"
                          :description="
                          validation.lastName ? validation.lastName.msg : null
                        "
                          v-model="user.lastName"
                      />
                    </CCol>

                    <CCol sm="12">
                      <CInput
                          label="نام کاربری"
                          v-model="user.username"
                          :class="validation.username ? 'err' : null"
                          :description="
                          validation.username ? validation.username.msg : null
                        "
                          :disabled="$route.params.profile!=='new'"
                      />
                    </CCol>

                    <CCol sm="12">
                      <CInput
                          label="تلفن همراه"
                          placeholder="اختیاری"
                          v-model="user.mobileNumber"
                          :class="validation.mobileNumber ? 'err' : null"
                          :description="
                          validation.mobileNumber
                            ? validation.mobileNumber.msg
                            : null
                        "
                      />
                    </CCol>

                    <CCol sm="12">
                      <CInput
                          :class="validation.email ? 'err' : null"
                          label="ایمیل"
                          v-model="user.email"
                          :description="
                          validation.email ? validation.email.msg : null
                        "
                      />
                    </CCol>

                    <template v-if="$route.params.profile === 'new'">
                      <CCol sm="12">
                        <CInput
                            :class="validation.password ? 'err' : null"
                            label="کلمه عبور"
                            type="password"
                            :description="
                            validation.password ? validation.password.msg : null
                          "
                            v-model="user.password"
                        />
                      </CCol>
                      <CCol sm="12">
                        <CInput
                            :class="
                            validation.password_confirmation ? 'err' : null
                          "
                            label="تکرار کلمه عبور"
                            type="password"
                            :description="
                            validation.password_confirmation
                              ? validation.password_confirmation.msg
                              : null
                          "
                            v-model="user.password_confirmation"
                        />
                      </CCol>
                    </template>
                  </CRow>
                  <el-divider/>
                  <template v-if="$route.params.profile !== 'profile'">
                    <h6>انتخاب محدوده دسترسی</h6>
                    <el-select
                        v-model="user.portals"
                        multiple
                        placeholder="انتخاب کنید"
                        style="width: 100%;"
                        @change="changePortalVal"
                    >
                      <el-option
                          v-for="item in portals"
                          :key="item.value"
                          :label="item.name"
                          :value="item.value"
                      >
                      </el-option>
                    </el-select>
                    <p
                        style="margin-top : 5px !important ; color : red"
                        class="form-err"
                        v-if="validation.portals"
                    >
                      {{ validation.portals.msg }}
                    </p>
                    <el-divider/>

                    <el-select
                        style="width: 100%;"
                        v-model="user.specialPermissions"
                        multiple
                        filterable
                        placeholder="انتخاب دسترسی خاص"
                    >
                      <el-option
                          v-for="item in filterSpecPer"
                          :key="item._id"
                          :label="item.title"
                          :value="item._id"
                      >
                        <!-- <span>{{setTitle(item)}}</span> -->
                      </el-option>
                    </el-select>
                    <p class="text-danger" v-if="!user.specialPermissions.length">درصورتی که دسته بندی خاصی را انتخاب
                      نکنید,کاربر به تمام اخبار دسترسی خواهد
                      داشت.</p>

                    <div style="margin-top : 5px">
                      <p
                          style="margin-top : 5px !important ; color : red"
                          class="form-err"
                          v-if="validation.specialPermissions"
                      >
                        {{ validation.specialPermissions.msg }}
                      </p>
                    </div>

                    <el-divider/>

                    <h6 class="mb-3">دسترسی های کاربر</h6>
                    <div class="user-permissions">
                      <p
                          style="margin-top : 5px !important ; color : red"
                          class="form-err"
                          v-if="validation.permissions"
                      >
                        {{ validation.permissions.msg }}
                      </p>
                      <el-tag
                          class="ml-2 mb-2"
                          style="cursor: pointer"
                          v-for="(item, index) in user.permissions"
                          :key="index + Math.random() + 1"
                          closable
                          disable-transitions
                          @close="removePermission(item)"
                      >
                        {{ getPermissionName(item) }}
                      </el-tag>
                    </div>
                  </template>
                </CForm>
              </CCol>
              <CCol lg="6">
                <CForm>
                  <CRow>
                    <CCol sm="12">
                      <h4>عکس پروفایل</h4>
                      <el-divider/>
                      <CCol>
                        <img
                            :src="user.profilePic"
                            style="width: 100%;max-width: 250px;"
                            alt=""
                        />
                      </CCol>
                      <input
                          type="file"
                          ref="profilePic"
                          @change="imagePreview"
                      />
                      <p
                          style="margin-top : 5px !important ;"
                          class="form-err"
                          v-if="validation.profilePic"
                      >
                        {{ validation.profilePic.msg }}
                      </p>
                      <p class="mt-3 text-muted">
                        عکس 500*500 باشد. در غیر این صورت اتوماتیک بریده می شود.
                      </p>
                      <CCol></CCol>
                      <p
                          style="margin-top : 0px !important ; "
                          class="form-err"
                          v-if="validation.password_confirmation"
                      >
                        {{ validation.password_confirmation.msg }}
                      </p>
                    </CCol>
                    <template v-if="$route.params.profile !== 'new'">
                      <CCol sm="12" class="mt-5">
                        <h4>تغییر کلمه عبور</h4>
                        <el-divider/>
                        <CInput
                            :class="validation.password ? 'err' : null"
                            label="کلمه عبور"
                            type="password"
                            :description="
                            validation.password ? validation.password.msg : null
                          "
                            v-model="newPass.password"
                        />
                      </CCol>

                      <CCol sm="12">
                        <CInput
                            :class="
                            validation.password_confirmation ? 'err' : null
                          "
                            label="تکرار کلمه عبور"
                            type="password"
                            :description="
                            validation.password_confirmation
                              ? validation.password_confirmation.msg
                              : null
                          "
                            v-model="newPass.password_confirmation"
                        />

                        <CButton
                            size="sm"
                            color="success"
                            class="mr-1 mt-3"
                            @click="updatePassword"
                        >تغییر کلمه عبور
                        </CButton>
                      </CCol>
                    </template>
                  </CRow>
                </CForm>
              </CCol>
            </CRow>
          </CCardBody>
        </CCard>

        <CCard v-if="$route.params.profile !== 'profile'">
          <CCardBody>
            <h6 class="mb-3" style="color:#000">لیست کل دسترسی ها</h6>
            <div class="permissions">
              <el-tag
                  class="ml-2 mb-2"
                  style="cursor: pointer"
                  v-for="(item, index) in permissions"
                  :key="index + Math.random() + 2"
                  :type="hasPermission(item.value) ? 'success' : 'primary'"
                  disable-transitions
                  @click="addPermission(item.value)"
              >{{ item.name }}
              </el-tag>
            </div>
          </CCardBody>
        </CCard>
      </CCol>
    </CRow>
  </div>
</template>

<script>
import axiosUploadProcess from "@/mixins/axiosUploadProcess"

export default {
  data() {
    return {
      user: null,
      permissions: null,
      specialPermissions: null,
      newPass: {
        password: '',
        password_confirmation: ''
      },
      validation: {},
      portals: null,
      filterSpecPer: null
    }
  },
  mixins: [axiosUploadProcess],
  computed: {
    title() {
      return this.$route.params.profile === 'new' ? 'افزودن کاربر' : 'مشاهده پروفایل کاربر'
    }
  },
  methods: {
    changePortalVal(value) {
      this.user.specialPermissions = [];
      this.filterSpecPer = this.specialPermissions.filter(item => value.includes(item.modelType));
    },
    getPermissionName(value) {
      if (value) {
        return this.permissions.filter(item => item.value === value)[0].name
      }
    },
    addPermission(val) {
      if (!this.user.permissions.includes(val) && !this.user.permissions.includes('superAdmin')) {
        val === 'superAdmin' ? this.user.permissions = [val] : this.user.permissions.push(val)
      } else {
        this.$message({
          type: 'warning',
          message: 'کاربر از قبل این دسترسی را دارد'
        });
      }
    },
    removePermission(val) {
      this.user.permissions = this.user.permissions.filter(item => item !== val)
    },
    hasPermission(val) {
      if (this.user.permissions.includes('superAdmin')) {
        return true;
      } else {
        return this.user.permissions.includes(val)
      }
    },
    imagePreview(e) {
      this.user.profilePic = URL.createObjectURL(e.target.files[0])
    },
    post() {
      this.validation = {}
      const data = new FormData()
      data.append("firstName", this.user.firstName.trim())
      data.append("lastName", this.user.lastName.trim())
      data.append("mobileNumber", this.user.mobileNumber.trim())
      data.append("email", this.user.email.trim())
      data.append("username", this.user.username.trim())
      data.append("permissions", JSON.stringify(this.user.permissions))
      data.append("password", this.user.password)
      data.append("portals", JSON.stringify(this.user.portals))
      data.append("specialPermissions", JSON.stringify(this.user.specialPermissions))
      data.append("registration_done", !this.user?.registration_done ? false : this.user.registration_done)
      data.append("password_confirmation", this.user.password_confirmation)
      if (this.$refs.profilePic.files[0]) data.append("profilePic", this.$refs.profilePic.files[0])


      this.$axios.post(`/api/admin/user/registerAdmin`, data, this.axiosConfig)
          .then(response => {
            this.$message({
              type: 'success',
              message: 'کاربر با موفقیت ایجاد شد.'
            })
            this.$router.push({
              name: 'admin-users'
            })
          })
          .catch(err => {
            if (err.response.status === 401) {
              return this.$message({
                type: 'error',
                message: 'لطفا دوباره وارد سیستم شوید.'
              })
            }
            if (err.response.status === 422) this.validation = err.response.data.validation
            else console.log(err.response.data)
          })
    },
    update() {
      this.validation = {};

      const data = new FormData();
      data.append("firstName", this.user.firstName.trim())
      data.append("lastName", this.user.lastName.trim())
      data.append("mobileNumber", this.user.mobileNumber.trim())
      data.append("email", this.user.email.trim())
      data.append("username", this.user.username.trim())
      data.append("permissions", JSON.stringify(this.user.permissions))
      data.append("password", this.user.password)
      data.append("portals", JSON.stringify(this.user.portals))
      data.append("specialPermissions", JSON.stringify(this.user.specialPermissions))
      data.append("registration_done", !this.user?.registration_done ? false : this.user.registration_done)
      data.append("password_confirmation", this.user.password_confirmation)
      if (this.$refs.profilePic.files[0]) data.append("profilePic", this.$refs.profilePic.files[0])

      this.$axios.put(this.$route.params.profile === 'profile' ? '/api/admin/profile' : `/api/admin/user/${this.user._id}`, data, this.axiosConfig)
          .then(response => {
            this.$message({
              type: 'success',
              message: 'اطلاعات بروزرسانی شد.'
            })
            this.$nuxt.refresh()
          })
          .catch(err => {
            if (err.response.status === 401) {
              return this.$message({
                type: 'error',
                message: 'لطفا دوباره وارد سیستم شوید.'
              })
            }
            if (err.response.status === 422) this.validation = err.response.data.validation
            else console.log(err.response.data);
          })
    },
    updatePassword() {
      this.validation = {}

      this.$axios.put(this.$route.params.profile === 'profile' ? '/api/admin/profile/changePass' : `/api/admin/user/changePass/${this.user._id}`, this.newPass)
          .then(async (response) => {
            this.$message({
              type: 'success',
              message: 'کلمه عبور بروزرسانی شد.'
            })
            this.newPass = {
              password: '',
              password_confirmation: ''
            }

            if (this.$route.params.profile === 'profile') {
              await this.$auth.logout()
              window.location.replace('/admin/login');
            }
          })
          .catch(err => {
            if (err.response.status === 401) {
              return this.$message({
                type: 'error',
                message: 'لطفا دوباره وارد سیستم شوید.'
              })
            }
            if (err.response.status === 422) this.validation = err.response.data.validation
            else console.log(err.response.data)
          })
    }
  },
  head() {
    return {
      title: this.title
    }
  },
  layout: 'admin',
  async asyncData({
                    $axios,
                    params,
                    error
                  }) {
    try {
      // const permissions = await $axios.get('/api/admin/permissions',{ progress: false });
      // const portals = await $axios.get('/api/admin/portals',{ progress: false });
      // const specialPermissions = await $axios.get('/api/admin/category/permissions',{ progress: false });

      const requests = [
        $axios.get('/api/admin/permissions', {progress: false}),
        $axios.get('/api/admin/portals', {progress: false}),
        $axios.get('/api/admin/category/permissions', {progress: false})
      ];

      const fetch = await Promise.all(requests);

      let [permissions, portals, specialPermissions] = fetch;

      if (params.profile === 'profile') {
        const user = await $axios.get(`/api/admin/profile`);

        return {
          portals: portals.data,
          permissions: permissions.data,
          specialPermissions: specialPermissions.data,
          filterSpecPer: specialPermissions.data.filter(item => user.data.portals.includes(item.modelType)),
          user: user.data
        }
      } else if (params.profile !== 'new') {
        var user = await $axios.get(`/api/admin/user/${params.profile}`);

        var permissionsArr = [];
        for (const item of user.data.specialPermissions) {
          permissionsArr.push(item._id);
        }

        user.data.specialPermissions = permissionsArr;

        return {
          portals: portals.data,
          permissions: permissions.data,
          specialPermissions: specialPermissions.data,
          filterSpecPer: specialPermissions.data.filter(item => user.data.portals.includes(item.modelType)),
          user: user.data
        }
      } else {
        return {
          portals: portals.data,
          permissions: permissions.data,
          specialPermissions: specialPermissions.data,
          user: {
            firstName: '',
            lastName: '',
            mobileNumber: '',
            email: '',
            username: '',
            password: '',
            portals: [],
            password_confirmation: '',
            profilePic: '',
            permissions: [],
            specialPermissions: []
          }
        }
      }
    } catch (e) {
      if (e?.response?.status === 401) {
        error({
          status: 401,
          message: "لطفا دوباره وارد سیستم شوید.",
        });
      }
      if (e?.response?.status === 403) {
        error({
          status: 403,
          message: e?.response?.data?.message,
        });
      }
      if (e?.response?.status === 500) {
        error({
          status: 500,
          message: "مشکلی در گرفتن اطلاعات پیش آمده",
        });
      } else
        error({
          status: 404,
          message: "اطلاعات کاربر مورد نظر پیدا نشد",
        });
    }
  }
}
</script>
