import { useCtx } from "@/comm/ctx";
import ListModule from "..";
import { queenApi } from "queenjs";
import { cloneDeep } from "lodash";
export default ListModule.action({
  async getAssetList(init = false) {
    if (this.store.list.length > 0 && init) {
      return;
    }
    const { deviceCtrl } = useCtx();
    const appDataDir = deviceCtrl.appDataDir;
    const currentCategory = localStorage.getItem("category") || "default";

    const assetsJson = await deviceCtrl.ReadFileText(
      `${appDataDir}/screen/assets_${currentCategory}.json`
    );
    if (assetsJson.error) {
      const res = await deviceCtrl.WriteFileText(
        `${appDataDir}/screen/assets_${currentCategory}.json`,
        "[]"
      );
      this.store.list = [];
    }
    if (assetsJson.text) {
      const assets = JSON.parse(assetsJson.text);
      this.store.list = assets;
    }
  },
  async getAssetDetail(id: string) {
    const res = await this.https.getAssetDetail(id);
    if (res.errorNo != 200) {
      queenApi.messageError(res.errorDesc);
      return;
    }
    return res.result;
  },
  async delAsset(record: any) {
    const { deviceCtrl } = useCtx();
    const list = cloneDeep(this.store.list);
    list.map((e: any, index: number) => {
      if (e._id == record._id) {
        list.splice(index, 1);
      }
    });
    this.store.list = list;
    const appDataDir = deviceCtrl.appDataDir;
    const currentCategory = localStorage.getItem("category") || "default";
    const res = await deviceCtrl.WriteFileText(
      `${appDataDir}/screen/assets_${currentCategory}.json`,
      JSON.stringify(list)
    );
  },
});
