<template>
  <header class="app-head" app-border dir-bottom>
    <a class="app-head-back" href="./material.html#/works">
      <i class="iconfont icon-editor_return"></i>
      返回我的作品
    </a>
    <span class="app-head-title">{{ info.name }}</span>
    <div class="app-head-save ui-button deepcancel app-head-view" @click="onView" :class="{ disable: !canLoad || isEditing }">
      <i class="iconfont iconeditor_preview"></i>
      预览
    </div>

    <div class="ui-button submit app-head-save" @click="onSave" :class="{ disable: !canLoad || isEditing }">
      <i class="iconfont iconeditor_save"></i>
      保存
    </div>
    <preview v-if="info" :name="info.name" :show="showPreview" :ifr="`./show.html?id=${info.id}&rnd=${Math.random()}`" @close="showPreview = false" />
  </header>
</template>
<script>
import { saveWorks, getPanoInfo, checkLogin } from "@/api";
import { mapGetters } from "vuex";
// import config from '@/config'
import preview from "@/components/preview";
let hhhreg = /\\\\\\\\/g;

export default {
  name: "app-head",
  data() {
    return {
      showPreview: false,
      canLoad: false,
    };
  },

  components: { preview },

  mounted() {
    this.$bus.on("canLoad", (data) => {
      this.canLoad = data;
      if (data) {
        this.getInfo().then((res) => {
          // getInfo里调用了后端接口，底层用了jquery的网络请求方法，为啥会导致promise嵌套没有展平，res拿到的不是promise 对象的resolve值而是promise对象本身？？？？
          res.then(() => {
            this.$store.commit("TakeInfoSnapShotAtSave")
          })
        });
      }
    });
  },
  computed: {
    ...mapGetters({
      info: "info",
      isShow: "isShow",
      catalogTopology: "catalogTopology",
      currentScene: "scene/currentScene",
      isEditing: "isEditing",
    }),
  },
  methods: {
    checkParams() {
      if (!this.info.name && !this.info.icon && !this.info.description && this.info.scenes.length <= 0) {
        this.$alert({
          content: "您还未创建任何内容哦",
          ok: () => {
            this.$router.push({ path: "/base" });
          },
        });
        return false;
      }
      // if (this.info.scenes.length <= 0 && this.isShow) {
      //   this.$alert({
      //     content: "至少添加一个场景才保存/预览，请前往“场景导航”添加",
      //     forceOK: true,
      //     ok: () => {
      //       this.$router.push({ path: "/navigation" });
      //     },
      //   });
      //   return false;
      // }
      return true;
    },
    onView() {
      if (!this.checkParams()) {
        return;
      }
      this.fixData();
      this.info.scenes = this.info.scenes.map((item) => {
        if (typeof item.someData == "string") {
          item.someData = item.someData.replace(hhhreg, "");
        }
        return item;
      });
      saveWorks(
        {
          password: this.info.password,
          someData: { ...this.info, status: 1 },
        },
        () => {
          this.$msg.success("保存成功");
          document.title = this.info.name;
          this.getInfo();
          this.$store.commit("UpdateIsShowState", true);
          setTimeout(() => {
            if (this.info.scenes.length <= 0 && this.isShow) {
              return this.$alert({
                content: "至少添加一个场景才可预览，请前往“场景导航”添加",
              });
            }
            this.showPreview = true;
          }, 500);
        }
      );
    },

    fixData() {
      // 如果没有设置作品封面，拿第一个一级分组内第一个二级分组内第一个场景作为作品封面。
      if (!this.info.icon) {
        this.info.icon = this.catalogTopology[0].children[0].children[0].icon;
      }

      if (this.info.firstScene) {
        this.info.firstScene = this.info.scenes.find((item) => item.sceneCode == this.info.firstScene.sceneCode);
      }
    },

    onSave() {
      if (!this.checkParams()) {
        return;
      }
      this.fixData();

      this.info.scenes = this.info.scenes.map((item) => {
        if (typeof item.someData == "string") {
          item.someData = item.someData.replace(hhhreg, "");
        }
        return item;
      });

      saveWorks(
        {
          password: this.info.password,
          someData: { ...this.info, status: 1 },
        },
        () => {
          this.$msg.success("保存成功");
          document.title = this.info.name;
          this.getInfo();
          this.$store.commit("UpdateIsShowState", true);
          this.$store.commit("TakeInfoSnapShotAtSave")
        },
        () => {}
      );
    },
    getInfo() {
      return checkLogin().then((res) => {
        return new Promise((resolve, reject) => {
          if (res.code == 0) {
            getPanoInfo("", (data) => {
              this.$store.commit("SetInfo", data);
              this.$store.commit("scene/setScenes", data.scenes);

              let firstScene = "";

              if (data.firstScene) {
                firstScene = data.scenes.find((item) => item.sceneCode == data.firstScene.sceneCode);
              }
              this.$store.commit("scene/setCurrentScene", firstScene || data.scenes[0]);

              // 查询初始场景的所在1级分组
              let catalog = data.catalogs.find((item) => item.id == this.currentScene.category);
              data.catalogRoot.forEach((item) => {
                let temp = item.children && item.children.find((sub) => sub == catalog.id);
                if (temp) {
                  this.$store.commit("scene/setCurrentCatalogRoot", item);
                  return;
                }
              });
              resolve()
            }, (err) => {
              reject(err)
            });
          } else {
            reject()
          }
        })
      });
    },
  },
};
</script>
<style lang="less">
.app-head {
  width: 100%;
  min-width: 50px;
  height: 60px;
  position: relative;
}
.app-head-back {
  color: white;
  display: flex;
  align-items: baseline;
  font-size: 16px;
  position: absolute;
  left: 24px;
  top: 50%;
  transform: translateY(-50%);
  > i {
    margin-right: 15px;
  }
}
.app-head-title {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  font-size: 16px;
  color: white;
}
.app-head-save {
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  right: 10px;
  i {
    font-size: 14px;
    margin-right: 4px;
  }
}

.ui-preview {
  background: #313131;
}

.app-head-view {
  right: 120px;
}
</style>
