<template>
  <div class="main">
    <m-title
      area="title"
      @click.prevent.stop="save"
      @touch="showLayoutModal = true"
      >静安智慧房管</m-title
    >
    <m-grid
      v-if="layout.boxNum > 0"
      :template="layout.template"
      columns="1fr 1.5fr 1fr"
      :rows="`${layout.rows}`"
    >
      <div
        v-for="(_, index) in new Array(layout.boxNum)"
        :key="index"
        class="box"
        :area="`box${index + 1}`"
        :class="{ done: !!components[index] }"
      >
        <component
          :is="componentList[components[index]]"
          v-if="!!components[index]"
        />
        <img
          v-else
          class="add-btn"
          src="@/assets/images/add.png"
          @click.prevent.stop="openComponentModal(index)"
        />
        <n-icon
          v-show="!!components[index]"
          class="del-btn"
          size=".16rem"
          @click="onCancelComponent(index)"
        >
          <TrashBin />
        </n-icon>
      </div>
    </m-grid>
  </div>
  <LayoutModal v-model="showLayoutModal" @select="onChangeLayout" />
  <ComponentModal v-model="showComponentModal" @select="onSelectComponent" />
</template>

<script lang="ts" setup>
import LayoutModal from './components/layout-modal.vue'
import ComponentModal from './components/component-modal.vue'
import useLayout from '@/hooks/useLayout'
import useComponent from '@/hooks/useComponent'
import useConfig from '@/hooks/useConfig'
import { TrashBin } from '@vicons/ionicons5'

const { showLayoutModal, layout, onChangeLayout } = useLayout()
const {
  components,
  componentList,
  showComponentModal,
  openComponentModal,
  onCancelComponent,
  onSelectComponent,
} = useComponent()
const save = () => {
  const data = {
    layout: layout.value,
    components: components.value,
  }
  useConfig(JSON.stringify(data))
}
</script>

<style lang="stylus" scoped>
@import '../components/MyComponent/main.styl'
.main
  width 100%
  height 100%
  display flex
  flex-direction column
.box
  border-radius .02rem
  border .01rem dashed #4270B3
  background rgba(54,65,77,.5)
  $blur(0.01rem)
  position relative
  overflow hidden
  &:hover
    >.del-btn
      opacity 0.7
  &.done
    border none
    background transparent
    $blur(0)
  >.add-btn
    width .2rem
    height @width
    position absolute
    top 50%
    left 50%
    transform translate(-50%,-50%)
    opacity .8
    cursor pointer
    transition all .2s ease-in-out
    &:hover
      opacity 1
      width .24rem
      height @width
  >.del-btn
    position absolute
    top .05rem
    right .05rem
    cursor pointer
    color red
    opacity 0
    transition opacity .2s ease-in-out
    &:hover
      opacity 1
</style>
