<template>
  <div class="radius-base">
    <div class="fill-blank radius-base p-t-base">
      <base-form :items="items" :model="model" :label-width="'80px'" size="small">
        <template #form-item-button>
          <el-button type="primary" @click="onStartCheck">开始检查</el-button>
        </template>
        <template #form-item-info>
          <span>待回收：</span>
          <span class="recovery-count">{{ recoveryCountRes?.count }}</span>
        </template>
      </base-form>
    </div>
    <div class="m-t-base flex">
      <div class="radius-base fill-blank p-base overflow-hidden flex-1">
        <div class="flex items-center m-b-base table-title">
          <span class="label">在评卷员手中</span>
          <span class="data-count">{{ unMarkPaperList?.result?.length }}</span>
          <el-button :disabled="!multipleSelection1.length" type="primary" size="small" @click="onTaskChangeMarker"
            >任务指定</el-button
          >
        </div>
        <!-- <base-table
          ref="table1"
          v-loading="loading1"
          border
          stripe
          size="small"
          :columns="columns1"
          :data="unMarkPaperList?.result"
          highlight-current-row
          @current-change="onCheckTask"
        ></base-table> -->
        <div v-loading="loading1" class="table-wrap">
          <!-- <base-table
            ref="table1"
            v-loading="loading1"
            border
            stripe
            size="small"
            :columns="columns1"
            :data="unMarkPaperList?.result"
            @selection-change="handleSelectionChange1"
          ></base-table> -->
          <el-table-v2
            :header-height="43"
            :row-height="43"
            :height="tableHeight"
            :width="tableWidth"
            :columns="columns1"
            :data="unMarkPaperList ? unMarkPaperList.result : []"
            fixed
          ></el-table-v2>
        </div>
      </div>
      <div class="radius-base fill-blank p-base overflow-hidden m-l-base flex-1">
        <div class="flex items-center m-b-base table-title">
          <span class="label">打回中的试卷</span>
          <span class="data-count">{{ unMarkBackPaperList?.result?.length }}</span>
          <el-button :disabled="!multipleSelection2.length" type="primary" size="small" @click="onTaskChangeMarker2"
            >任务指定</el-button
          >
        </div>
        <!-- <base-table
          ref="table2"
          v-loading="loading4"
          border
          stripe
          size="small"
          :columns="columns1"
          :data="unMarkBackPaperList?.result"
          highlight-current-row
          @current-change="onCheckTask2"
        ></base-table> -->
        <div v-loading="loading4" class="table-wrap">
          <!-- <base-table
            ref="table2"
            v-loading="loading4"
            border
            stripe
            size="small"
            :columns="columns1"
            :data="unMarkBackPaperList?.result"
            @selection-change="handleSelectionChange2"
          ></base-table> -->
          <el-table-v2
            :header-height="43"
            :row-height="43"
            :height="tableHeight"
            :width="tableWidth"
            :columns="columns11"
            :data="unMarkBackPaperList ? unMarkBackPaperList.result : []"
            fixed
          ></el-table-v2>
        </div>
      </div>
      <div class="radius-base fill-blank p-base overflow-hidden m-l-base flex-1">
        <div class="flex items-center m-b-base table-title">
          <span class="label">未处理问题卷</span>
          <span class="data-count">{{ unProcessProblemList?.length }}</span>
        </div>
        <div class="table-wrap">
          <base-table
            v-loading="loading2"
            border
            stripe
            size="small"
            :columns="columns2"
            :data="unProcessProblemList"
          ></base-table>
        </div>
      </div>
      <div class="radius-base fill-blank p-base overflow-hidden m-l-base flex-1">
        <div class="flex items-center m-b-base table-title">
          <span class="label">未处理雷同卷</span>
          <span class="data-count">{{ unProcessSimilarList?.length }}</span>
        </div>
        <div class="table-wrap">
          <base-table
            v-loading="loading3"
            border
            stripe
            size="small"
            :columns="columns3"
            :data="unProcessSimilarList"
          ></base-table>
        </div>
      </div>
    </div>
  </div>
  <base-dialog
    v-model="visibleChangeMarker"
    title="任务指定评卷员"
    destroy-on-close
    @close="changeMarkerModel.loginName = ''"
  >
    <base-form
      ref="formRef"
      size="small"
      :rules="rules"
      :model="changeMarkerModel"
      :items="changeMarkerItems"
    ></base-form>
    <template #footer>
      <confirm-button around @confirm="onSubmitChangeMarker" @cancel="visibleChangeMarker = false"></confirm-button>
    </template>
  </base-dialog>
  <base-dialog
    v-model="visibleChangeMarker2"
    title="任务指定评卷员"
    destroy-on-close
    @close="changeMarkerModel2.loginName = ''"
  >
    <base-form
      ref="formRef"
      size="small"
      :rules="rules"
      :model="changeMarkerModel2"
      :items="changeMarkerItems2"
    ></base-form>
    <template #footer>
      <confirm-button around @confirm="onSubmitChangeMarker2" @cancel="visibleChangeMarker2 = false"></confirm-button>
    </template>
  </base-dialog>
</template>

<script setup lang="tsx" name="EndCheck">
/** 收尾检查 */
import { reactive, ref, computed, watch, onMounted, onBeforeUnmount } from 'vue'
import { ElButton, ElMessage, ElTableV2, ElCheckbox } from 'element-plus'
import BaseForm from '@/components/element/BaseForm.vue'
import BaseTable from '@/components/element/BaseTable.vue'
import BaseDialog from '@/components/element/BaseDialog.vue'
import ConfirmButton from '@/components/common/ConfirmButton.vue'
import useFetch from '@/hooks/useFetch'
import useOptions from '@/hooks/useOptions'
import useVW from '@/hooks/useVW'
import useForm from '@/hooks/useForm'
import useMainLayoutStore from '@/store/layout'
import type { ExtractApiParams, ExtractMultipleApiResponse } from '@/api/api'
import type { EpFormItem, EpTableColumn, EpFormRules } from 'global-type'

const SelectionCell: any = (obj: any) => {
  const { value, intermediate = false, onChange } = obj
  return <ElCheckbox onChange={onChange} modelValue={value} indeterminate={intermediate} />
}
const mainLayout = useMainLayoutStore()
// const table1 = ref()
// const table2 = ref()
let tableWidth = ref(1)
let tableHeight = ref(window.innerHeight - 280)

function setTableWidth() {
  let winWidth = window.innerWidth > 1240 ? window.innerWidth : 1240
  let leftWidth = mainLayout.collapse ? 220 : 0
  tableWidth.value = parseInt((winWidth - leftWidth - 40) / 4 - 80 + '')
  tableHeight.value = window.innerHeight - 280
}
// let tableWidth = computed(() => {
//   let winWidth = window.innerWidth
//   let leftWidth = mainLayout.collapse ? 220 : 0
//   return parseInt((winWidth - leftWidth - 40) / 4 - 80 + '')
// })
setTableWidth()
watch(
  () => mainLayout.collapse,
  () => {
    setTimeout(setTableWidth, 400)
  }
)
function listenResize() {
  setTableWidth()
}
onMounted(() => {
  window.addEventListener('resize', listenResize)
})
onBeforeUnmount(() => {
  window.removeEventListener('resize', listenResize)
})
const multipleSelection1 = computed(() => {
  if (unMarkPaperList.value?.result && unMarkPaperList.value?.result.length) {
    return unMarkPaperList.value?.result.filter((item: any) => {
      return !!item.checked
    })
  } else {
    return []
  }
})
const multipleSelection2 = computed(() => {
  if (unMarkBackPaperList.value?.result && unMarkBackPaperList.value?.result.length) {
    return unMarkBackPaperList.value?.result.filter((item: any) => {
      return !!item.checked
    })
  } else {
    return []
  }
})
// const handleSelectionChange1 = (val: any[]) => {
//   multipleSelection1.value = val
// }
// const handleSelectionChange2 = (val: any[]) => {
//   multipleSelection2.value = val
// }

/** 指定评卷员 */
const visibleChangeMarker = ref<boolean>(false)
const visibleChangeMarker2 = ref<boolean>(false)

const changeMarkerModel = reactive({ loginName: '' })
const changeMarkerModel2 = reactive({ loginName: '' })

const { formRef, elFormRef } = useForm()

const changeMarkerItems: EpFormItem[] = [{ label: '请输入指定评卷员账号', prop: 'loginName', slotType: 'input' }]
const changeMarkerItems2: EpFormItem[] = [{ label: '请输入指定评卷员账号', prop: 'loginName', slotType: 'input' }]

const rules: EpFormRules = {
  loginName: [{ required: true, message: '请输入指定评卷员账号' }],
}

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

/** 搜索 */
const model = reactive<ExtractApiParams<'unProcessProblemList'>>({
  markingGroupNumber: dataModel.group,
  questionMainNumber: dataModel.question,
  subjectCode: dataModel.subject || '',
})

const { fetch: getUnMarkPaperList, result: unMarkPaperList, loading: loading1 } = useFetch('unMarkPaperList')
const {
  fetch: getUnMarkBackPaperList,
  result: unMarkBackPaperList,
  loading: loading4,
} = useFetch('unMarkBackPaperList')
const {
  fetch: getUnProcessProblemList,
  result: unProcessProblemList,
  loading: loading2,
} = useFetch('unProcessProblemList')
const {
  fetch: getUnProcessSimilarList,
  result: unProcessSimilarList,
  loading: loading3,
} = useFetch('unProcessSimilarList')

const { fetch: getRecoveryCount, result: recoveryCountRes, loading: loading5 } = useFetch('getRecoveryTaskCount')

watch(dataModel, () => {
  model.subjectCode = dataModel.subject || ''
  model.questionMainNumber = dataModel.question
  model.markingGroupNumber = dataModel.group
})

const { defineColumn, _ } = useForm()

const OneRow = defineColumn(_, 'row-1', { span: 5 })
const btnRow = defineColumn(_, 'row-1', { span: 2 })
const infoRow = defineColumn(_, 'row-1', { span: 3 })

const items = computed<EpFormItem[]>(() => [
  OneRow({
    label: '科目',
    prop: 'subjectCode',
    slotType: 'select',
    labelWidth: '46px',
    slot: { options: subjectList.value, onChange: changeModelValue('subject'), disabled: !isExpert.value },
  }),
  OneRow({
    label: '大题',
    prop: 'questionMainNumber',
    slotType: 'select',
    labelWidth: '60px',
    slot: {
      options: mainQuestionList.value,
      onChange: changeModelValue('question'),
      disabled: !isExpert.value && !isLeader.value,
    },
  }),
  OneRow({
    label: '小组',
    prop: 'markingGroupNumber',
    slotType: 'select',
    labelWidth: '60px',
    slot: {
      options: groupListWithAll.value,
      onChange: changeModelValue('group'),
    },
  }),
  btnRow({
    slotName: 'button',
    labelWidth: '20px',
  }),
  infoRow({
    slotName: 'info',
    labelWidth: '20px',
  }),
])

/** 未评卷 table */
const columns1 = computed(() => {
  const w = parseInt((tableWidth.value - 41) / 3 + '')

  return [
    {
      key: 'selection',
      width: 40,
      cellRenderer: (rowObj: any) => {
        const { rowData } = rowObj
        const onChange = (value: any) => (rowData.checked = value)
        return <SelectionCell value={rowData.checked} onChange={onChange} />
      },

      headerCellRenderer: () => {
        let data = unMarkPaperList.value ? unMarkPaperList.value.result : []
        // const _data = unref(data)
        const onChange = (value: any) =>
          (data = data.map((row: any) => {
            row.checked = value
            return row
          }))
        const allSelected = !data.length ? false : data.every((row: any) => row.checked)
        const containsChecked = !data.length ? false : data.some((row: any) => row.checked)

        return <SelectionCell value={allSelected} intermediate={containsChecked && !allSelected} onChange={onChange} />
      },
    },
    {
      title: '评卷员',
      key: 'markerName',
      dataKey: 'markerName',
      width: w,
      // formatter(row: any) {
      //   return `${row.loginName}-${row.markerName}`
      // },
    },
    { title: '密号', key: 'secretNumber', dataKey: 'secretNumber', width: w },
    { title: '大题', key: 'questionMainName', dataKey: 'questionMainName', width: w + 1 },
  ]
})
const columns11 = computed(() => {
  const w = parseInt((tableWidth.value - 41) / 3 + '')
  return [
    {
      key: 'selection',
      width: 40,
      cellRenderer: (rowObj: any) => {
        const { rowData } = rowObj
        const onChange = (value: any) => (rowData.checked = value)
        return <SelectionCell value={rowData.checked} onChange={onChange} />
      },

      headerCellRenderer: () => {
        let data = unMarkBackPaperList.value ? unMarkBackPaperList.value.result : []
        // const _data = unref(data)
        const onChange = (value: any) =>
          (data = data.map((row: any) => {
            row.checked = value
            return row
          }))
        const allSelected = !data.length ? false : data.every((row: any) => row.checked)
        const containsChecked = !data.length ? false : data.some((row: any) => row.checked)

        return <SelectionCell value={allSelected} intermediate={containsChecked && !allSelected} onChange={onChange} />
      },
    },
    {
      title: '评卷员',
      key: 'markerName',
      dataKey: 'markerName',
      width: w,
      cellRenderer: (rowObj: any) => {
        const { rowData } = rowObj
        return <span>{`${rowData.loginName}-${rowData.markerName}`}</span>
      },
      // formatter(row: any) {
      //   return `${row.loginName}-${row.markerName}`
      // },
    },
    { title: '密号', key: 'secretNumber', dataKey: 'secretNumber', width: w },
    { title: '大题', key: 'questionMainName', dataKey: 'questionMainName', width: w + 1 },
  ]
})
/** 未处理问题卷table */
const columns2: EpTableColumn[] = [
  { label: '密号', prop: 'secretNumber' },
  { label: '大题', prop: 'questionMainName' },
]
/** 未处理雷同卷table */
const columns3: EpTableColumn[] = [
  { label: '密号', prop: 'secretNumber' },
  { label: '雷同密号', prop: 'sameSecretNumber' },
  { label: '大题', prop: 'questionMainName' },
]

/** 开始检查 */
const onStartCheck = () => {
  // getUnMarkPaperList({ pageNumber: 1, pageSize: 20, ...model })
  getUnMarkPaperList({ pageNumber: 1, pageSize: 999999, ...model })
  // getUnMarkBackPaperList({ pageNumber: 1, pageSize: 20, ...model })
  getUnMarkBackPaperList({ pageNumber: 1, pageSize: 999999, ...model })
  getUnProcessProblemList(model)
  getUnProcessSimilarList(model)
  getRecoveryCount({ questionMainNumber: model.questionMainNumber, subjectCode: model.subjectCode })
}

const currentTask = ref<ExtractMultipleApiResponse<'unMarkPaperList'>>()
const currentTask2 = ref<ExtractMultipleApiResponse<'unMarkPaperList'>>()

const onCheckTask = (row: ExtractMultipleApiResponse<'unMarkPaperList'>) => {
  currentTask.value = row
}
const onCheckTask2 = (row: ExtractMultipleApiResponse<'unMarkPaperList'>) => {
  currentTask2.value = row
}

/** 任务指定评卷员 */
const onTaskChangeMarker = () => {
  visibleChangeMarker.value = true
}
const onTaskChangeMarker2 = () => {
  visibleChangeMarker2.value = true
}
const onSubmitChangeMarker = async () => {
  try {
    // if (!currentTask.value) {
    //   return ElMessage.error('点击表格行选择评卷任务')
    // }
    const valid = await elFormRef?.value?.validate()
    if (valid) {
      if (multipleSelection1.value?.find((item: any) => item.loginName == changeMarkerModel.loginName)) {
        return ElMessage.error('任务指定不可指定给原评卷人')
      }

      await useFetch('changeTaskMarker').fetch({
        // taskId: currentTask.value.taskId,
        taskIds: multipleSelection1.value.map((item: any) => item.taskId),
        loginName: changeMarkerModel.loginName,
      })
      visibleChangeMarker.value = false
      onStartCheck()
    }
  } catch (error) {
    console.error(error)
  }
}
const onSubmitChangeMarker2 = async () => {
  try {
    // if (!currentTask2.value) {
    //   return ElMessage.error('点击表格行选择评卷任务')
    // }
    const valid = await elFormRef?.value?.validate()
    if (valid) {
      if (multipleSelection2.value?.find((item: any) => item.loginName == changeMarkerModel2.loginName)) {
        return ElMessage.error('任务指定不可指定给原评卷人')
      }
      await useFetch('changeBackTaskMarker').fetch({
        // taskId: currentTask2.value.taskId,
        taskIds: multipleSelection2.value.map((item: any) => item.taskId),
        loginName: changeMarkerModel2.loginName,
      })
      visibleChangeMarker2.value = false
      onStartCheck()
    }
  } catch (error) {
    console.error(error)
  }
}

onOptionInit(onStartCheck)
</script>

<style scoped lang="scss">
.recovery-count {
  color: $color--primary;
  font-weight: bold;
  font-size: 16px;
}
.table-wrap {
  height: calc(100vh - 280px);
  overflow: auto;
}
.table-title {
  .label {
    font-size: $SmallFont;
    color: $RegularFontColor;
  }
  .data-count {
    padding: 4px 10px;
    margin: 0 12px;
    border: $OnePixelLine;
    border-radius: 4px;
    font-size: $MediumFont;
    color: $NormalColor;
  }
}
</style>
