import db from "../plugins/db";

export default {
  methods: {
    getLastLoginUser() {
      return db.getDict("lastLoginUser", "");
    },
    async setLastLoginUser(user) {
      await db.setDict("lastLoginUser", JSON.stringify(user));
    },
    async initScanArea(subjects) {
      const storeScanArea = await db.getDict("scanArea", "");
      const scanArea = storeScanArea ? JSON.parse(storeScanArea) : {};

      let newScanArea = {};
      subjects.map(subject => {
        let info = { ...subject };
        if (scanArea[subject.id] && scanArea[subject.id].collectConfig)
          info.collectConfig = scanArea[subject.id].collectConfig;

        newScanArea[subject.id] = info;
      });

      this.$store.commit("client/setScanArea", newScanArea);
    },
    async initStartCountTime(subjects) {
      const storeStartCountTime = await db.getDict("startCountTime", "");

      let startCountTime = {};
      if (storeStartCountTime) {
        startCountTime = JSON.parse(storeStartCountTime);
        this.$store.commit("client/setStartCountTime", startCountTime);
      } else {
        subjects.map(subject => {
          startCountTime[subject.id] = 0;
        });
        this.$store.dispatch("client/updateStartCountTime", startCountTime);
      }
    },
    async initStore() {
      const storeDict = await db.getAllDict();
      const needInitDict = ["scanArea", "startCountTime", "lastLoginUser"];
      for (let key in needInitDict) {
        if (
          !Object.prototype.hasOwnProperty.call(storeDict, needInitDict[key])
        ) {
          await db.initDict(needInitDict[key]);
        }
      }
    }
  }
};
