<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 scroll-auto left-form">
        <base-form
          ref="formRef"
          :label-width="'72px'"
          :disabled="loading"
          :groups="groups"
          :rules="rules"
          :items="items"
          :model="model"
        >
          <template #form-item-paperTable>
            <base-table
              ref="tableRef"
              v-loading="paperLoading"
              border
              stripe
              size="small"
              :data="paperTableData"
              :columns="[
                { label: '密号', prop: 'secretNumber' },
                { label: '分数', prop: 'score' },
              ]"
              max-height="176"
            ></base-table>
          </template>
        </base-form>
      </div>
      <div class="flex-1 radius-base fill-blank tree-card">
        <div class="flex items-center justify-between">
          <span>选择评卷员</span>
          <el-button
            :disabled="!model.forceGroupNumber"
            :loading="loading"
            size="small"
            type="primary"
            @click="sendHandler"
            >分发考核卷</el-button
          >
        </div>
        <!-- <div class="flex direction-column m-t-extra-base p-base radius-base fill-lighter tree-box"> -->
        <div class="flex direction-column 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
              node-key="id"
              :default-checked-keys="defaultCheckedKeys"
              default-expand-all
              :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 :loading="tableLoading" size="small" special @click="onSearch">查询</el-button>
      </div>
      <base-table border stripe class="flex-1 m-t-mini" size="small" :columns="columns" :data="handOutProgressList">
        <template #empty>
          <empty :image-size="150"></empty>
        </template>
      </base-table>
    </div>

    <base-dialog v-model="forceCheckVisible" :title="dialogTitle" destroy-on-close :width="550">
      <div class="dialog-body-wrap">
        <div class="q-title flex items-center">
          <img src="../../../assets/images/main_question.png" />
          <span>{{ questionName }}</span>
        </div>
        <div class="choose-list-box">
          <div class="row">
            <span class="label"> 强制考核卷组： </span>
            <div class="value">{{ `${model.forceGroupNumber} （试卷共${paperCount}份）` }}</div>
          </div>
          <div class="row">
            <span class="label"> 分发给： </span>
            <div class="value">
              <!-- {{ previewChecked }} -->
              <div v-for="(item, index) in previewChecked" :key="index">
                第{{ item.markingGroupNumber }}组（{{ item.names.join('；') }}）
              </div>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="flex justify-center">
          <confirm-button
            :loading="loading"
            @confirm="onHandOutForceCheck"
            @cancel="forceCheckVisible = false"
          ></confirm-button>
        </div>
      </template>
    </base-dialog>
  </div>
</template>

<script setup lang="ts" name="MarkingAssess">
/** 强制考核分发 */
import { reactive, ref, computed, watch } from 'vue'
import { ElButton, ElInput, ElTree, ElMessage, ElTable } 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 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 ConfirmButton from '@/components/common/ConfirmButton.vue'
import type { ExtractApiParams, ExtractApiResponse } from '@/api/api'
import type { FormGroup, EpFormItem, EpFormRules, EpTableColumn } from 'global-type'
import { useRoute } from 'vue-router'
import { TreeKey } from 'element-plus/es/components/tree/src/tree.type'
const route = useRoute()
const forceCheckVisible = ref(false)
const { subjectList, mainQuestionList, dataModel, onOptionInit, changeModelValue, isExpert, isLeader } = useOptions([
  'subject',
  'question',
])

const markerIds = ref()
let defaultCheckedKeys = ref<TreeKey[]>([])
const queryMId: any = route.query.markerId

if (queryMId) {
  defaultCheckedKeys.value = [queryMId]
}
const model = reactive<ExtractApiParams<'handOutForceCheck'>>({
  subjectCode: dataModel.subject || '',
  mainNumber: dataModel.question,
  markerIds: [],
  forceGroupNumber: void 0,
})

const { fetch: handOutForceCheck, loading } = useFetch('handOutForceCheck')
const { fetch: getForceCheckGroupList, result: forceCheckGroupList } = useFetch('getForceCheckGroupList')
const { fetch: getExpertAssessList, result: rfSampleList, loading: paperLoading } = useFetch('getExpertAssessList')
const { fetch: getMarkerTree, result: markerTree } = useFetch('getMarkerTree')
const paperCount = computed(() => {
  return (forceCheckGroupList.value || []).find((item) => {
    return item.forceGroupNumber == model.forceGroupNumber
  })?.paperCount
})
const paperTableData = computed<any>(() => {
  return rfSampleList.value?.result || []
})
watch(
  model,
  () => {
    if ((model.subjectCode, model.mainNumber)) {
      getForceCheckGroupList({ subjectCode: model.subjectCode, mainNumber: model.mainNumber })
      getMarkerTree({ subjectCode: model.subjectCode, mainNumber: model.mainNumber, name: '' })
      if (model.forceGroupNumber) {
        getExpertAssessList({
          subjectCode: model.subjectCode,
          mainNumber: model.mainNumber,
          pageNumber: 1,
          pageSize: 9999999,
          forceGroupNumber: model.forceGroupNumber,
        })
      }
    }
  },
  { immediate: true }
)

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

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

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

const Span12 = defineColumn(_, '', { span: 12 })
const Span6 = defineColumn(_, '', { span: 6 })
const Span18 = defineColumn(_, '', { span: 18 })
const Span24 = defineColumn(_, '', { span: 24 })

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[]>(() => {
  let rowStart = 3
  let domArr = []
  let arr = forceCheckGroupList?.value || []
  for (let i = 0; i < arr.length; i++) {
    if (i % 5 == 0) {
      domArr.push(
        Span24({
          rowKey: 'row-' + rowStart,
          prop: 'forceGroupNumber',
          slotType: 'radio',
          slot: {
            options: arr.slice(i, i + 5).map((v) => ({
              label: v.forceGroupNumber,
              slotLabel: `第${v.forceGroupNumber}组`,
            })),
          },
        })
      )
      rowStart++
    }
    if (model.forceGroupNumber == arr[i].forceGroupNumber) {
      domArr.push(
        Span18({
          rowKey: 'row-' + rowStart,
          slotName: 'paperTable',
        })
      )
      rowStart++
    }
  }
  return [
    Span12({
      rowKey: 'row-1',
      label: '科目',
      prop: 'subjectCode',
      slotType: 'select',
      slot: {
        options: subjectList.value,
        onChange: changeModelValue('subject'),
        disabled: !isExpert.value,
      },
    }),
    Span12({
      rowKey: 'row-1',
      label: '大题',
      prop: 'mainNumber',
      slotType: 'select',
      slot: {
        options: mainQuestionList.value,
        onChange: changeModelValue('question'),
        disabled: !isExpert.value && !isLeader.value,
      },
    }),
    // Span24({
    //   rowKey: 'row-3',
    //   prop: 'forceGroupNumber',
    //   slotType: 'radio',
    //   slot: {
    //     options: forceCheckGroupList?.value?.map((v) => ({
    //       label: v.forceGroupNumber,
    //       slotLabel: `第${v.forceGroupNumber}组`,
    //     })),
    //   },
    // }),
    ...domArr,
    // Span18({
    //   rowKey: 'row-3',
    //   slotName: 'paperTable',
    // }),
  ]
})

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('请选择评卷员')
    }
    await handOutForceCheck(model)
    forceCheckVisible.value = false
    treeRef?.value?.setCheckedKeys([])
    ElMessage.success('操作成功')
  } 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,
  loading: tableLoading,
} = useFetch('getHandOutProgressList')

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

onOptionInit((data) => {
  getMarkerTree({ subjectCode: data?.subject || '', mainNumber: data?.question, name: '' })
})

const dialogTitle = computed(() => {
  let target = (subjectList.value || []).find((item: any) => {
    return item.code == model.subjectCode
  })
  return `${target?.code} - ${target?.name}`
})
const questionName = computed(() => {
  let target = (mainQuestionList.value || []).find((item: any) => {
    return item.mainNumber == model.mainNumber
  })
  return `${target?.label}`
})
const previewChecked = ref<any[]>([])
const sendHandler = () => {
  const checked: any = treeRef?.value?.getCheckedNodes()
  if (!checked.length) {
    ElMessage.error('请选择评卷员')
    return
  }
  let map: any = {}
  let arr = checked.filter((person: any) => !!person.name)
  for (let i = 0; i < arr.length; i++) {
    if (!map[arr[i].markingGroupNumber + '']) {
      map[arr[i].markingGroupNumber + ''] = [arr[i].name]
    } else {
      map[arr[i].markingGroupNumber + ''].push(arr[i].name)
    }
  }
  previewChecked.value = []
  for (let k in map) {
    previewChecked.value.push({ markingGroupNumber: k, names: map[k] })
  }
  // previewChecked.value = checked
  //   .filter((person: any) => !!person.name)
  //   .map((person: any) => {
  //     return `第${person.markingGroupNumber}组:${person.name}`
  //   })
  //   .join(';   ')
  console.log('checked:', checked)
  forceCheckVisible.value = true
}
</script>

<style scoped lang="scss">
.left-form {
  :deep(.custom-block:not(:first-child)) {
    .default-custom-block-title {
      margin-bottom: 0;
    }
    .el-form-item {
      margin-bottom: 5px;
    }
  }
}
.dialog-body-wrap {
  .choose-list-box {
    background-color: #f5f5f5;
    border-radius: 6px;
    padding: 20px;
    max-height: 400px;
    overflow: auto;
    .row {
      display: flex;
      line-height: 28px;
      .label {
        width: 90px;
        text-align: right;
      }
      .value {
        flex: 1;
      }
    }
  }
  .q-title {
    margin-bottom: 15px;
    img {
      height: 20px;
      margin-right: 10px;
    }
    span {
      color: #444;
      font-size: 14px;
    }
  }
}
.top-box {
  // height: 395px;
  height: 420px;
  .form-card {
    padding: 16px 20px 20px 20px;
  }
  .tree-card {
    padding: 10px 20px 20px 20px;
    .tree-box {
      // height: 320px;
      height: 345px;
      margin-top: 10px;
    }
  }
}
.table-card {
  height: 365px;
  padding: 10px 20px 20px 20px;
}
.card-title {
  font-size: $MediumFont;
}
</style>
