<script lang="ts" setup>
import { computed, nextTick, onMounted, reactive, ref, watch } from 'vue'
import Masonry from 'masonry-layout'
import { useInfiniteScroll } from '@vueuse/core'
import { debounce } from 'lodash-es'
import imagesloaded from 'imagesloaded'
import { useMessage } from 'naive-ui'
import { timeOptions, viewOptions } from '@/config/home'
import { off, on } from '@/utils/domUtils'
import { useTask } from '@/store/modules/task'
import { TASK_STATUS_OBJ } from '@/enums/index'
import { formatToDateHMS } from '@/utils/dateUtil'
import { getSimilarityList, getTaskDetailInfo } from '@/api/task/task'
import emitter from '@/utils/mitt'

const emit = defineEmits<{
  (e: 'reject', params: any)
  (e: 'approval', params: any)
}>()

const cardStyle = {
  '--n-padding-bottom': '40px',
  '--n-padding-left': '120px',
}

const totalCount = ref(0)
const timeRange = ref('all')
const timeLabel = computed(() => {
  const item = timeOptions.find((option) => {
    return option.value === timeRange.value
  })

  return item?.label
})

const viewMode = ref('masonry')

const viewLabel = computed(() => {
  const item = viewOptions.find((option) => {
    return option.value === viewMode.value
  })

  return item?.label
})

const taskStore = useTask()
const masonryRef = ref<ComponentRef>(null)
const el = ref<HTMLDivElement | null>(null)
const listData = ref<any[]>([])
const taskDetailInfo = ref<any>({})
const pagination = reactive({
  pageNo: 0,
  pageSize: 30,
})
const loading = ref(false)
let _masonry: null | Masonry = null
const show = ref(false)

const sortBy: any = {
  orderType: 'desc',
  orderName: 'similarityScore',
}
const batch = ref(false)
let _imagesload: any
const message = useMessage()

const layout = debounce(() => {
  if (!show.value)
    return

  if (_masonry !== null)
    (_masonry as any).destroy()

  _masonry = new Masonry(masonryRef.value as any, {
    itemSelector: '.grid-item',
    columnWidth: 214,
    percentPosition: true,
    stagger: 10,
  })

  _imagesload = imagesloaded('.grid-item')

  _imagesload.on('done', (instance) => {
    (_masonry as any).layout()
    if (!el.value)
      return
    loading.value = false
  })

  _imagesload.on('fail', (instance) => {
    message.error('图片错误')
    loading.value = false
  })
}, 300)

watch(viewMode, () => {
  layout()
})

let canloadMore = true

useInfiniteScroll(
  el as any,
  () => {
    loadMore()
  },
  { distance: 10, canLoadMore: () => canloadMore },
)

async function loadMore() {
  if (loading.value || el.value == null)
    return
  const taskId = taskStore.getActiveId

  if (!taskId)
    return

  const more = await fetchList()
  listData.value.push(...more)
  nextTick(() => {
    layout()
  })
}

async function fetchList() {
  loading.value = true
  try {
    pagination.pageNo += 1
    const { data, pageCount, total } = await getSimilarityList(
      {
        ...pagination,
        ...sortBy,
        pictureId: taskDetailInfo.value.ocrPicture.id,
      },
    )
    canloadMore = pageCount >= pagination.pageNo && pageCount > 0
    totalCount.value = total

    return data
  }
  catch (error) {
    canloadMore = false
    return []
  }
}

let start: { x: number, y: number } | null = null
let selectionBox: HTMLDivElement | null
const selectIds = ref<string[]>([])

function downHandler(event: MouseEvent) {
  event.stopPropagation()

  if (!selectionBox || batch.value === false)
    return

  const classname = (event.target as any).className

  if (!classname.includes('checkbox')) {
    selectIds.value.length = 0
    start = { x: event.clientX, y: event.clientY }
    selectionBox.style.width = '0'
    selectionBox.style.height = '0'
    selectionBox.style.left = `${start.x}px`
    selectionBox.style.top = `${start.y}px`
    selectionBox.style.display = 'block'
    selectionBox.style.zIndex = '9999'
  }
}

function imUpdateSelectIds(x: number, y: number, w: number, h: number) {
  const items = document.querySelectorAll('.grid-item')

  items.forEach((item: HTMLDivElement) => {
    const rect = item.getBoundingClientRect()
    const index = selectIds.value.indexOf(item.dataset.id!)

    if (rect.right > x && rect.bottom > y && rect.left < x + w && rect.top < y + h)
      index === -1 && selectIds.value.push(item.dataset.id!)
    else index !== -1 && selectIds.value.splice(index, 1)
  })
}

function moveHandler(e: MouseEvent) {
  if (!selectionBox || !start || batch.value === false)
    return

  const x = Math.min(e.clientX, start.x)
  const y = Math.min(e.clientY, start.y)
  const w = Math.abs(e.clientX - start.x)
  const h = Math.abs(e.clientY - start.y)

  selectionBox.style.width = `${w}px`
  selectionBox.style.height = `${h}px`
  selectionBox.style.left = `${x}px`
  selectionBox.style.top = `${y}px`

  imUpdateSelectIds(x, y, w, h)
}

function upHandler(event: MouseEvent) {
  if (!selectionBox)
    return

  selectionBox.style.display = 'none'
  start = null
}

const gridHeight = computed(() => {
  return viewMode.value !== 'masonry' ? '157px' : ''
})

function addListeners() {
  selectionBox = document.querySelector('.selection-box') as HTMLDivElement

  on(el.value!, 'mousedown', downHandler)
  on(el.value!, 'mousemove', moveHandler)
  on(document, 'mouseup', upHandler)

  emitter.on('refresh', refreshHandler)
}

function removeListeners() {
  off(el.value!, 'mousedown', downHandler)
  on(el.value!, 'mousemove', moveHandler)
  on(document, 'mouseup', upHandler)

  emitter.off('refresh', refreshHandler)
}

async function afterEnter() {
  addListeners()
  refreshHandler()
}

function afterLeave() {
  removeListeners()
}

onMounted(() => {
  show.value && addListeners()
})

function showModal() {
  show.value = true
}

function closeModal(event: MouseEvent) {
  show.value = false
}

defineExpose({
  showModal,
})

function forwardHandler() {
  taskStore.forward()
}

function backHandler() {
  taskStore.back()
}

function onCheckChange(checked: any, item: any) {
  const index = selectIds.value.indexOf(item.id)

  if (index === -1 && checked)
    selectIds.value.push(item.id)

  else
    selectIds.value.splice(index, 1)
}

watch(() => selectIds.value.length, () => {
  const list = listData.value
  for (const item of list) {
    if (selectIds.value.includes(item.id))
      item.checked = true
    else
      item.checked = false
  }
})

const showActions = computed(() => {
  return selectIds.value.length > 0 && batch
})

function setBatch(value: boolean) {
  batch.value = value
  if (value === false)
    selectIds.value.length = 0
}

function reject() {
  emit('reject', getSelectItems())
}

function approval() {
  emit('approval', getSelectItems())
}

function getSelectItems() {
  return listData.value.filter(item => selectIds.value.includes(item.id))
}

function reset() {
  pagination.pageNo = 0
  pagination.pageSize = 30
  listData.value.length = 0
  loading.value = false
  canloadMore = true
  layout()
}

async function refreshHandler() {
  reset()
  const taskId = taskStore.getActiveId

  if (!taskId)
    return
  taskDetailInfo.value = await getTaskDetailInfo(taskId, '')

  nextTick(() => {
    useInfiniteScroll(
      el as any,
      () => {
        loadMore()
      },
      { distance: 10, canLoadMore: () => canloadMore },
    )
  })
}

watch(() => taskStore.activeId, async (newValue, oldValue) => {
  refreshHandler()
})
</script>

<template>
  <div>
    <n-modal
      v-model:show="show" :mask-closable="false" style="position: relative;" transform-origin="center"
      @after-enter="afterEnter" @after-leave="afterLeave"
    >
      <n-card
        :style="cardStyle" class="card" style="position: fixed;top:64px" :bordered="false" size="huge"
        role="dialog" aria-modal="true"
      >
        <div class="wrapper">
          <div class="wrapper-m32">
            <SvgIcon name="task-batch" size="16" />
            <span style="margin-left: 8px;">任务审批</span>
          </div>
          <div class="wrapper-title wrapper-m32">
            <span>任务ID:{{ taskStore.getActiveId }}</span>
            <SvgIcon size="22" class="forward" name="arrow-left" @click="backHandler" />
            <SvgIcon size="22" class="back" name="arrow-right" @click="forwardHandler" />
          </div>
          <div class="wrapper-statistic  wrapper-m32">
            <table style="width: 100%;">
              <thead>
                <tr>
                  <th scope="col">
                    创建人
                  </th>
                  <th scope="col">
                    状态
                  </th>
                  <th scope="col">
                    创建时间
                  </th>
                  <th scope="col">
                    图片来源
                  </th>
                  <th scope="col">
                    相似匹配
                  </th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>
                    {{ taskDetailInfo?.createusername }}
                  </td>
                  <td>{{ TASK_STATUS_OBJ[taskDetailInfo?.states] }}</td>
                  <td>{{ taskDetailInfo?.ocrPicture?.createTime }}</td>
                  <td>{{ taskDetailInfo?.fromsourceid }}</td>
                  <td>{{ totalCount }}</td>
                </tr>
              </tbody>
            </table>
          </div>

          <div class="wrapper-content">
            <div class="wrapper-content-form wrapper-m32">
              <div>
                <n-popselect v-model:value="timeRange" :options="timeOptions" trigger="click">
                  <div class="wrapper-content-form-dropdown">
                    <span>{{ timeLabel || '时间模式' }}</span>
                    <SvgIcon class="wrapper-content-form-dropdown-gap" name="arrow-botton" size="14" />
                  </div>
                </n-popselect>
                <n-popselect v-model:value="viewMode" :options="viewOptions" trigger="click">
                  <div class="wrapper-form-dropdown">
                    <span>{{ viewLabel || '视图模式' }}</span>
                    <SvgIcon class="wrapper-content-form-gap" name="arrow-botton" size="14" />
                  </div>
                </n-popselect>
              </div>
              <div>
                <div v-show="!showActions" class="wrapper-content-form-button" @click="setBatch(true)">
                  <SvgIcon style="margin-right: 6px;" size="22" name="batch" />
                  批量审批
                </div>
                <div v-show="showActions" class="batch">
                  <n-button text @click="setBatch(false)">
                    <template #icon>
                      <SvgIcon name="revoke" />
                    </template>
                    返回
                  </n-button>
                  <div style="cursor: pointer;margin-left: 16px;" @click="reject">
                    <SvgIcon width="64" height="28" name="a1" />
                  </div>
                  <SvgIcon size="24" name="vs" />
                  <div style="cursor: pointer;" @click="approval">
                    <SvgIcon width="64" height="28" name="a2" />
                  </div>
                </div>
              </div>
            </div>

            <div ref="el" class="scroll">
              <!-- <n-scrollbar :on-scroll="scrollHandler"> -->
              <div ref="masonryRef" class="grid">
                <div
                  v-for="(item, index) in listData" :key="index" :data-id="item.id" :style="{ height: gridHeight }"
                  class="grid-item"
                >
                  <div class="img-wrap">
                    <img
                      class="wrapper-content-item-img"
                      :class="{ 'wrapper-content-item-img-fit': viewMode !== 'masonry' }" :src="item.imgUrl"
                    >
                    <div class="small-mark" />
                    <div class="time">
                      <div v-if="item.photoDateTimestamp" class="time-item">
                        <SvgIcon class="svg-time" color="#FFF" size="14" name="camera-time" />
                        <span>{{ formatToDateHMS(Number(item.photoDateTimestamp) || 0) }}</span>
                      </div>
                      <div v-if="item.submitDateTimestamp" class="time-item time-item2">
                        <SvgIcon class="svg-time" color="#FFF" size="14" name="submit-time" />
                        <span>{{ formatToDateHMS(Number(item.submitDateTimestamp) || 0) }}</span>
                      </div>
                    </div>
                    <img v-if="item.historyStates === 2" class="tag-status" src="@/assets/images/task/tag-pass.png" alt="">
                    <img v-if="item.historyStates === 3" class="tag-status" src="@/assets/images/task/tag-not-pass.png" alt="">
                    <div class="check">
                      <n-checkbox
                        v-show="batch && item.historyStates === 1"
                        v-model:checked="item.checked" @click.prevent
                        @update:checked="onCheckChange($event, item)"
                      />
                    </div>
                    <div :class="{ 'percent-red': item.similarityScore === 100 }" class="percent">
                      {{ item.similarityScore }}<span class="percent-unit">%</span>
                    </div>
                  </div>
                </div>
              </div>
              <!-- </n-scrollbar> -->
            </div>
          </div>

          <div class="close" @pointerdown="closeModal">
            <div class="icon" />
          </div>
        </div>
      </n-card>
    </n-modal>
  </div>
</template>

<style lang="less" scoped>
::-webkit-scrollbar {
  display: none;
}
.card {
  width: 100vw;
  height: calc(100vh - 64px);
  user-select: none;
  /* Standard syntax */
}

.img-wrap{
  position: relative;
}

.small-mark{
  width: 100%;
  height: 36px;
  background: linear-gradient(180deg,rgba(0,0,0,0.01), rgba(0,0,0,0.44) 88%);
  border-radius: 0px 8px 8px 8px;
  position: absolute;
  left: 0;
  bottom: 0;
  z-index: 0;
}

.tag-status{
  width: 46px;
  height: 22px;
  position: absolute;
  left: -4px;
  top: 4px;
}

.time {
  position: absolute;
  z-index: 3;
  left: 3px;
  bottom: 3px;
  .time-item{
    display: flex;
    align-items: center;
    font-size: 14px;
    font-family: PingFang SC, PingFang SC-Medium;
    font-weight: 500;
    color: #ffffff;
    margin-bottom: 2px;
    line-height: 12px;
  }

  .time-item2{
    margin-bottom: 0;
  }

  .svg-time{
    margin-right: 5px
  }
}

.close {
  position: absolute;
  right: -90px;
  top: -70px;
  width: 18px;
  height: 18px;
  cursor: pointer;
}

.icon {
  background: #FFF;
  display: inline-block;
  width: 18px;
  height: 1px;
  transform: rotate(45deg);
  -webkit-transform: rotate(45deg);

  &:after {
    content: '';
    display: block;
    width: 18px;
    height: 1px;
    background: #FFF;
    transform: rotate(-90deg);
    -webkit-transform: rotate(-90deg);
  }
}

.wrapper {
  display: flex;
  flex-direction: column;
  position: relative;

  &-title {
    font-weight: bold;
    font-size: 21px;
    padding: 24px 0px 12px 0px;
    display: flex;
    align-items: center;

    .forward {
      cursor: pointer;
      margin-left: 16px;
    }

    .back {
      cursor: pointer;
      margin-left: 6px;
    }
  }

  &-statistic {
    background-color: #fafbfc;
    padding: 12px 20px;
    border-radius: 3px;
    margin-bottom: 10px;

    th {
      color: #d7d7d7;
      text-align: left;
    }

    td {
      text-align: center;
      font-weight: bold;
      text-align: left;
    }
  }

  &-m32 {
    margin-left: 32px;
  }

  &-content {
    &-form {
      display: flex;
      justify-content: space-between;
      align-items: center;
    background: #FFF;
    box-sizing: border-box;
    border-radius: 3px;
    height: 36px;

      &-dropdown {
        display: flex;
        flex-direction: row;
        align-items: center;
        margin-right: 24px;

        &-gap {
          margin-left: 5px;
        }
      }

      &-button {
        width: 118px;
        height: 36px;
        background: linear-gradient(135deg, #5b85f8, #3c6cf0);
        border-radius: 17px;
        box-shadow: 0px 2px 6px 0px rgba(116, 153, 253, 0.30);
        display: flex;
        align-items: center;
        justify-content: center;
        color: #FFF;
        margin-left: 18px;
        cursor: pointer;
      }

      div {
        display: flex;
        align-items: center;
      }
    }

    &-item {
      &-img {
        border-radius: 7px;
        display: block;
        height: 100%;
      }

      &-img-fit {
        width: 100%;
        object-fit: cover;
      }
    }

    .grid-item {
      width: 214px;
      padding: 16px;
      position: relative;

      .check{
        position: absolute;
        z-index: 3;
        left: 4px;
        top: 4px;
      }

      .percent {
        position: absolute;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 35px;
        height: 18px;
        opacity: 0.9;
        background: #6f92fd;
        border-radius: 6px 0px 6px 0px;
        z-index: 5;
        right: 4px;
        top: 4px;
        color: #fff;
        font-size: 14px;
      }

      .percent-unit{
        font-size: 8px;
        margin-top: 4px
      }

      .percent-red{
        background: #ff4e4f;
      }
    }

    .grid-item-selected {
      background-color: #dae3ff;
    }

    .scroll {
      overflow-y: scroll;
      height: calc(100vh - 420px);
    }
  }
}
</style>
