import { mapState, mapActions } from "pinia";
import { useCommonStore } from "~/stores/commonStore";

export default {
  created() {
    this.httpService = useNuxtApp()["$http"];
  },
  mounted() {
    // this.httpService = new HttpService(import.meta.env.VITE_AUTH_BASE_URL);
    this.get();
  },
  computed: {
    ...mapState(useCommonStore, [
      "currentUser",
      "isAuthenticatedGetter",
      "isRealUser",
    ]),
  },
  data() {
    return {
      canView: false,
      fetchingData: false,

      profile: {
        avatar: "",
        first_name: null,
        last_name: null,
        mobile: null,
        mail: null,
      },
      changepass: {
        pass: "",
        newpass: "",
        renewpass: "",
      },
      file: null,
      // currentTab: 1,
      httpService: undefined,
    };
  },
  methods: {
    ...mapActions(useCommonStore,["checkPermissions","setUser"]),
    async checkPermisionBeforGetList(permission) {
      if (this.fetchingData) return;
      this.fetchingData = true;

      return await this.checkPermissions({ permission, _this: this })
        .then(() => {
          this.canView = true;
        })
        .catch(() => {
          this.canView = false;
          this.fetchingData = false;
        });
    },

    setTab(tab) {
      this.currentTab = tab;
    },
    get: function () {
      var vm = this;
      this.httpService
        .getRequest(loginUrl() + "profile/get")
        .then(({ data }) => {
          vm.profile = data;
        });
    },
    edit: function () {
      const vm = this;

      if (this.currentTab == 1) {
        this.httpService
          .formDataRequest(loginUrl() + "profile/update", this.profile)
          .then((res) => {
            let userData = this.currentUser;
            userData.user_data = { ...userData.user_data, ...res.data };
            this.setUser(userData);

            this.mySwalToast({
              icon: "success",
              title: res.message,
              html: "",
            });
          })
          .catch((err) => {});
      } else if (this.currentTab == 2) {
        if (
          this.$v.password.$model === "" ||
          this.$v.newpass.$model === "" ||
          this.$v.repassword.$model === ""
        ) {
          this.mySwalToast({
            title: " رمز عبور ",
            text: "مقدار کلمه عبور   خالی  هست.",
            html: "مقدار کلمه عبور   خالی  هست.",
            icon: "error",
            position: "bottom-end",
            showConfirmButton: false,
            toast: true,
            timer: 1500,
          });
          return;
        }
        if (this.$v.newpass.$invalid && this.$v.repassword.$invalid) {
          // نمایش خطا در صورتی که newpass معتبر نباشد
          this.mySwalToast({
            title: "تغییر پسورد",
            text: "کلمه عبور جدید معتبر نیست.",
            html: "کلمه عبور جدید باید شرایط مورد نظر را رعایت کند.",
            icon: "error",
            position: "bottom-end",
            showConfirmButton: false,
            toast: true,
            timer: 1500,
          });
          return;
        }

        if (this.$v.newpass.$model == this.$v.repassword.$model) {
          let payload = {
            pass: this.$v.password.$model,
            newpass: this.$v.newpass.$model,
            renewpass: this.$v.repassword.$model,
          };
          this.httpService
            .formDataRequest(loginUrl() + "profile/changepass", payload)
            .then(({ message }) => {
              this.mySwalToast({
                icon: "success",
                title: message,
                html: "",
                timer: 1000,
              });
              setTimeout(() => {
                vm.logout();
              }, 1000);
            })
            .catch((err) => {});
        } else {
          this.mySwalToast({
            title: "تغییرپسورد",
            text: "کلمه عبور جدید تطابق ندارد.",
            html: "کلمه عبور جدید تطابق ندارد.",
            icon: "error",
            position: "bottom-end",
            showConfirmButton: false,
            toast: true,
            timer: 1500,
          });
        }
      }
    },
    onFileChange(e) {
      const vm = this;

      const file = e.target.files[0];
      this.file = file;
      if (typeof FileReader === "function") {
        const reader = new FileReader();
        reader.onload = (event) => {
          vm.profile.avatar = event.target.result;
          vm.profile.newAvatar = event.target.result;
          vm.profile.file = file;
        };
        reader.readAsDataURL(file);
      } else {
        this.mySwalToast({
          title: "خطا",
          text: "این فرمت پشتیبانی نمیشود",
          icon: "error",
          position: "bottom-end",
          showConfirmButton: false,
          toast: true,
          timer: 1500,
        });
      }
    },
  },
};