<script lang="ts" setup>
import { computed, nextTick, onMounted, onUnmounted, onUpdated, 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 { useWindowSizeFn } from '@/hooks/event/useWindowSizeFn'
import { getViewportOffset, off, on } from '@/utils/domUtils'

import { timeOptions, viewOptions } from '@/config/home'
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'
import bgLoading from '@/assets/images/bg-loading.png'

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

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

const bgLoadingImg = ref(bgLoading)
const totalCount = ref(0)
const timeRange = ref('all')
const taskId = ref('')
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 deviceHeight = ref(600)

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()
async function computeListHeight() {
  const headEl = document.querySelector('.wrapper-content')!
  const { bottomIncludeBody } = getViewportOffset(headEl)
  const height = bottomIncludeBody
  deviceHeight.value = height - 40 - 16 - 24
}

useWindowSizeFn(computeListHeight)

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

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

  _masonry = new Masonry(masonryRef.value as any, {
    itemSelector: '.grid-item',
    gutter: 17,
    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,
//   () => {
//     console.log(123456)
//     loadMore()
//   },
//   { distance: 10, canLoadMore: () => canloadMore },
// )

async function loadMore() {
  console.log('loadMore')
  if (loading.value || el.value == null)
    return

  if (!taskId.value)
    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,
        taskNode: taskDetailInfo.value.taskNode,
        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() {
  reload()
  removeListeners()
}

onMounted(() => {
  show.value && addListeners()
  window.addEventListener('keydown', handleKeydown)
})
onUnmounted(() => {
  window.removeEventListener('keydown', handleKeydown)
})
// 键盘左右箭头快捷切换
function handleKeydown(event) {
  // 在这里执行右箭头的逻辑
  if (event.keyCode === 67)
    show.value = false
  // batchModalRef.value.closeModal()
}
function showModal(value) {
  taskId.value = value
  refreshHandler()
  show.value = true
}

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

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 = []
    listData.value.forEach((item) => {
      item.checked = false
    })
  }
}

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()
}

function onChange() {
  reload()
}

async function refreshHandler() {
  reset()
  if (!taskId.value)
    return
  const taskPackage = taskStore.getApprovalList[taskStore.getCurrentIndex] || {}
  taskDetailInfo.value = await getTaskDetailInfo(taskId.value, taskPackage.packageid, taskPackage?.taskIndex || '')
  nextTick(() => {
    setTimeout(() => {
      useInfiniteScroll(
        el as any,
        () => {
          loadMore()
        },
        { distance: 10, canLoadMore: () => canloadMore },
      )
    }, 300)
  })
}

watch(() => taskStore.activeId, async (newValue, oldValue) => {
  taskId.value = taskStore.activeId
  selectIds.value = []
  refreshHandler()
})

const listStyle = computed(() => {
  return {
    height: `${deviceHeight.value}px`,
  }
})

function switchBatch() {
  setBatch(!batch.value)
}

function reload() {
  selectIds.value = []
  setBatch(false)
  refreshHandler()
}

function sortHandler(orderby: 'similarityScore' | 'createdate') {
  sortBy.orderName = orderby
  sortBy.orderType = sortBy.orderType === 'asc' ? 'desc' : 'asc'

  refreshHandler()
}

const gridHeight = computed(() => {
  let height = ''
  if (viewMode.value === 'masonry')
    height = ''
  else if (viewMode.value === 'horizontalVersion')
    height = '122px'
  else if (viewMode.value === 'verticalVersion')
    height = '300px'
  else if (viewMode.value === '3:4')
    height = '240px'

  return height
})

defineExpose({
  showModal,
  reload,
  closeModal,
})

onUpdated(() => {
  nextTick(() => {
    setTimeout(() => {
      layout()
    }, 50)
  })
})
</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;color: #666;">任务审批</span>
          </div>
          <div class="wrapper-title wrapper-m32">
            <span style="color: #333;">任务ID:{{ taskDetailInfo.fromtaskname }}</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>
                    <div
                      class="status-tag"
                      :class="{
                        'status-tag-red': taskDetailInfo?.userapprove?.statshis === 3,
                        'status-tag-green': taskDetailInfo?.userapprove?.statshis === 2,
                      }"
                    >
                      {{ TASK_STATUS_OBJ[taskDetailInfo?.userapprove?.statshis] }}
                    </div>
                  </td>
                  <td>{{ taskDetailInfo?.ocrPicture?.createTime }}</td>
                  <td>{{ taskDetailInfo?.pictureInfo?.source }}</td>
                  <td>{{ totalCount }}</td>
                </tr>
              </tbody>
            </table>
          </div>
          <div class="title wrapper-m32">
            相似图片
          </div>

          <div class="wrapper-content">
            <div class="wrapper-content-form wrapper-m32" style="margin-bottom: 16px;">
              <div>
                <!-- <n-popselect v-model:value="timeRange" :options="timeOptions" trigger="click" @change="onChange">
                  <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> -->
                <n-popselect v-model:value="viewMode" :options="viewOptions" trigger="click">
                  <div class="dropdown">
                    <!-- <span>{{ viewLabel || '请选择' }}</span> -->
                    <span>视图</span>
                    <SvgIcon class="gap" name="arrow-botton" size="14" />
                  </div>
                </n-popselect>
                <div style="margin-left: 15px;cursor: pointer;color:#323233" @click="sortHandler('createdate')">
                  <span>时间排序</span>
                  <SvgIcon style="margin-left: 8px;" name="sort" size="12" />
                </div>
                <div style="margin-left: 15px;cursor: pointer;color:#323233" @click="sortHandler('similarityScore')">
                  <span>相似度排序</span>
                  <SvgIcon style="margin-left: 8px;" name="sort" size="12" />
                </div>
              </div>
              <div>
                <div v-show="!showActions" class="wrapper-content-form-button" @click="switchBatch()">
                  <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>

            <n-spin :show="loading">
              <div ref="el" class="scroll" :style="listStyle">
                <!-- <n-scrollbar :on-scroll="scrollHandler"> -->
                <div ref="masonryRef" class="grid">
                  <div
                    v-for="(item, index) in listData"
                    :key="index"
                    :style="{ height: gridHeight }"
                    class="grid-item"
                  >
                    <n-image
                      class="img"

                      :class="{
                        'img-fit': viewMode === 'horizontalVersion',
                        'img-full': viewMode === '3:4' || viewMode === 'verticalVersion',
                      }"

                      :src="item.serverThumbnailUrl ? item.serverThumbnailUrl : item.imgUrl"
                      :fallback-src="bgLoadingImg"
                      :style="{ backgroundImage: `url(${loading ? bgLoadingImg : 'none'})` }"
                    />
                    <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>
                <!-- </n-scrollbar> -->
              </div>
            </n-spin>
          </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;
}

.title{
  font-size: 18px;
  font-family: PingFang SC, PingFang SC-Medium;
  font-weight: 500;
  text-align: left;
  color: #333333;
  margin-top: 14px;
  margin-bottom: 24px;
}

.small-mark{
  width: 100%;
  height: 56px;
  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;
  border-radius: 0 0 8px 8px;
}

.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
  }
}

.status-tag{
  display: inline-block;
  padding: 0 12px;
  height: 22px;
  background: #ffc671;
  border-radius: 12px;
  align-items: center;
  justify-content: center;
  font-size: 13px;
  font-family: PingFang SC, PingFang SC-Medium;
  font-weight: 500;
  text-align: left;
  color: #ffffff;
}

.status-tag-green{
  background: #53c21d;
}

.status-tag-red{
  background: #e45656;
}

.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: #999999;
      text-align: left;
    }

    td {
      text-align: center;
      font-weight: bold;
      text-align: left;
      font-size: 14px;
      font-family: PingFang SC, PingFang SC-Medium;
      font-weight: 500;
      text-align: left;
      color: #333333;
    }
  }

  &-m32 {
    // margin-left: 19px;
  }

  &-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;
      overflow: hidden;
    }

    .img {
      border-radius: 7px;
      display: block;
      // height: calc(100% - 25px);
      height: 100%;
      width: 100%;
    }

    .img-full {
      width: 100%;
      overflow: hidden;

      ::v-deep(img) {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .grid-item {
      width: 214px;
      // padding: 16px;
      // width: 182px;
      position: relative;
      margin-bottom: 32px;
      transition: 0.5s;

      .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);
    }
  }
}
::v-deep(.n-image img) {
  width: 100%!important;
}
</style>
