<template>
  <RightFillPano>
    <ui-group borderBottom>
      <template #header>
        <Actions class="edit-header" :items="options" single />
      </template>
    </ui-group>
    <ui-group title="测量列表">
      <template #icon>
        <ui-icon 
          ctrl
          :type="custom.showMeasures ? 'eye-s' : 'eye-n'" 
          @click="custom.showMeasures = !custom.showMeasures" 
        />
      </template>
      <ui-group-option>
        <ui-input type="text" width="100%" placeholder="搜索" v-model="keyword">
          <template #preIcon>
            <ui-icon type="search" />
          </template>
        </ui-input>
      </ui-group-option>
      <MeasureSign 
        v-for="measure in filterMeasures" 
        :key="measure.id" 
        :measure="measure" 
        :selected="selectMeasure === measure"
        @delete="deleteMeasure(measure)"
        @select="selectMeasure = measure"
      />
    </ui-group>
  </RightFillPano>

  <EditMeasure 
    v-if="editMeasure" 
    :measure="editMeasure" 
    @close="editMeasure = null"
    @submit="measure => measures.push(measure)"
  />
</template>

<script lang="ts" setup>
import MeasureSign from './sign.vue'
import Actions from '@/components/actions/index.vue'
import EditMeasure from './edit.vue'
import { RightFillPano } from '@/layout'
import { computed, ref } from 'vue';
import { custom, showMeasuresStack } from '@/env'
import { measures, MeasureTypeMeta, MeasureType, createMeasure, autoSaveMeasures } from '@/store'
import { useViewStack } from '@/hook'

import type { Measure } from '@/store'
import type { ActionsItem } from '@/components/actions/index.vue'

const keyword = ref('')
const filterMeasures = computed(() => measures.value.filter(measure => measure.desc.includes(keyword.value)))
const selectMeasure = ref<Measure | null>(null)
const editMeasure = ref<Measure | null>(null)
const enterCreateMeasure = (type: MeasureType) => {
  editMeasure.value = createMeasure({ type })
}
const options: ActionsItem[] = [
  {
    icon: MeasureTypeMeta[MeasureType.free].icon,
    text: MeasureTypeMeta[MeasureType.free].desc,
    action: enterCreateMeasure.bind(null, MeasureType.free)
  },
  {
    icon: MeasureTypeMeta[MeasureType.vertical].icon,
    text: MeasureTypeMeta[MeasureType.vertical].desc,
    action: enterCreateMeasure.bind(null, MeasureType.vertical)
  },
  {
    icon: MeasureTypeMeta[MeasureType.area].icon,
    text: MeasureTypeMeta[MeasureType.area].desc,
    action: enterCreateMeasure.bind(null, MeasureType.area)
  }
]


const deleteMeasure = (measure: Measure) => {
  const index = measures.value.indexOf(measure)
  measures.value.splice(index, 1)
}

useViewStack(() => showMeasuresStack.push(ref(true)))
useViewStack(autoSaveMeasures)
</script>