<template>
  <q-page class="">
    <div class="flex" style="gap: 20px">
      <q-card class="main-block-with-cropped">
        <q-card-section class="text-h6">
          <div class="text-h6">Изменение данных</div>
          <div class="text-subtitle2">Заполните ваш профиль</div>
        </q-card-section>
        <q-card-section v-if="user" class="q-pa-sm">
          <q-list class="row">
            <q-item class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
              <q-item-section side>
                <q-avatar size="100px">
                  <!--                            <img :src="avataroBildo">-->
                  <q-img
                    :loading="imgLoading"
                    :ratio="1"
                    :src="avataroBildo"
                    basic
                    class="rounded-borders"
                    native-context-menu
                    spinner-color="white"
                    style="width: 160px"
                  >
                    <template v-slot:error>
                      <div
                        class="absolute-full flex flex-center bg-negative"
                      ></div>
                    </template>
                  </q-img>
                </q-avatar>
              </q-item-section>
              <q-item-section>
                <change-avatar-btn
                  class="text-white"
                  :objId="user.objId"
                ></change-avatar-btn>
              </q-item-section>
            </q-item>
            <q-item class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
              <q-item-section>
                <q-input
                  class=""
                  v-model="retnomo"
                  :dark="dark"
                  dense
                  label="Псевдоним"
                />
              </q-item-section>
            </q-item>
            <q-item class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
              <q-item-section>
                <q-input
                  v-model="chefaRetposhto"
                  :dark="dark"
                  dense
                  label="Email"
                  readonly
                  type="email"
                >
                  <template v-slot:default>
                    <change-email-btn class="q-px-sm" />
                  </template>
                </q-input>
              </q-item-section>
            </q-item>
            <q-item class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
              <q-item-section>
                <q-input v-model="unuaNomo" :dark="dark" dense label="Имя" />
              </q-item-section>
            </q-item>
            <q-item class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
              <q-item-section>
                <q-input
                  v-model="duaNomo"
                  :dark="dark"
                  dense
                  label="Отчество"
                />
              </q-item-section>
            </q-item>
            <q-item class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
              <q-item-section>
                <q-input
                  v-model="familinomo"
                  :dark="dark"
                  dense
                  label="Фамилия"
                />
              </q-item-section>
            </q-item>
            <q-item
              class="col-lg-12 col-md-12 col-sm-12 col-xs-12"
              v-if="false"
            >
              <q-item-section>
                <q-input
                  v-model="user_details.address"
                  autogrow
                  :dark="dark"
                  dense
                  label="Адрес"
                  readonly
                />
              </q-item-section>
            </q-item>
            <q-item class="col-lg-6 col-md-6 col-sm-12 col-xs-12" v-if="false">
              <q-item-section>
                <q-input
                  v-model="user_details.city"
                  color="dlack"
                  :dark="dark"
                  dense
                  label="Город"
                  readonly
                />
              </q-item-section>
            </q-item>
            <q-item class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
              <q-item-section>
                <q-input
                  v-model="naskighdato"
                  :dark="dark"
                  dense
                  label="Дата рождения"
                  type="date"
                />
              </q-item-section>
            </q-item>
            <q-item
              class="col-lg-12 col-md-12 col-sm-12 col-xs-12"
              v-if="false"
            >
              <q-item-section>
                <q-input
                  v-model="user_details.about"
                  :dark="dark"
                  dense
                  label="Описание"
                  readonly
                  type="textarea"
                />
              </q-item-section>
            </q-item>
          </q-list>
        </q-card-section>
        <q-card-actions align="right">
          <q-btn
            class="text-capitalize text-white cursor-pointer"
            flat
            style="background: #0fab9d; margin-right: 15px; margin-bottom: 15px"
            @click="setUzanto"
            >Сохранить
          </q-btn>
        </q-card-actions>
      </q-card>

      <q-form ref="passwordForm" @submit.prevent="setPassword">
        <q-card class="main-block-with-cropped">
          <q-card-section class="text-h6">
            <div class="text-h6">Изменить пароль</div>
          </q-card-section>
          <q-card-section class="row q-pa-sm">
            <q-list class="row">
              <q-item class="col-lg-4 col-md-4 col-sm-12 col-xs-12">
                <q-item-section> Текущий пароль </q-item-section>
              </q-item>
              <q-item class="col-lg-8 col-md-8 col-sm-12 col-xs-12">
                <q-item-section>
                  <q-input
                    v-model="password"
                    :dark="dark"
                    dense
                    label="Текущий пароль"
                    outlined
                    round
                    type="password"
                    hide-bottom-space
                  />
                </q-item-section>
              </q-item>
              <q-item class="col-lg-4 col-md-4 col-sm-12 col-xs-12">
                <q-item-section> Новый пароль </q-item-section>
              </q-item>
              <q-item class="col-lg-8 col-md-8 col-sm-12 col-xs-12">
                <q-item-section>
                  <q-input
                    v-model="newPassword"
                    :rules="passwordRules"
                    :dark="dark"
                    dense
                    label="Новый пароль"
                    outlined
                    round
                    type="password"
                    hide-bottom-space
                  />
                </q-item-section>
              </q-item>
              <q-item class="col-lg-4 col-md-4 col-sm-12 col-xs-12">
                <q-item-section> Подтверждение пароля </q-item-section>
              </q-item>
              <q-item class="col-lg-8 col-md-8 col-sm-12 col-xs-12">
                <q-item-section>
                  <q-input
                    v-model="confirmPassword"
                    :rules="confirmRules"
                    :dark="dark"
                    dense
                    label="Подтверждение пароля"
                    outlined
                    round
                    type="password"
                    hide-bottom-space
                  />
                </q-item-section> </q-item
            ></q-list>
          </q-card-section>
          <q-card-actions align="right">
            <q-btn
              class="text-white"
              flat
              no-caps
              style="
                background: #0fab9d;
                margin-right: 15px;
                margin-bottom: 15px;
              "
              type="submit"
              >Сохранить пароль
            </q-btn>
          </q-card-actions>
        </q-card>
      </q-form>
    </div>
  </q-page>
</template>
<script>
import { createMetaMixin } from "quasar";
import { defineAsyncComponent, defineComponent } from "vue";
import meta from "src/utils/meta";
import { mapState, mapActions } from "pinia";
import { useRegistradoStore } from "src/stores/registrado";
import { useAuthStore } from "src/stores/auth";
import { useUiStore } from "src/stores/UI";
import { useUserStore } from "src/stores/uzanto";

export default defineComponent({
  name: "UserProfile",

  setup() {
    return {
      getPageStyle(offset, height) {
        return {
          height: `${height - offset - 105}px`,
        };
      },
    };
  },

  mixins: [
    createMetaMixin(function () {
      return meta(this.metaTags);
    }),
  ],
  components: {
    ChangeEmailBtn: defineAsyncComponent(() =>
      import("components/ChangeEmailDialog")
    ),
    ChangeAvatarBtn: defineAsyncComponent(() =>
      import("components/ChangeAvatarDialog")
    ),
  },
  data() {
    return {
      metaTags: {
        title: "Профиль пользователя",
        description: "Профиль пользователя",
        keywords: "Профиль пользователя",
        url: process.env.APP_HOST + this.$route.path,
        image: "",
        robots: "",
      },
      user_details: {},
      password_dict: {},

      optionsLandoj: this.infoj?.landoj,
      optionsRegiono: this.infoj?.regiono,
      optionsOrganizo: this.infoj?.organizo,
      unuaNomo: null,
      duaNomo: null,
      familinomo: null,
      retnomo: null,
      sovetoj: null,
      sindikatoj: null,
      sekso: null,
      seksoOptions: ["Мужской", "Женский"],
      naskighdato: null,
      loghregiono: null,
      loghlando: null,
      statuso: null,
      chefaTelefonanumero: null,
      chefaRetposhto: null,
      chefaOrganizo: null,
      chefaLingvo: null,
      avataro: null,
      administritajKomunumoj: null,
      changeAvatar: null,
      errors: {},
      tab: "baza",
      uuid: null,
      tabs: [
        {
          tab: "baza",
          nomo: "Основные",
        },
        {
          tab: "sekura",
          nomo: "Безопасность",
        },
        {
          tab: "sciigo",
          nomo: "Уведомления",
        },
      ],
      title: "Настройки пользователя",

      password: null,
      newPassword: null,
      confirmPassword: null,
      passwordRules: [
        (v) =>
          this.password ? !!v || "Поле обязательно для заполнения" : true,
        (v) =>
          /^[0-9a-zA-Z+-_*.,;$!?%#=()]+$/.test(v) ||
          'Допустимы только символы латинского алфавита, цифры и символы "_*.,;$!?%#=()"',
        (v) =>
          this.password
            ? (v?.length >= 6 && v?.length <= 32) ||
              "Пароль должен иметь длину от 6 до 32 символов"
            : true,
        (v) =>
          !Object.prototype.hasOwnProperty.call(this.errors, "pasvorto") ||
          this.errors.pasvorto,
      ],
      confirmRules: [
        (v) =>
          this.password ? !!v || "Поле обязательно для заполнения" : true,
        (v) =>
          /^[0-9a-zA-Z+-_*.,;$!?%#=()]+$/.test(v) ||
          'Допустимы только символы латинского алфавита, цифры и символы "_*.,;$!?%#=()"',
        (v) => this.newPassword === v || "Пароли не совпадают",
      ],
    };
  },

  watch: {
    user: function () {
      this.fillUzanto();
    },
    regionoKodo: function (cur) {
      this.fetchInfojRegiono({
        lando_Kodo: cur.value || "RU",
      });
    },
  },
  computed: {
    ...mapState(useRegistradoStore, {
      infoj: "getInfoj",
    }),
    ...mapState(useAuthStore, {
      user: "user",
    }),
    ...mapState(useUiStore, {
      dark: "dark",
      imgLoading: "getImageLoadingMode",
    }),

    retlisto: {
      get: function () {
        if (!this.user?.agordoj) return null;
        const curJSON = JSON.parse(this.user.agordoj);
        return Object.prototype.hasOwnProperty.call(curJSON, "abono_shlosilo");
      },
      set: function (val) {
        this.changeUzanto({ poshtoSciigoj: val }).then((resp) => {
          if (resp.status) {
            this.$q.notify({
              type: "positive",
              message: resp.message,
            });
          } else {
            this.$q.notify({
              type: "negative",
              message: resp.message,
            });
          }
        });
      },
    },

    seksoLazyFix: function () {
      if (this.sekso === "Мужской") return "vira";
      if (this.sekso === "Женский") return "virina";
      return null;
    },
    regionoKodo: function () {
      if (typeof this.loghlando !== "object") {
        const cur = this.infoj.landoj.filter((v) => {
          return v.label === this.loghlando;
        });
        return cur;
      }
      return this.loghlando;
    },
    selectWidth: function () {
      return this.$refs.selectOrganizo[0].clientWidth;
    },
    avataroBildo: function () {
      return this.avataro.bildoE?.url || this.avataro.bildoF?.url;
    },
  },
  methods: {
    ...mapActions(useRegistradoStore, [
      "fetchInfoj",
      "fetchOrganizo",
      "fetchInfojRegiono",
    ]),
    ...mapActions(useAuthStore, ["addUniversoUzanto"]),
    ...mapActions(useUserStore, ["changeUzanto", "changePassword"]),

    filterLandoj(val, update, abort) {
      update(() => {
        const needle = val.toLowerCase();
        this.optionsLandoj = this.infoj.landoj.filter(
          (v) => v.label.toLowerCase().indexOf(needle) > -1
        );
      });
    },
    filterRegiono(val, update, abort) {
      update(() => {
        const needle = val.toLowerCase();
        this.optionsRegiono = this.infoj.regiono.filter(
          (v) => v.label.toLowerCase().indexOf(needle) > -1
        );
      });
    },
    filterOrganizo(val, update, abort) {
      update(() => {
        const needle = val.toLowerCase();
        this.optionsOrganizo = this.infoj.organizo.filter(
          (v) => v.label.toLowerCase().indexOf(needle) > -1
        );
      });
    },

    setUzanto() {
      const retnomo =
        this.retnomo === this.user.universoUzanto?.retnomo
          ? null
          : this.retnomo;
      const params = {
        unuaNomo:
          this.unuaNomo === this.user.unuaNomo?.enhavo ? null : this.unuaNomo,
        duaNomo:
          this.duaNomo === this.user.duaNomo?.enhavo ? null : this.duaNomo,
        familinomo:
          this.familinomo === this.user.familinomo?.enhavo
            ? null
            : this.familinomo,
        sekso:
          this.seksoLazyFix === this.user?.sekso ? null : this.seksoLazyFix,
        naskighdato:
          this.naskighdato === this.user.naskighdato
            ? null
            : this.naskighdato.replace(/\//g, "."),
        chefaOrganizo:
          this.chefaOrganizo.label === this.user.chefaOrganizo?.nomo?.enhavo
            ? null
            : this.chefaOrganizo.value,
        lando:
          this.loghlando.label === this.user.loghlando?.nomo?.enhavo
            ? null
            : this.loghlando.value,
        lingvo:
          this.chefaLingvo.label === this.user.chefaLingvo?.nomo
            ? null
            : this.chefaLingvo.value,
        regiono:
          this.loghregiono === this.user.loghregiono?.nomo?.enhavo
            ? null
            : this.loghregiono.value,
        statuso:
          this.statuso === this.user.statuso?.enhavo ? null : this.statuso,
      };
      //тут сокращаю запрос, чтоб были только содержательные параметры (не null или undefined)
      const reducedParams = Object.fromEntries(
        Object.entries(params).filter(
          ([key, value]) => value !== null && value !== undefined
        )
      );
      if (Object.keys(reducedParams).length) {
        this.changeUzanto(reducedParams).then((resp) => {
          if (resp.status) {
            this.$q.notify({
              type: "positive",
              message: resp.message,
            });
          } else {
            this.$q.notify({
              type: "negative",
              message: resp.message,
            });
          }
        });
      }

      if (retnomo) {
        this.addUniversoUzanto({ retnomo, uuid: this.uuid }).then((resp) => {
          if (resp.status) {
            this.$q.notify({
              type: "positive",
              message: resp.message,
            });
          } else {
            this.$q.notify({
              type: "negative",
              message: resp.message,
            });
          }
        });
      }
    },

    mapErrorObject(errors) {
      const out = {};
      for (const item of errors) {
        out[item.field] = item.message;
      }
      return out;
    },
    onReset() {
      this.fillUzanto();
    },
    fillUzanto() {
      if (this.user) {
        this.unuaNomo = this.user.unuaNomo.enhavo;
        this.duaNomo = this.user.duaNomo.enhavo;
        this.familinomo = this.user.familinomo.enhavo;
        this.retnomo = this.user.universoUzanto.retnomo;
        this.sovetoj = [
          ...new Set(
            this.user.sovetoj.edges.map((cur) => cur.node.nomo.enhavo)
          ),
        ].join(", ");
        this.sindikatoj = [
          ...new Set(
            this.user.sindikatoj.edges.map((cur) => cur.node.nomo.enhavo)
          ),
        ].join(", ");
        this.sekso =
          this.user.sekso === "vira"
            ? "Мужской"
            : this.user.sekso === "virina"
            ? "Женский"
            : "";
        this.naskighdato = this.user.naskighdato;
        this.loghregiono = this.user.loghregiono?.nomo?.enhavo;
        this.loghlando = this.user.loghlando?.nomo?.enhavo;
        this.statuso = this.user.statuso?.enhavo;
        this.chefaTelefonanumero = this.user.chefaTelefonanumero ?? "";
        this.chefaRetposhto = this.user.chefaRetposhto;
        this.chefaOrganizo = this.user.chefaOrganizo?.nomo?.enhavo ?? "";
        this.chefaLingvo = this.user.chefaLingvo?.nomo ?? "";
        this.avataro = this.user.avataro ?? "";
        this.uuid = this.user.universoUzanto.uuid;
        this.administritajKomunumoj = [
          ...new Set(
            this.user.administritajKomunumoj.edges.map(
              (cur) => cur.node.nomo.enhavo
            )
          ),
        ].join(", ");
      }
    },

    setPassword() {
      if (this.newPassword !== this.confirmPassword) {
        this.$q.notify({
          type: "negative",
          message: "Новый пароль не совпадает с подтверждением",
        });
        return;
      }
      const params = {
        uzantoId: this.user.objId,
        pasvorto: this.password,
        novaPasvorto: this.newPassword,
      };
      this.changePassword(params)
        .then((resp) => {
          if (resp?.status) {
            this.$q.notify({
              type: "positive",
              message: resp.message,
            });
          } else {
            this.errors = { message: resp?.message };
            this.$refs.passwordForm.validate();
            this.errors = {};
            this.$q.notify({
              type: "negative",
              message: resp?.message,
            });
          }
        })
        .catch((err) => console.log(err))
        .finally(() => {
          this.onResetPassword();
        });
    },

    onResetPassword() {
      this.password = this.newPassword = this.confirmPassword = null;
    },
  },
  created() {
    if (process.env.CLIENT) this.fetchInfoj;
    if (process.env.CLIENT) this.fetchOrganizo;

    this.fillUzanto();
  },
});
</script>
<style scoped>
@media (max-width: 535px) {
  /* .user-profile__container {
    margin-left: 0;
  } */
}
</style>
