<template>
  <div class="flex direction-column full">
    <mark-header
      :include-operations="['back']"
      :paper-path="currentSamePaper?.filePath"
      :secret-number="currentSamePaper?.secretNumber"
      @click="onOperationClick"
    >
      <el-button class="m-l-base" size="small" type="primary" @click="onConfirmSame(true)">确定雷同</el-button>
      <el-button class="m-l-base" size="small" type="primary" plain @click="onConfirmSame(false)">否定雷同</el-button>
      <el-button class="m-l-base m-r-auto" size="small" type="primary" custom-1 @click="onExport"> 导出 </el-button>
    </mark-header>
    <div class="flex flex-1 overflow-hidden p-base mark-container">
      <splitpanes class="default-theme" style="height: 100%" @resize="setPaneSize">
        <pane max-size="80" :size="paneSize" class="flex flex-1 direction-column mark-content">
          <!-- <right-button class="next-button" @click="checkNext" /> -->
          <div ref="imgWrap1" class="flex-1 p-base scroll-auto radius-base fill-blank mark-content-paper">
            <img :src="dataUrl" alt="" class="paper-img" :style="{ 'background-color': frontColor }" />
          </div>
          <div ref="imgWrap2" class="flex-1 p-base m-t-base scroll-auto radius-base fill-blank mark-content-paper">
            <img :src="dataUrlSame" alt="" class="paper-img" :style="{ 'background-color': frontColor }" />
          </div>
        </pane>
        <pane
          max-size="80"
          :size="100 - paneSize"
          class="flex direction-column p-base radius-base fill-blank table-view"
        >
          <base-form size="small" :model="formModel" :items="formItems">
            <template #form-item-search>
              <el-button :loading="loading" type="primary" @click="onSearch">查询</el-button>
            </template>
          </base-form>
          <div class="flex items-center justify-between detail-info-table-header">
            <el-button custom-1 size="small" class="detail-info-label">
              <span class="">雷同卷: 共</span>
              <span class="m-l-extra-small detail-info-label-num">{{ pagination.total }}</span>
            </el-button>
            <btn-pagination v-model="currentPage" :pagination="pagination"></btn-pagination>
          </div>
          <div class="flex-1 scroll-auto m-t-mini">
            <base-table
              ref="tableRef"
              border
              stripe
              size="small"
              height="100%"
              :data="tableData"
              :columns="columns"
              highlight-current-row
              :cell-style="{ padding: '6px 0' }"
              :memory-column="true"
              @current-change="onCurrentChange"
              @row-dblclick="onDbClick"
            ></base-table>
          </div>
        </pane>
      </splitpanes>
    </div>
  </div>
  <mark-history-list
    :id="currentViewHistory?.taskId"
    v-model="visibleHistory"
    :task="currentViewHistory"
  ></mark-history-list>
</template>

<script setup lang="ts" name="MarkingSimilar">
/** 雷同卷查看 */
import { reactive, computed, watch, ref } from 'vue'
import { ElButton, ElMessage } from 'element-plus'
import { useSetImgBg } from '@/hooks/useSetImgBg'
import useFetch from '@/hooks/useFetch'
import useVW from '@/hooks/useVW'
import useForm from '@/hooks/useForm'
import useOptions from '@/hooks/useOptions'
import useMarkHeader from '@/hooks/useMarkHeader'
import useTableCheck from '@/hooks/useTableCheck'
import BaseForm from '@/components/element/BaseForm.vue'
import BaseTable from '@/components/element/BaseTable.vue'
import MarkHistoryList from '@/components/shared/MarkHistoryList.vue'
import RightButton from '@/components/shared/RightButton.vue'
import MarkHeader from '@/components/shared/MarkHeader.vue'
import BtnPagination from '@/components/common/BtnPagination.vue'
import useTable from '@/hooks/useTable'

import type { SetImgBgOption } from '@/hooks/useSetImgBg'
import type { ExtractMultipleApiResponse, ExtractApiParams } from '@/api/api'
import type { MarkHeaderInstance, EpFormItem, EpTableColumn } from 'global-type'
import { Splitpanes, Pane } from 'splitpanes'
import { setPaneSize } from '@/utils/common'
import useMainStore from '@/store/main'
const mainStore = useMainStore()
const paneSize = computed(() => {
  return mainStore.paneSizeConfig[location.pathname] || 60
})

const imgWrap1 = ref()
const imgWrap2 = ref()
type RowType = ExtractMultipleApiResponse<'getSimilarPaperList'> & { index: number }

const { onBack, frontColor, setFrontColor } = useMarkHeader()

type OperationClick = MarkHeaderInstance['onClick']

type OperationType = Parameters<Exclude<OperationClick, undefined>>[0]['type']

const operationHandles: Partial<Record<OperationType, (...args: any) => void>> = {
  back: onBack,
}

const onOperationClick: OperationClick = ({ type, value }) => {
  operationHandles[type]?.(value)
}

const { subjectList, mainQuestionList, dataModel, changeModelValue, onOptionInit, isExpert, isLeader } = useOptions([
  'subject',
  'question',
])

const formModel = reactive<any>({
  mainNumber: dataModel.question,
  status: '',
  // pageNumber: 1,
  // pageSize: 9999999,
  subjectCode: dataModel.subject,
})

watch(dataModel, () => {
  formModel.mainNumber = dataModel.question
  formModel.subjectCode = dataModel.subject
})

const { defineColumn, _ } = useForm()

const span10 = defineColumn(_, '', { span: 10 })

const formItems = computed<EpFormItem[]>(() => [
  span10({
    rowKey: 'row-1',
    label: '科目',
    prop: 'subjectCode',
    slotType: 'select',
    labelWidth: '70px',
    slot: { options: subjectList.value, onChange: changeModelValue('subject'), disabled: !isExpert.value },
  }),
  span10({
    rowKey: 'row-1',
    label: '大题',
    prop: 'mainNumber',
    slotType: 'select',
    labelWidth: '70px',
    slot: {
      options: mainQuestionList.value,
      onChange: changeModelValue('question'),
      disabled: !isExpert.value && !isLeader.value,
    },
  }),
  span10({
    rowKey: 'row-2',
    label: '雷同判定',
    labelWidth: '70px',
    prop: 'status',
    slotType: 'select',
    slot: {
      options: [
        { label: '全部', value: '' },
        { label: '是', value: 'SAME' },
        { label: '否', value: 'NOT_SAME' },
      ],
    },
  }),
  { rowKey: 'row-1', slotName: 'search', labelWidth: '10px', colProp: { span: 4 } },
])

/** 雷同卷卷列表 */
const columns: EpTableColumn<RowType>[] = [
  { label: '密号', prop: 'secretNumber', minWidth: 110, fixed: 'left' },
  { label: '雷同密号', prop: 'sameSecretNumber', minWidth: 110 },
  { label: '评卷员', prop: 'markerName', minWidth: 100 },
  {
    label: '雷同判定',
    prop: 'status',
    minWidth: 100,
    formatter(row) {
      // return { INITIAL: '', SAME: '雷同', NOT_SAME: '不雷同' }[row.status]
      return { INITIAL: '', SAME: '是', NOT_SAME: '否' }[row.status]
    },
  },
]

// const { fetch: getSimilarPaperList, result: similarPaperList, loading } = useFetch('getSimilarPaperList')
const { pagination, currentPage, data, fetchTable, loading } = useTable('getSimilarPaperList', formModel, {
  pageSize: 100,
})

const {
  tableRef,
  tableData,
  current: currentSamePaper,
  currentView: currentViewHistory,
  next: checkNext,
  visibleHistory,
  onDbClick,
  onCurrentChange,
} = useTableCheck(data)
watch(currentSamePaper, () => {
  if (imgWrap1.value) {
    imgWrap1.value.scrollTop = 0
  }
  if (imgWrap2.value) {
    imgWrap2.value.scrollTop = 0
  }
})
const onSearch = async () => {
  formModel.status === '' && (formModel.status = null)
  // getSimilarPaperList(formModel)
  fetchTable()
}

/** 是否雷同 */
const { fetch: confirmIsSimilar } = useFetch('confirmIsSimilar')

const onConfirmSame = async (same: boolean) => {
  try {
    if (currentSamePaper.value) {
      await confirmIsSimilar({ id: currentSamePaper.value.id, same })
      ElMessage.success('操作成功')
      onSearch()
    }
  } catch (error) {
    console.error(error)
  }
}

/** 导出 */
const onExport = () => {
  useFetch('exportSimilarPaper').fetch(formModel)
}

onOptionInit(onSearch)

const imgOption = computed<SetImgBgOption>(() => {
  return {
    image: currentSamePaper?.value?.filePath,
  }
})
const sameImgOption = computed<SetImgBgOption>(() => {
  return {
    image: currentSamePaper?.value?.sameFilePath,
  }
})

const { drawing, dataUrl } = useSetImgBg(imgOption, frontColor, setFrontColor)
const { drawing: drawingSame, dataUrl: dataUrlSame } = useSetImgBg(sameImgOption, frontColor, setFrontColor)
</script>

<style scoped lang="scss">
.mark-container {
  .mark-content {
    position: relative;
    .preview {
      position: absolute;
      cursor: pointer;
      top: 20px;
      right: 25px;
      font-size: 38px;
    }
    .next-button {
      position: absolute;
      right: -20px;
      top: 300px;
    }
    .mark-content-paper {
      img {
        max-width: 100%;
      }
    }
  }
  .table-view {
    // width: 580px;
    .detail-info-label {
      .detail-info-label-num {
        min-width: 32px;
        height: 24px;
        line-height: 24px;
        background: #00987b;
        border-radius: 4px;
      }
    }
  }
}
</style>
