<template>
  <header class="app-head" app-border dir-bottom v-if="info">
    <a class="app-head-back" :href="`./material.html?lang=${$lang}&from=${routerForm}#/works`">
      <i class="iconfont icon-editor_return"></i>
      {{ back_myworks }}
    </a>

    <span class="app-head-title">{{ info.work.name }}</span>
    <div class="app-head-save ui-button deepcancel app-head-view" @click="onView" :class="{ disable: !canLoad || isEditing }">
      <i class="iconfont icon-editor_play"></i>
      {{ preview }}
    </div>
    <div class="ui-button submit app-head-save" @click="onSave" :class="{ disable: !canLoad || isEditing }">
      <i class="iconfont icon-editor_save"></i>
      {{ savetips }}
    </div>
    <preview v-if="info" :key="Math.random()" :name="info.work.name" :show="showPreview" :ifr="`./show.html?id=${info.work.id}&lang=${$lang}&rnd=${Math.random()}`" @close="showPreview = false" />
  </header>
</template>
<script>
import { saveWorks, getPanoInfo, checkLogin, getWorkInfo } from "@/api";
import { mapGetters } from "vuex";
// import config from '@/config'
import preview from "@/components/preview";
import { i18n } from "@/lang";
import { $waiting } from "@/components/shared/loading";
import browser from "@/utils/browser";

let hhhreg = /\\\\\\\\/g;

export default {
  name: "app-head",
  data() {
    return {
      back_myworks: i18n.t("edit_page.back_myworks"),
      preview: i18n.t("edit_page.preview"),
      savetips: i18n.t("edit_page.save"),

      showPreview: false,
      canLoad: false,
      hiddenSave: false,
    };
  },

  components: { preview },
  watch: {
    // "$route.name": {
    //   immediate: true,
    //   handler: function (newVal) {
    //     if (newVal == "hotspot") {
    //       // this.hiddenSave = true;
    //     } else {
    //       // this.hiddenSave = false;
    //     }
    //   },
    // },
    sceneList: {
      handler: function (newVal, oldVal) {
        if (newVal.length != oldVal.length) {
          // console.error("sceneList change");
          let currentScene = newVal.find((item) => item.id == this.currentScene.id);
          if (!currentScene) {
            //如果找不到当前选择的场景，则情况。重新遍历查找
            this.$store.commit("scene/setCurrentScene", null);
          }
        }
      },
      deep: true,
    },
  },
  mounted() {
    this.getSettingsInfo();
    this.$bus.on("canLoad", (data) => {
      // console.error("canLoad", data);
      this.canLoad = data;
      // if (data) {
      // this.getInfo().then((res) => {
      //   // getInfo里调用了后端接口，底层用了jquery的网络请求方法，为啥会导致promise嵌套没有展平，res拿到的不是promise 对象的resolve值而是promise对象本身？？？？
      //   res.then(() => {
      //     // alert(1);
      //     this.$store.commit("TakeInfoSnapShotAtSave");
      //   });
      // });
      // }
    });
  },
  computed: {
    ...mapGetters({
      // info: "info",
      baseInfo: "base/baseInfo",
      sceneList: "base/sceneList",
      isShow: "isShow",
      catalogTopology: "catalogTopology",
      currentScene: "scene/currentScene",
      isEditing: "isEditing",
      saveApiList: "scene/saveApiList",
      currentRootId: "navigation/currentRootId",
      currentSecondId: "navigation/currentSecondId",
    }),

    info() {
      if (this.baseInfo) {
        this.$store.commit("base/initDefaultData");
        //初始化

        if (!this.currentScene) {
          console.error("初始化");
          let firstScene = null;
          if (this.baseInfo.firstScene) {
            firstScene = this.baseInfo.firstScene;
          } else {
            // firstScene = this.baseInfo.navigationTrees[0].children[0];
            firstScene = this.sceneList[0];
          }
          this.$store.commit("scene/setCurrentScene", firstScene);
          let activeScene = null;
          this.baseInfo.navigationTrees.forEach((item, index) => {
            activeScene = item.children.find((pano) => pano.id == firstScene.id);

            if (activeScene) {
              this.$store.commit("scene/setCurrentScenesList", item.children);
              this.$store.commit("navigation/setData", { currentSecondId: null, currentRootId: item.id });
              // throw new Error("LoopTerminated");
            }
            item = item.children.forEach((s_item, s_index) => {
              activeScene = s_item.children.find((pano) => pano.id == firstScene.id);

              if (activeScene) {
                this.$store.commit("scene/setCurrentScenesList", s_item.children);
                this.$store.commit("navigation/setData", { currentSecondId: s_item.id, currentRootId: item.id });
                // throw new Error("LoopTerminated");
              }
              s_item = s_item.children.forEach((t_item, t_index) => {
                activeScene = t_item.children.find((pano) => pano.id == firstScene.id);

                if (activeScene) {
                  this.$store.commit("scene/setCurrentScenesList", s_item.children);
                  this.$store.commit("navigation/setData", { currentSecondId: s_item.id, currentRootId: item.id });
                  // throw new Error("LoopTerminated");
                }
              });
            });
          });
        }
        console.error(this.currentSecondId);
        // if (data.firstScene) {
        //   firstScene = data.scenes.find((item) => item.sceneCode == data.firstScene.sceneCode);
        // }

        // //判断列表里是否有全景图
        // if (data.scenes.some((item) => item.type == "pano") && firstScene && firstScene.type == "4dkk") {
        //   console.log(this.currentScene.sceneCode);
        //   //如果当前有选中场景，则激活选中场景，无则显示第一个全景图
        //   firstScene = this.currentScene.sceneCode ? this.currentScene : data.scenes.find((item) => item.type == "pano");
        // }

        // console.log(firstScene, "firstScene");
        // this.$store.commit("scene/setCurrentScene", firstScene || data.scenes[0]);
      }
      return this.baseInfo;
    },

    routerForm() {
      const from = browser.urlQueryValue("from");
      return from;
    },
  },
  methods: {
    checkParams() {
      // if (!this.info.work.name && !this.info.work.icon && !this.info.work.description && this.info.scenes.length <= 0) {
      if (!this.baseInfo.work.name && !this.baseInfo.work.icon && !this.baseInfo.work.description) {
        this.$alert({
          content: this.$i18n.t("gather.nothing_edit"),
          ok: () => {
            this.$router.push({ path: "/base" });
          },
        });
        return false;
      }
      return true;
    },
    onView() {
      if (!this.checkParams()) {
        return;
      }
      const isFixData = this.fixData();
      if (isFixData) {
        // this.info.scenes = this.info.scenes.map((item) => {
        //   if (typeof item.someData == "string") {
        //     item.someData = item.someData.replace(hhhreg, "");
        //   }
        //   return item;
        // });
        $waiting.show();

        let promises = [];
        if (this.saveApiList.length) {
          let idx = this.saveApiList.find((item) => item == "navigation");
          console.error(idx);
          let length = 0;
          if (idx) {
            //优先保存导航树
            this.$store.dispatch(`navigation/save`).then((res) => {
              this.saveApiList.forEach((item) => {
                if (item != "navigation") {
                  promises.push(this.$store.dispatch(`${item}/save`));
                }
              });
              let currentRouter = this.saveApiList.find((item) => item == this.$route.name);
              if (!currentRouter) {
                promises.push(this.$store.dispatch(`${this.$route.name}/save`));
              }
              Promise.all(promises)
                .then((res) => {
                  console.log("Promise.all success", res);
                  this.$store.commit(`scene/removeSaveApi`);
                  this.$msg.success(i18n.t("gather.save_done"));
                  //成功后查看
                  $waiting.hide();
                  if (this.sceneList <= 0 && this.isShow) {
                    return this.$alert({
                      content: this.$i18n.t("gather.at_least_one_scene"),
                    });
                  }
                  this.showPreview = true;
                })
                .catch((err) => {
                  console.error("Promise.all failed", err);
                });
            });
          } else {
            this.saveApiList.forEach((item) => {
              promises.push(this.$store.dispatch(`${item}/save`));
            });
            let currentRouter = this.saveApiList.find((item) => item == this.$route.name);
            if (!currentRouter) {
              promises.push(this.$store.dispatch(`${this.$route.name}/save`));
            }
            Promise.all(promises)
              .then((res) => {
                console.log("Promise.all success", res);
                this.$store.commit(`scene/removeSaveApi`);
                this.$msg.success(i18n.t("gather.save_done"));
                //成功后查看
                $waiting.hide();
                if (this.sceneList <= 0 && this.isShow) {
                  return this.$alert({
                    content: this.$i18n.t("gather.at_least_one_scene"),
                  });
                }
                this.showPreview = true;
              })
              .catch((err) => {
                console.error("Promise.all failed", err);
              });
          }
        } else {
          this.$store.dispatch(`${this.$route.name}/save`).then((res) => {
            this.$store.commit(`scene/removeSaveApi`);
            this.$msg.success(i18n.t("gather.save_done"));
            //成功后查看
            $waiting.hide();
            if (this.sceneList <= 0 && this.isShow) {
              return this.$alert({
                content: this.$i18n.t("gather.at_least_one_scene"),
              });
            }
            this.showPreview = true;
          });
        }

        // saveWorks(
        //   {
        //     password: this.info.work.password,
        //     someData: { ...this.info, status: 1 },
        //   },
        //   () => {
        //     this.$msg.success(this.$i18n.t("gather.save_done"));
        //     // document.title = this.info.name;
        //     document.title = this.info.work.name || this.$i18n.t("gather.no_title");
        //     // this.getInfo().then((res) => {
        //     //   // getInfo里调用了后端接口，底层用了jquery的网络请求方法，为啥会导致promise嵌套没有展平，res拿到的不是promise 对象的resolve值而是promise对象本身？？？？
        //     //   res.then(() => {
        //     //     this.$store.commit("UpdateIsShowState", true);
        //     //     $waiting.hide()
        //     //     setTimeout(() => {
        //     //       if (this.info.scenes.length <= 0 && this.isShow) {
        //     //         return this.$alert({
        //     //           content: this.$i18n.t('gather.at_least_one_scene'),
        //     //         });
        //     //       }
        //     //       this.showPreview = true;
        //     //     }, 500);
        //     //   })
        //     // });
        //     $waiting.hide();
        //     if (this.info.scenes.length <= 0 && this.isShow) {
        //       return this.$alert({
        //         content: this.$i18n.t("gather.at_least_one_scene"),
        //       });
        //     }
        //     this.showPreview = true;
        //   }
        // );
      }
    },

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

      if (this.baseInfo.firstScene) {
        this.baseInfo.firstScene = this.sceneList.find((item) => item.sceneCode == this.baseInfo.firstScene.sceneCode);
      }
      const scenes = this.sceneList;
      // debugger
      // if (scenes && scenes.length > 0) {
      //   scenes.forEach((scene, index) => {
      //     if (scene.someData && scene.someData.hotspots && scene.someData.hotspots.length > 0) {
      //       this.lockHotspotResourceTree(index, scene.someData.hotspots);
      //     }
      //   });
      // }
      if (this.baseInfo && this.baseInfo.workHotList && this.baseInfo.workHotList.length > 0) {
        this.lockHotspotResourceTree(this.baseInfo.workHotList);
      }

      //开场校验
      if (this.baseInfo?.workCoverType?.isShowCover === 1) {
        if (this.baseInfo.workCoverType.coverSelect === "videoAndImg") {
          if (!this.baseInfo.workCoverType.coverPc || !this.baseInfo.workCoverType.coverMo || !this.baseInfo.workCoverType.videoPc || !this.baseInfo.workCoverType.videoMo) {
            this.$msg.warning(this.$i18n.t("gather.converinfo_no_valid"));
            return false;
          }
        }
        if (this.baseInfo.workCoverType.coverSelect === "video") {
          if (!this.baseInfo.workCoverType.videoPc || !this.baseInfo.workCoverType.videoMo || this.baseInfo.workCoverType.videoPc == "" || this.baseInfo.workCoverType.videoMo == "") {
            this.$msg.warning(this.$i18n.t("gather.converinfo_no_valid"));
            return false;
          }
        }
        if (this.baseInfo.workCoverType.coverSelect === "img") {
          if (!this.baseInfo.workCoverType.coverPc || !this.baseInfo.workCoverType.coverMo || this.baseInfo.workCoverType.coverPc == "" || this.baseInfo.workCoverType.coverMo == "") {
            this.$msg.warning(this.$i18n.t("gather.converinfo_no_valid"));
            return false;
          }
        }

        //新增不上传背景底图限制
        if (this.baseInfo.workCoverType.coverImgBac === "imgTile") {
          if (!this.baseInfo.workCoverType.coverBac) {
            this.$msg.warning(this.$i18n.t("gather.converinfo_no_valid"));
            return false;
          }
        }
      }
      return true;
      // this.lockHotspotResourceTree();
      // fodderId:[] 资源引用给后端
    },
    /**
     * 给热点的资源引用上锁
     */
    // lockHotspotResourceTree(sceneIndex, hotspots) {
    lockHotspotResourceTree(hotspots) {
      hotspots.forEach((item, index) => {
        // const target = this.info.scenes[sceneIndex].someData.hotspots[index];
        let fodderId = [];
        switch (item.hotspotType) {
          case "image":
            fodderId = item.image.reduce((p, c) => p.concat(c["id"]), []).map((i) => i);
            item.fodderId = fodderId;
            // fodderId = item.content.image.reduce((p, c) => p.concat(c["id"]), []).map((i) => i);
            // item.fodderId = fodderId;
            break;
          case "audio":
          item.fodderId = [item.audio.id].map((i) => i);
            // item.fodderId = [item.content.audio.id].map((i) => i);
            break;
          case "imageText":
            fodderId = item.imageTextInfo.imageList.reduce((p, c) => p.concat(c["id"]), []).map((i) => i);
            item.imageTextInfo.audio.id && fodderId.push(item.imageTextInfo.audio.id);
            item.fodderId = fodderId;
            // fodderId = item.content.imageTextInfo.imageList.reduce((p, c) => p.concat(c["id"]), []).map((i) => i);
            // item.imageTextInfo.audio.id && fodderId.push(item.content.imageTextInfo.audio.id);
            // item.fodderId = fodderId;
            break;
          case "video":
          item.fodderId = [item.video.id];
            // item.fodderId = [item.content.video.id];
            break;
          case "scene":
            item.fodderId = [item.scene.fodderId].map((i) => i);
            // item.fodderId = [item.content.scene.fodderId].map((i) => i);
            break;
          default:
            // target.fodderId = [];
            item.fodderId = [];
            break;
        }
      });
    },

    onSave() {
      if (!this.checkParams()) {
        return;
      }
      const isFixData = this.fixData();
      if (isFixData) {
        // this.sceneList = this.sceneList.map((item) => {
        //   if (typeof item.someData == "string") {
        //     item.someData = item.someData.replace(hhhreg, "");
        //   }
        //   return item;
        // });
        $waiting.show();

        // console.error(this.$router.name)
        let promises = [];
        if (this.saveApiList.length) {
          let idx = this.saveApiList.find((item) => item == "navigation");
          console.error(idx);
          let length = 0;
          if (idx) {
            //优先保存导航树
            this.$store.dispatch(`navigation/save`).then((res) => {
              this.saveApiList.forEach((item) => {
                if (item != "navigation") {
                  promises.push(this.$store.dispatch(`${item}/save`));
                  // this.$store.dispatch(`${item}/save`).then((res) => {});
                }
              });
              let currentRouter = this.saveApiList.find((item) => item == this.$route.name);
              if (!currentRouter) {
                promises.push(this.$store.dispatch(`${this.$route.name}/save`));
              }
              Promise.all(promises)
                .then((res) => {
                  console.log("Promise.all success", res);
                  this.$store.commit(`scene/removeSaveApi`);
                  this.$msg.success(i18n.t("gather.save_done"));
                })
                .catch((err) => {
                  console.error("Promise.all failed", err);
                });
            });
          } else {
            this.saveApiList.forEach((item) => {
              promises.push(this.$store.dispatch(`${item}/save`));
              // this.$store.dispatch(`${item}/save`).then((res) => {});
            });
            let currentRouter = this.saveApiList.find((item) => item == this.$route.name);
            if (!currentRouter) {
              promises.push(this.$store.dispatch(`${this.$route.name}/save`));
            }
            Promise.all(promises)
              .then((res) => {
                console.log("Promise.all success", res);
                this.$store.commit(`scene/removeSaveApi`);
                this.$msg.success(i18n.t("gather.save_done"));
              })
              .catch((err) => {
                console.error("Promise.all failed", err);
              });
          }
        } else {
          this.$store.dispatch(`${this.$route.name}/save`).then((res) => {
            this.$store.commit(`scene/removeSaveApi`);
            this.$msg.success(i18n.t("gather.save_done"));
          });
        }
        // this.$store.commit(`scene/removeSaveApi`);
        // this.$msg.success(i18n.t("gather.save_done"));
        // saveWorks(
        //   {
        //     password: this.info.password,
        //     someData: { ...this.info, status: 1 },
        //   },
        //   () => {
        //     this.$msg.success(this.$i18n.t("gather.save_done"));
        //     // document.title = this.info.name;
        //     document.title = this.info.name || this.$i18n.t("gather.no_title");
        //     $waiting.hide();
        //     // this.getInfo();
        //     // this.$store.commit("UpdateIsShowState", true);
        //     this.$store.commit("TakeInfoSnapShotAtSave");
        //   },
        //   () => {}
        // );
      }
    },
    getInfo() {
      return checkLogin().then((res) => {
        return new Promise((resolve, reject) => {
          $waiting.hide();

          if (res.code == 0) {
            // $waiting.show();
            // getPanoInfo(
            //   "",
            //   (data) => {
            //     this.$store.commit("SetInfo", data);
            //     this.$store.commit("scene/setScenes", data.scenes);
            //     $waiting.hide();
            //     let firstScene = "";
            //     if (data.firstScene) {
            //       firstScene = data.scenes.find((item) => item.sceneCode == data.firstScene.sceneCode);
            //     }
            //     //判断列表里是否有全景图
            //     if (data.scenes.some((item) => item.type == "pano") && firstScene && firstScene.type == "4dkk") {
            //       console.log(this.currentScene.sceneCode);
            //       //如果当前有选中场景，则激活选中场景，无则显示第一个全景图
            //       firstScene = this.currentScene.sceneCode ? this.currentScene : data.scenes.find((item) => item.type == "pano");
            //     }
            //     console.log(firstScene, "firstScene");
            //     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();
          }
        });
      });
    },

    getSettingsInfo() {
      // this.$store.commit("base/setData", this.info);
      getWorkInfo(
        {},
        (res) => {
          let data = res.data;
          this.$store.commit("base/initbaseInfo", data);

          this.$store.commit("UpdateIsShowState", true);
          // OnlineDetector.valid();
        },
        () => {}
      );
    },
  },
};
</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>
