<template>
  <!-- <div class="remark-container" :class="{ 'hidden-width': !visible }"> -->
  <div class="remark-container">
    <div class="p-l-base" style="height: 100%">
      <div class="flex-1 remark-box radius-base flex direction-column p-base">
        <div class="p-b-base">
          <el-button v-if="task" type="primary" size="small" @click="back">返回正评</el-button>
          <el-button v-else type="primary" size="small" @click="close">关闭</el-button>
        </div>
        <div class="flex-1 scroll-auto p-t-base">
          <base-table
            v-if="viewType === 'list'"
            ref="historyTable"
            border
            stripe
            size="small"
            :columns="tableColumns"
            :data="markHistoryList"
            highlight-current-row
            :cell-style="{ padding: '6px 0' }"
            @current-change="onCurrentChange"
          ></base-table>
          <div v-else class="flex flex-wrap preview-list">
            <div
              v-for="markHistory in markHistoryList"
              :key="markHistory.taskId"
              class="m-l-mini preview-item"
              :class="{ current: task?.taskId === markHistory.taskId }"
              @click="onCurrentChange(markHistory)"
            >
              <img :src="markHistory.url" alt="" />
              <div class="text-center">{{ markHistory.markScore }}分</div>
            </div>
          </div>
        </div>
        <div class="flex items-center justify-around m-t-base" style="border-top: 1px solid #ddd">
          <el-radio-group v-model="viewType">
            <el-radio label="list">列表</el-radio>
            <el-radio label="preview">缩略图</el-radio>
          </el-radio-group>
        </div>
      </div>
    </div>
  </div>
</template>
<script name="RemarkBox" setup lang="ts">
import { reactive, ref, watch, nextTick, onMounted, onBeforeUnmount, computed } from 'vue'
import { ElRadioGroup, ElRadio, ElButton, ElMessage } from 'element-plus'
import ConfirmButton from '../../../components/common/ConfirmButton.vue'
import useFetch from '@/hooks/useFetch'
import useVModel from '@/hooks/useVModel'
import BaseTable from '@/components/element/BaseTable.vue'
import { throttle } from 'lodash-es'
import { preloadImg } from '@/utils/common'
import useMarkHeader from '@/hooks/useMarkHeader'
const props = defineProps<{ imgOption: any }>()

const { frontColor, setFrontColor } = useMarkHeader()
const imgOptionCom = computed(() => {
  return props.imgOption
})
console.log('props.imgOption:', props.imgOption)
const markHistoryList = ref<any>([])
const historyTable = ref()
const getMarkHistory = async () => {
  let res = await useFetch('getMarkHistory').fetch()
  markHistoryList.value = res.markHistoryList
  markHistoryList.value.forEach((task: any) => {
    preloadImg(task?.url)
  })
  nextTick(() => {
    if (!markHistoryList.value.length) {
      ElMessage.info('暂无回评数据')
    } else {
      historyTable.value?.tableRef?.setCurrentRow(markHistoryList.value[0])
    }
  })
}
const emits = defineEmits<{
  (e: 'task-change', data: any): void
  (e: 'update:modeValue', visible: boolean): void
  (e: 'back'): void
  (e: 'close'): void
}>()
const tableColumns: any = [
  { label: '密号', prop: 'secretNumber' },
  { label: '分数', prop: 'markScore' },
  { label: '时间', prop: 'markTime' },
  // { label: '试卷类型', prop: 'taskType' },
]
// const visible = useVModel(props)
const viewType = ref<'list' | 'preview'>('list')
watch(viewType, () => {
  nextTick(() => {
    console.log('historyTable', historyTable.value)
    if (task.value && viewType.value === 'list') {
      historyTable.value?.tableRef?.setCurrentRow(task.value)
    }
  })
})
// watch(visible, () => {
//   if (visible.value) {
//     getMarkHistory()
//   }
// })
const task = ref<any>()

const onConfirm = () => {
  if (task.value) {
    emits('task-change', task.value)
    // visible.value = false
  }
}
const onCurrentChange = (row: any) => {
  task.value = row
  onConfirm()
}
const back = () => {
  emits('back')
}
const close = () => {
  emits('close')
}
const getCurIndex = () => {
  return (markHistoryList.value || []).findIndex((item: any) => item.taskId == task.value?.taskId)
}
const nextRow = throttle(() => {
  if (!markHistoryList.value.length) {
    return
  }
  let curIndex = getCurIndex()
  if (curIndex == markHistoryList.value.length - 1) {
    ElMessage.warning('当前已是最后一条回评数据')
    return
  }
  const index = curIndex + 1
  const elTableRef = historyTable.value?.tableRef
  elTableRef?.setCurrentRow(markHistoryList.value[index])
  const tBodyDomWrap: any = elTableRef?.$refs.bodyWrapper
  if (tBodyDomWrap) {
    if (index == 0) {
      elTableRef?.scrollTo({ left: 0, top: 0, behavior: 'smooth' })
    } else {
      const wrap = tBodyDomWrap.getElementsByClassName('el-scrollbar__wrap')[0]
      const oHeight = wrap.offsetHeight
      const sTop = wrap.scrollTop
      const sHeight = wrap.scrollHeight
      const targetRowAsHeight = 36 * (curIndex + 1)
      if (sHeight > oHeight && targetRowAsHeight - sTop > oHeight) {
        const t = sHeight - targetRowAsHeight
        elTableRef?.scrollTo({ left: 0, top: sTop + 36, behavior: 'smooth' })
      }
    }
  }
}, 300)
const prevRow = throttle(() => {
  if (!markHistoryList.value.length) {
    return
  }
  let curIndex = getCurIndex()
  const elTableRef = historyTable.value?.tableRef
  if (curIndex > 0) {
    elTableRef?.setCurrentRow(markHistoryList.value[curIndex - 1])
    const tBodyDomWrap: any = elTableRef?.$refs.bodyWrapper
    if (tBodyDomWrap) {
      const wrap = tBodyDomWrap.getElementsByClassName('el-scrollbar__wrap')[0]
      const oHeight = wrap.offsetHeight
      const sTop = wrap.scrollTop
      const sHeight = wrap.scrollHeight
      const targetRowAsHeight = 36 * (curIndex || 0)
      if (targetRowAsHeight - 36 < sTop) {
        elTableRef?.scrollTo({ left: 0, top: targetRowAsHeight - 36, behavior: 'smooth' })
      }
    }
  }
}, 300)
const arrowDownToNextRow = (e: any) => {
  if ((e.target.className || '').includes('contenteditable-ele')) {
    return false
  }
  if (e.key === 'ArrowDown') {
    e.preventDefault()
    nextRow()
  } else if (e.key === 'ArrowUp') {
    e.preventDefault()
    prevRow()
  }
}
onMounted(() => {
  getMarkHistory()
  document.addEventListener('keydown', arrowDownToNextRow)
})
onBeforeUnmount(() => {
  document.removeEventListener('keydown', arrowDownToNextRow)
})

const updateRow = (score: any) => {
  !!task.value && (task.value.markScore = score)
}
const getNextRow = () => {
  if (!markHistoryList.value || !markHistoryList.value.length) {
    return false
  }
  let curIndex = (markHistoryList.value || []).findIndex((item: any) => item.taskId == task.value?.taskId)
  if (curIndex < markHistoryList.value?.length - 1) {
    let nextTask = markHistoryList.value[curIndex + 1]
    task.value = nextTask
    historyTable.value?.tableRef?.setCurrentRow(nextTask)
    return nextTask
  } else {
    ElMessage.warning('当前已是最后一条回评数据')
    return null
  }
}
defineExpose({ updateRow, getNextRow })
</script>
<style lang="scss" scoped>
.remark-container {
  width: 570px;
  height: 100%;
  transition: all 0.3s;
  overflow: hidden;
  &.hidden-width {
    width: 0;
  }
  .remark-box {
    height: 100%;
    background-color: #fff;
  }

  .preview-list {
    // overflow: auto;
    .preview-item {
      width: 32%;
      border: 1px solid;
      border-color: transparent;
      margin-bottom: 8px;
      text-align: center;
      border-radius: 6px;
      padding: 6px;
      &.current {
        // border-color: $color--primary;
        box-shadow: 0 0 4px $color--primary;
      }
      img {
        max-width: 100%;
        max-height: 100%;
        object-fit: contain;
      }
    }
  }
}
</style>
