<template>
  <div class="flex direction-column full">
    <mark-header
      :exclude-operations="['remark', 'problem', 'example', 'bookmark']"
      :paper-path="currentExpertPaper?.filePath"
      :secret-number="currentExpertPaper?.secretNumber"
      @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">
      <splitpanes class="default-theme" style="height: 100%" @resize="setPaneSize">
        <pane
          max-size="80"
          :size="paneSize"
          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>
          <p v-if="currentExpertPaper" class="absolute mark-score">{{ currentExpertPaper.score }}</p>
          <!-- <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 }" />
          </div>
          <!-- <scoring-panel-with-confirm
          v-model:visible="editScoreVisible"
          v-model:score="modelScore"
          modal
          :toggle-modal="false"
          :auto-visible="false"
          :main-number="currentExpertPaper?.mainNumber"
          @submit="onSubmit"
        ></scoring-panel-with-confirm> -->
          <scoring-panel-with-confirm
            v-model:visible="editScoreVisible"
            v-model:score="modelScore"
            modal
            :auto-visible="false"
            :main-number="currentExpertPaper?.mainNumber"
            :subject-code="formModel.subjectCode"
            @submit="onSubmit"
          ></scoring-panel-with-confirm>
        </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" :label-width="'72px'">
            <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="">{{ paperType }}: 共</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' }"
              :memory-column="true"
              @current-change="onCurrentChange"
            ></base-table>
          </div>
        </pane>
      </splitpanes>
    </div>
  </div>
  <image-preview v-model="previewModalVisible" :url="currentExpertPaper?.filePath"></image-preview>
</template>

<script setup lang="ts" name="ExpertExpert">
/** 专家卷浏览-专家挑选卷 */
import { reactive, ref, computed, watch, nextTick } from 'vue'
import { ElButton, ElMessage } from 'element-plus'
import { PaperMap } from '@/constants/dicts'
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'
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
})
type RowType = ExtractMultipleApiResponse<'getExpertPickList'> & { index: number }
const ROLE_OPTION = ref<any[]>([])
useFetch('getAllRoleList')
  .fetch()
  .then((res: any) => {
    ROLE_OPTION.value = res.map((item: any) => {
      return {
        value: item.code,
        label: item.roleName,
      }
    })
    if (ROLE_OPTION.value.length) {
      formModel.role = ROLE_OPTION.value[0].value
    }
  })
/** 给分板 */
const editScoreVisible = ref<boolean>(true)

/** 图片预览 */
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 onDelete = async () => {
  try {
    if (currentExpertPaper.value) {
      await useFetch('deletePaper').fetch({ id: currentExpertPaper.value.id })
      await onSearch()
    } else {
      ElMessage.warning('未选择试卷')
    }
  } catch (error) {
    console.error(error)
  }
}

/** 预览试卷 */
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,
  delete: onDelete,
}

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

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

const formModel = reactive<ExtractApiParams<'getExpertPickList'>>({
  mainNumber: dataModel.question,
  forceGroupNumber: void 0,
  // role: 'CHIEF',
  role: '',
  paperType: 'RF',
  pageNumber: 1,
  pageSize: 9999999,
  subjectCode: dataModel.subject,
})

watch(
  () => formModel.paperType,
  () => {
    if (formModel.paperType !== 'FORCE') {
      formModel.forceGroupNumber = void 0
    }
  }
)

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

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[]>(() => {
  const items = [
    span10({
      rowKey: 'row-1',
      label: '科目',
      prop: 'subjectCode',
      slotType: 'select',
      labelWidth: '50px',
      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: '角色',
      prop: 'role',
      slotType: 'select',
      labelWidth: '50px',
      slot: { options: ROLE_OPTION.value },
    }),
    { rowKey: 'row-1', slotName: 'search', labelWidth: '10px', colProp: { span: 4 } },
    span10({
      rowKey: 'row-2',
      label: '试卷类型',
      prop: 'paperType',
      labelWidth: '70px',
      slotType: 'select',
      slot: {
        options: [
          { label: 'RF卷', value: 'RF' },
          { label: '强制考核卷', value: 'FORCE' },
          { label: 'SAMPLE_A', value: 'SAMPLE_A' },
          { label: 'SAMPLE_B', value: 'SAMPLE_B' },
        ],
      },
    }),
  ]

  if (formModel.paperType === 'FORCE') {
    items.push(
      span10({
        rowKey: 'row-2',
        label: '组号',
        prop: 'forceGroupNumber',
        slotType: 'select',
        slot: {
          options: forceCheckGroup.value?.map((d) => ({
            value: d.forceGroupNumber,
            label: `第${d.forceGroupNumber}组`,
          })),
        },
      })
    )
  }
  return items
})

/** 专家挑选卷 */

const columns: EpTableColumn<RowType>[] = [
  { label: '序号', type: 'index', width: 60 },
  { label: '密号', prop: 'secretNumber', minWidth: 110 },
  { label: '标准分', prop: 'score', minWidth: 60 },
  { label: '提交人', prop: 'createName', minWidth: 100 },
  { label: '角色', prop: 'roleName', minWidth: 70 },
  { label: '提交时间', prop: 'createTime', minWidth: 130 },
]

const { fetch: getExpertPickList, result: expertPaperList, loading } = useFetch('getExpertPickList')

const {
  tableRef,
  tableData,
  current: currentExpertPaper,
  next: checkNext,
  onCurrentChange,
  nextRow,
} = useTableCheck(expertPaperList)

const paperType = ref<string>('')

const onSearch = async () => {
  paperType.value = PaperMap[formModel.paperType]
  getExpertPickList(formModel)
}

/** 确定给分 */

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

const onSubmit = async () => {
  if (currentExpertPaper.value) {
    const scores = JSON.parse(JSON.stringify(modelScore.value))

    await updateMarkScore({ id: currentExpertPaper.value.id, scores: modelScore.value })
    currentExpertPaper.value.score = add(...scores)
    ElMessage.success('修改成功')
    // editScoreVisible.value = false
    // onSearch()
    nextRow()
  }
}

onOptionInit(onSearch)

const imgOption = computed<SetImgBgOption>(() => {
  return {
    image: currentExpertPaper?.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: 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>
