import { defineComponent, onMounted } from 'vue'
import useLayoutStore from '../useLayoutStore'
import { OhVueIcon, addIcons } from 'oh-vue-icons'
import { MdAdd } from 'oh-vue-icons/icons'
import useRouterStore from '@/useRouterStore'
import Sortable from 'sortablejs'

addIcons(MdAdd)

export default defineComponent(() => {
  const layout = useLayoutStore()
  const router = useRouterStore()
  let container: HTMLDivElement | null = null
  onMounted(() => {
    if (!container) return
    new Sortable(container, {
      animation: 400,
      scroll: true,
      scrollSensitivity: 200,
      scrollSpeed: 10,
      invertSwap: true,
      invertedSwapThreshold: 1,
      filter: '.operation-button',
      ghostClass: 'opacity-20',
      dragClass: 'dragging-block',
      onStart: (e) => {
        //   layout.moving.id = e.item.id
        //   layout.moving.type = e.item.dataset?.type || ''
      },
      onMove: (e) => {
        if (e.related.className.includes('operation-button') && e.willInsertAfter) return false
      },
      onEnd: (e) => {
        //   const oldPath = e.from.dataset.path
        //   const newPath = e.to.dataset.path
        //   if (e.oldIndex === undefined || e.newIndex === undefined || !oldPath || !newPath) return
        //   const oldIndex = e.oldIndex
        //   const newIndex = e.newIndex
        //   const oldList = useSortList(oldPath as any)
        //   const newList = useSortList(newPath as any)
        //   const item = oldList[oldIndex]
        //   if (!item || !isReactive(oldList) || !isReactive(newList)) return
        //   oldList.splice(oldIndex, 1)
        //   newList.splice(newIndex, 0, item)
        //   layout.moving.id = ''
        //   layout.moving.type = ''
      }
    })
  })
  return () => (
    <div
      class="absolute left-0 top-0 w-full h-screen overflow-y-auto no-scrollbar pt-[240px] px-[calc((100%_-_var(--main-width))_/_2)]"
      onScroll={(e) => {
        const h = (e.target as any).scrollTop
        if (h > 60) {
          // 需要移动搜索框和时间
          layout.isCompact = true
        } else {
          layout.isCompact = false
        }
      }}
    >
      <div
        class="w-full grid justify-center grid-flow-row-dense pb-[200px]"
        style="grid-template-columns:repeat(auto-fill, var(--block-size));grid-auto-rows:var(--block-size);grid-template-rows:var(--block-size)"
        ref={(el) => (container = el as any)}
      >
        <div class="w-full h-full flex justify-center items-center p-[var(--block-padding)] relative operation-button">
          <div
            class="w-full h-full overflow-hidden rounded-[calc(var(--block-radius)_*_var(--block-size))] bg-white/80 backdrop-blur flex justify-center items-center cursor-pointer hover:scale-105 transition-all"
            onClick={() => {
              router.path = 'global-adder'
            }}
          >
            <OhVueIcon name="md-add" fill="white" scale={2} />
          </div>
        </div>
      </div>
    </div>
  )
})
