<template>
  <div class="p-base">
    <div class="m-b-base flex top-box">
      <div class="flex-1 p-base radius-base fill-blank m-r-base form-card">
        <base-form
          ref="formRef"
          :label-width="useVW(62)"
          :disabled="loading"
          :groups="groups"
          :rules="rules"
          :items="items"
          :model="model"
        ></base-form>
      </div>
      <div class="flex-1 radius-base fill-blank tree-card">
        <div class="flex items-center justify-between">
          <span>选择评卷员</span>
          <el-button size="small" type="primary" @click="onHandOutForceCheck">分发考核卷</el-button>
        </div>
        <div class="flex direction-column m-t-extra-base p-base radius-base fill-lighter tree-box">
          <el-input v-model="filterText" placeholder="输入评卷员账号或名称筛选" clearable></el-input>
          <div class="flex-1 m-t-base scroll-y-auto">
            <el-tree
              ref="treeRef"
              v-model="markerIds"
              show-checkbox
              :filter-node-method="filterTree"
              :data="markerTree"
              :props="treeProp"
            ></el-tree>
          </div>
        </div>
      </div>
    </div>
    <div class="flex direction-column radius-base fill-blank table-card">
      <div class="flex items-center justify-between">
        <span>分发进度</span>
        <el-button size="small" special @click="onSearch">查询</el-button>
      </div>
      <base-table class="flex-1" size="small" :columns="columns" :data="handOutProgressList">
        <template #empty>
          <empty :image-size="150"></empty>
        </template>
      </base-table>
    </div>
  </div>
</template>

<script setup lang="ts" name="MarkingAssess">
/** 强制考核分发 */
import { reactive, ref, computed, watch } from 'vue'
import { ElButton, ElInput, ElTree, ElMessage } from 'element-plus'
import BaseForm from '@/components/element/BaseForm.vue'
import BaseTable from '@/components/element/BaseTable.vue'
import Empty from '@/components/common/Empty.vue'
import useForm from '@/hooks/useForm'
import useFetch from '@/hooks/useFetch'
import useOptions from '@/hooks/useOptions'
import useVW from '@/hooks/useVW'

import type { ExtractApiParams, ExtractApiResponse } from '@/api/api'
import type { FormGroup, EpFormItem, EpFormRules, EpTableColumn } from 'global-type'

const markerIds = ref()

const model = reactive<ExtractApiParams<'handOutForceCheck'>>({
  subjectCode: '',
  mainNumber: void 0,
  markerIds: [],
  forceGroupNumber: void 0,
})

const { fetch: handOutForceCheck, loading } = useFetch('handOutForceCheck')
const { fetch: getForceCheckGroupList, result: forceCheckGroupList } = useFetch('getForceCheckGroupList')

const { fetch: getMarkerTree, result: markerTree } = useFetch('getMarkerTree')

watch(model, () => {
  if ((model.subjectCode, model.mainNumber)) {
    getForceCheckGroupList({ subjectCode: model.subjectCode, mainNumber: model.mainNumber })
  }
})

watch(forceCheckGroupList, () => {
  if (forceCheckGroupList?.value?.length && !model.forceGroupNumber) {
    model.forceGroupNumber = forceCheckGroupList.value[0].forceGroupNumber
  }
})

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

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

const { formRef, elFormRef, defineColumn, _ } = useForm()

const Span12 = defineColumn(_, '', { span: 12 })

const rules: EpFormRules = {
  subjectCode: [{ required: true, message: '请选择科目' }],
  mainNumber: [{ required: true, message: '请选择大题' }],
}

const groups: FormGroup[] = [
  {
    groupTitle: '选择大题',
    rowKeys: ['row-1', 'row-2'],
  },
  {
    groupTitle: '考核卷组',
    rowKeys: ['row-3'],
  },
]

const items = computed<EpFormItem[]>(() => {
  return [
    Span12({
      rowKey: 'row-1',
      label: '科目',
      prop: 'subjectCode',
      slotType: 'select',
      slot: {
        options: subjectList.value,
        onChange: changeModelValue('subject'),
      },
    }),
    Span12({
      rowKey: 'row-2',
      label: '大题',
      prop: 'mainNumber',
      slotType: 'select',
      slot: {
        options: mainQuestionList.value,
        onChange: changeModelValue('question'),
      },
    }),
    {
      rowKey: 'row-3',
      prop: 'forceGroupNumber',
      slotType: 'radio',
      slot: {
        options: forceCheckGroupList?.value?.map((v) => ({
          label: v.forceGroupNumber,
          slotLabel: `第${v.forceGroupNumber}组`,
        })),
      },
    },
  ]
})

onOptionInit(() => {
  getMarkerTree({ subjectCode: model.subjectCode, mainNumber: model.mainNumber, name: '' })
})

type MarkerItem = ExtractArrayValue<ExtractArrayValue<ExtractApiResponse<'getMarkerTree'>>['markers']>

function isMarker(x: any): x is MarkerItem {
  return !!x.loginName
}

const treeProp = {
  children: 'markers',
  label(treeNode: ExtractArrayValue<ExtractApiResponse<'getMarkerTree'>>) {
    if (isMarker(treeNode)) {
      return treeNode.name || treeNode.loginName
    }
    return `第${treeNode.markingGroupNumber}组`
  },
} as unknown as InstanceType<typeof ElTree>['props']

const filterText = ref<string>('')
const treeRef = ref<InstanceType<typeof ElTree>>()

const filterTree = ((value: string, data: MarkerItem) => {
  if (!value) return true
  return data.name?.includes(value) || data.loginName?.includes(value)
}) as unknown as InstanceType<typeof ElTree>['filterNodeMethod']

watch(filterText, () => {
  treeRef?.value?.filter(filterText.value)
})

const onHandOutForceCheck = async () => {
  try {
    if (!model.forceGroupNumber) {
      return ElMessage.error('请选择强制考核卷组')
    }
    const checked = treeRef?.value?.getCheckedNodes()
    model.markerIds = checked?.filter((v) => !!v.id).map<number>((v) => v.id) || []
    if (!model.markerIds?.length) {
      return ElMessage.error('请选择评卷员')
    }
    handOutForceCheck(model)
  } catch (error) {
    console.error(error)
  }
}

const columns: EpTableColumn<ExtractApiResponse<'getHandOutProgressList'>>[] = [
  { label: '科目', prop: 'subject' },
  { label: '大题名称', prop: 'mainQuestion' },
  { label: '强制卷组', prop: 'forceGroupNumber' },
  { label: '小组', prop: 'markingGroupNumber' },
  { label: '评卷员', prop: 'marker' },
  { label: '未评量', prop: 'pendingCount' },
  { label: '已评量', prop: 'finishCount' },
  { label: '总量', prop: 'totalCount' },
]

const { fetch: getHandOutProgressList, result: handOutProgressList } = useFetch('getHandOutProgressList')

const onSearch = async () => {
  try {
    const valid = await elFormRef?.value?.validate()
    valid && (await getHandOutProgressList(model))
  } catch (error) {
    console.error(error)
  }
}
</script>

<style scoped lang="scss">
.top-box {
  height: 395px;
  .tree-card {
    padding: 10px 20px 20px 20px;
    .tree-box {
      height: 320px;
    }
  }
}
.table-card {
  height: 365px;
  padding: 10px 20px 20px 20px;
}
.card-title {
  font-size: $MediumFont;
}
</style>
