<template>
  <div class="flex direction-column full">
    <mark-header
      :exclude-operations="['remark', 'problem', 'example', 'delete', 'bookmark']"
      :paper-path="currentAssessPaper?.filePath"
      @click="onOperationClick"
    >
      <el-button class="m-l-base m-r-auto" size="small" type="primary" @click="onEditScore">修改给分</el-button>
    </mark-header>
    <div class="flex flex-1 overflow-hidden p-base mark-container">
      <div
        class="flex flex-1 direction-column radius-base fill-blank mark-content"
        :class="{ 'text-center': center }"
        :style="{ 'background-color': backgroundColor }"
      >
        <span class="preview" @click="onPreview">
          <svg-icon name="preview"></svg-icon>
        </span>
        <right-button class="next-button" @click="checkNext" />
        <div class="flex-1 p-base scroll-auto mark-content-paper img-wrap relative">
          <img :src="dataUrl" alt="" class="paper-img" :style="{ 'background-color': frontColor }" />
          <p v-if="currentAssessPaper" class="absolute mark-score">{{ currentAssessPaper.score }}</p>
        </div>
        <!-- <scoring-panel-with-confirm
          v-model:visible="editScoreVisible"
          v-model:score="modelScore"
          :main-number="currentAssessPaper?.mainNumber"
          modal
          :toggle-modal="false"
          :auto-visible="false"
          @submit="onSubmit"
        ></scoring-panel-with-confirm> -->
        <scoring-panel-with-confirm
          v-model:visible="editScoreVisible"
          v-model:score="modelScore"
          :main-number="currentAssessPaper?.mainNumber"
          modal
          :auto-visible="false"
          @submit="onSubmit"
        ></scoring-panel-with-confirm>
      </div>
      <div class="flex direction-column p-base radius-base fill-blank m-l-base table-view">
        <base-form size="small" :model="formModel" :items="formItems" :label-width="'52px'">
          <template #form-item-search>
            <el-button :loading="loading" type="primary" @click="onSearch">查询</el-button>
          </template>
        </base-form>
        <div>
          <el-button custom-1 size="small" class="detail-info-label">
            <span class="">考核卷: 共</span>
            <span class="m-l-extra-small detail-info-label-num">{{ tableData?.length }}</span>
          </el-button>
        </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' }"
            @current-change="onCurrentChange"
          ></base-table>
        </div>
      </div>
    </div>
  </div>
  <image-preview v-model="previewModalVisible" :url="currentAssessPaper?.filePath"></image-preview>
</template>

<script setup lang="ts" name="ExpertAssess">
/** 专家卷浏览-强制考核卷 */
import { reactive, ref, computed, watch } from 'vue'
import { ElButton, ElMessage } from 'element-plus'
import { add } from '@/utils/common'
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 MarkHeader from '@/components/shared/MarkHeader.vue'
import BaseForm from '@/components/element/BaseForm.vue'
import BaseTable from '@/components/element/BaseTable.vue'
import RightButton from '@/components/shared/RightButton.vue'
import SvgIcon from '@/components/common/SvgIcon.vue'
import ScoringPanelWithConfirm from '@/components/shared/ScoringPanelWithConfirm.vue'
import ImagePreview from '@/components/shared/ImagePreview.vue'

import type { SetImgBgOption } from '@/hooks/useSetImgBg'
import type { ExtractMultipleApiResponse, ExtractApiParams, ExtractApiResponse } from '@/api/api'
import type { MarkHeaderInstance, EpFormItem, EpTableColumn } from 'global-type'

type RowType = ExtractMultipleApiResponse<'getExpertAssessList'> & { index: number }

/** 给分板 */
const editScoreVisible = ref<boolean>(false)

/** 图片预览 */
const previewModalVisible = ref<boolean>(false)

/** 分数 */
const modelScore = ref<number[]>([])

const {
  rotate,
  scale,
  center,
  frontColor,
  backgroundColor,
  onBack,
  onScaleChange,
  onCenter,
  onRotate,
  setBackgroundColor,
  setFrontColor,
  onViewStandard,
} = useMarkHeader()

/** 刷新 */
const onRefresh = () => {
  onSearch()
}

/** 预览试卷 */
const onPreview = () => {
  previewModalVisible.value = true
}

const onEditScore = () => {
  editScoreVisible.value = true
}

type OperationClick = MarkHeaderInstance['onClick']

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

const operationHandles: Partial<Record<OperationType, (...args: any) => void>> = {
  back: onBack,
  'scale-change': onScaleChange,
  center: onCenter,
  rotate: onRotate,
  'front-color': setFrontColor,
  'background-color': setBackgroundColor,
  refresh: onRefresh,
  standard: onViewStandard,
}

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

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

const formModel = reactive<ExtractApiParams<'getExpertAssessList'>>({
  mainNumber: dataModel.question,
  pageNumber: 1,
  pageSize: 9999999,
})

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

const { fetch: getForceCheckGroupList, result: forceCheckGroup } = useFetch('getForceCheckGroupList')

watch(
  dataModel,
  () => {
    if (dataModel.subject && dataModel.question) {
      getForceCheckGroupList({ subjectCode: dataModel.subject, mainNumber: dataModel.question })
    }
  },
  { immediate: true }
)

const { defineColumn, _ } = useForm()

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

const formItems = computed<EpFormItem[]>(() => [
  span10({
    rowKey: 'row-1',
    label: '大题',
    prop: 'mainNumber',
    slotType: 'select',
    labelWidth: '46px',
    slot: { options: mainQuestionList.value, onChange: changeModelValue('question'), disabled: true },
  }),
  span10({
    rowKey: 'row-1',
    label: '组号',
    prop: 'forceGroupNumber',
    slotType: 'select',
    slot: {
      options: forceCheckGroup.value?.map((d) => ({ value: d.forceGroupNumber, label: `第${d.forceGroupNumber}组` })),
    },
  }),
  { rowKey: 'row-1', slotName: 'search', labelWidth: '10px', colProp: { span: 4 } },
])

/** 强制考核卷 */

const columns: EpTableColumn<RowType>[] = [
  { label: '序号', type: 'index' },
  { label: '密号', prop: 'secretNumber', width: 100 },
  { label: '标准分', prop: 'score' },
  { label: '分组', prop: 'forceGroupNumber' },
  { label: '提交时间', prop: 'createTime', width: 160 },
]

const { fetch: getExpertAssessList, result: rfSampleList, loading } = useFetch('getExpertAssessList')

const {
  tableRef,
  tableData,
  current: currentAssessPaper,
  next: checkNext,
  onCurrentChange,
} = useTableCheck(rfSampleList)

const onSearch = async () => {
  getExpertAssessList(formModel)
}

/** 确定给分 */

const { fetch: updateMarkScore } = useFetch('updateMarkScore')

const onSubmit = async () => {
  if (currentAssessPaper.value) {
    await updateMarkScore({ id: currentAssessPaper.value.id, scores: modelScore.value })
    currentAssessPaper.value.score = add(...modelScore.value)
    ElMessage.success('修改成功')
  }
}

onOptionInit(onSearch)

const imgOption = computed<SetImgBgOption>(() => {
  return {
    image: currentAssessPaper?.value?.filePath,
    rotate: rotate.value,
    scale: scale.value,
  }
})

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

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