<script setup>
import { ref, watch, onBeforeUnmount } from "vue"
import { useSkyLight } from "../hooks/useSkyLight"
import { useMapStore } from "../stores/mapStore"
import CustomSwitch from "./CustomSwitch.vue"

const store = useMapStore()
const { skyGroup, lightGroup, isFixedLightPos, init, setTime } = useSkyLight(store.map, {
  baseSunLight: 6,
  baseMoonLight: 2,
  baseAmbientLight: 1,
})
const currentTime = ref(420)

const timeOptions = Array.from({ length: 24 }).map((_, i) => ({
  label: `${i}时`,
  value: i * 60,
}))

const defaultLights = JSON.parse(JSON.stringify(store.map.mapData.options?.lightList ?? []))

const lightStatus = ref(false)
function changeLightDisplay (status) {
  if (status) {
    store.map.mapData.options.lightList = defaultLights.filter(i => {
      return i.name === 'PointLight'
    })
  } else {
    store.map.mapData.options.lightList = defaultLights
    currentTime.value = 420
  }
  lightGroup.visible = lightStatus.value = status
  store.map.addLight()
}

store.map.amap.maxPitch = 85
window.$setTime = setTime

init()
setTime(currentTime.value)

watch(currentTime, (value) => {
  setTime(value)

  if (value >= 360 && value < 1080) {
    setPointLightStatus(true)
  } else {
    setPointLightStatus(false)
  }
  store.map.addLight()
}, {
  immediate: true,
})

function setPointLightStatus (status) {
  store.map.mapData.options?.lightList?.filter((light) => {
    return light.name === "PointLight";
  }).forEach((light) => {
    if ('disable' in light) {
      light['disable'] = status
    }
  })
}

onBeforeUnmount(() => {
  skyGroup.value?.dispose()
})

// 暴露方法
defineExpose({
  setTime,
  changeLightDisplay
})
</script>

<template>
  <div class="sky-select">
    <div style="font-size: 12px;">光线设置:</div>
    <CustomSwitch :modelValue="lightStatus" @update:model-value="changeLightDisplay" off-label="默认" active-label="动态" />
    <template v-if="lightStatus">
      <CustomSwitch v-model="isFixedLightPos" off-label="随时间" active-label="固定位置" />
      <select name="time" id="time" v-model="currentTime">
        <option v-for="time in timeOptions" :key="time.value" :value="time.value">{{ time.label }}</option>
      </select>
    </template>
  </div>
</template>

<style scoped>
.sky-select {
  display: none; /* 隐藏控件 */
  color: white;
  text-shadow: 1px 1px 1px #000;
}

select {
  min-width: 100px;
}
</style>
