<template>
  <RightFillPano>
    <ui-group title="初始画面" borderBottom>
      <ui-group-option>
        <div class="init-pic" :class="{ disabled: isEdit }">
          <img :src="getFileUrl(setting!.cover)" class="init-puc-cover" />
          <div class="init-pic-set" @click="enterSetPic">设置</div>
        </div>
      </ui-group-option>
    </ui-group>

    <ui-group title="设置天空">
      <ui-group-option>
        <selectBack :value="setting?.back" @update:value="changeBack" />
      </ui-group-option>
    </ui-group>
  </RightFillPano>
</template>

<script lang="ts" setup>
import { RightFillPano } from "@/layout";
import { enterEdit, enterOld, setting, isEdit, updataSetting } from "@/store";
import { ref } from "vue";
import { togetherCallback, getFileUrl, loadPack } from "@/utils";
import { showRightPanoStack, showRightCtrlPanoStack } from "@/env";
import { analysisPose, sdk } from "@/sdk";
import selectBack from "./select-back.vue";

const enterSetPic = () => {
  enterEdit(
    togetherCallback([
      showRightPanoStack.push(ref(false)),
      showRightCtrlPanoStack.push(ref(false)),
    ])
  );
  enterOld(async () => {
    const dataURL = await sdk.screenshot(300, 150);
    const res = await fetch(dataURL);
    const blob = await res.blob();

    setting.value = {
      ...setting.value!,
      cover: { url: dataURL, blob },
      pose: analysisPose(sdk.getPose()),
    };
    await updataSetting();
  });
};

let initBack = setting.value!.back;
let isFirst = true;
const changeBack = (back: string) => {
  setting.value!.back = back;

  if (isFirst) {
    let isSave = false;
    isFirst = false;
    enterEdit(() => {
      if (!isSave) {
        setting.value!.back = initBack;
      }
      isFirst = true;
    });
    enterOld(async () => {
      initBack = setting.value!.back;
      isSave = true;
      await loadPack(updataSetting());
    });
  }
};
</script>

<style scoped lang="scss">
.init-pic {
  height: 150px;
  border-radius: 4px;
  overflow: hidden;
  position: relative;
}

.init-puc-cover {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.init-pic-set {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.5);
  font-size: 12px;
  color: #fff;
  line-height: 32px;
  z-index: 1;
  text-align: center;
  cursor: pointer;
}
</style>
