import { Component, Vue } from 'vue-property-decorator';
import { Getter, Mutation } from 'vuex-class';
import { isEqual } from 'lodash';
import localStorage from '@service/localStorage.service';

@Component({ name: 'AutoSaveMixin' })
export default class AutoSaveMixin extends Vue {
  @Getter('pageInfo') pageInfo;
  @Mutation('SET_PAGE_INFO') setPageInfo;

  showRecordModal: boolean = false;
  account: string = localStorage.get('user')?.account;
  hasCompared: boolean = false;
  timer: NodeJS.Timeout | null = null;

  get pageId() {
    return this.pageInfo.uuid || 'new';
  }

  showRecord() {
    // console.log('showRecord');
    const record = localStorage.get(`${this.account}-${this.pageId}`);
    if (record && !isEqual(record, this.pageInfo)) {
      this.showRecordModal = true;
      // console.log('showRecord', record, this.pageInfo);
      return;
    }
    this.hasCompared = true;
  }

  autoSave() {
    const interval = 5 * 1000;
    this.timer = setInterval(() => {
      // console.log('autoSave');
      if (this.account && this.pageInfo && this.hasCompared) {
        // console.log('autoSave in', this.pageInfo);
        localStorage.set(`${this.account}-${this.pageId}`, this.pageInfo);
      }
    }, interval);
    this.$once('hook:beforeDestroy', () => {
      this.clearTimer();
    });
  }

  removeDefaultCache(id = '') {
    this.clearTimer();
    localStorage.remove(`${this.account}-${id}`);
    this.autoSave();
  }

  clearTimer() {
    clearInterval(this.timer as NodeJS.Timeout);
    this.timer = null;
  }

  recover() {
    // console.log('recover');
    const record = localStorage.get(`${this.account}-${this.pageId}`);
    this.setPageInfo(record);
    this.hasCompared = true;
  }

  cancel() {
    // console.log('cancel');
    this.hasCompared = true;
    localStorage.remove(`${this.account}-${this.pageId}`);
  }
}