<template>
  <div class="p-base full mark-inquiry-view">
    <div class="full radius-base fill-blank p-large">
      <base-form ref="formRef" :disabled="saving" :label-width="useVW(88)" :rules="rules" :items="items" :model="model">
        <template #form-item-button-group>
          <el-button type="primary" @click="onSearch">抽查</el-button>
          <!-- <el-button type="primary">高级抽查</el-button> -->
          <el-button type="primary" @click="toggleVisible(true)">保存为快捷查询</el-button>
        </template>
        <template #form-item-short>
          <base-select
            v-model="shortQueryConfigIndex"
            clearable
            value-key="secretNumber"
            :options="customQueryConfigList?.map((v, i) => ({ label: v.name, value: i }))"
          ></base-select>
        </template>
      </base-form>
    </div>
    <base-dialog v-model="visible" title="快捷查询命名">
      <el-input v-model="shortName"></el-input>
      <template #footer>
        <confirm-button @confirm="onSetCustomQueryConfig" @cancel="toggleVisible(false)"></confirm-button>
      </template>
    </base-dialog>
  </div>
</template>

<script setup lang="ts" name="MarkingInquiry">
/** 阅卷-自定义查询 */
import { computed, reactive, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElButton, ElInput } from 'element-plus'
import { omit } from 'lodash-es'
import { filterEmpty } from '@/utils/common'
import BaseForm from '@/components/element/BaseForm.vue'
import BaseDialog from '@/components/element/BaseDialog.vue'
import BaseSelect from '@/components/element/BaseSelect.vue'
import ConfirmButton from '@/components/common/ConfirmButton.vue'
import useForm from '@/hooks/useForm'
import useFetch from '@/hooks/useFetch'
import useOptions from '@/hooks/useOptions'
import useVW from '@/hooks/useVW'

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

const { push } = useRouter()

const shortQueryConfigIndex = ref<number>()

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

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

type FormModel = Omit<ExtractApiParams<'setCustomQueryConfig'>['params'], 'timeStart' | 'timeEnd'> & { time: string[] }

const model = reactive<FormModel>({
  subjectCode: dataModel.subject,
  mainNumber: dataModel.question,
  markingGroupNumber: dataModel.group,
  checked: void 0,
  arbitration: false,
  markerId: void 0,
  scoreEnd: void 0,
  scoreStart: void 0,
  time: [],
  secretNumber: '',
  // timeEnd: void 0,
  // timeStart: void 0,
})

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

const { fetch: getCustomQueryConfigList, result: customQueryConfigList } = useFetch('getCustomQueryConfigList')
const { fetch: setCustomQueryConfig, loading: saving } = useFetch('setCustomQueryConfig')
const { fetch: getMarkerList, result: markerList } = useFetch('getMarkerList')

watch(
  () => [model.subjectCode, model.mainNumber, model.markingGroupNumber],
  () => {
    if (model.subjectCode && model.mainNumber) {
      getMarkerList({
        subjectCode: model.subjectCode,
        mainNumber: model.mainNumber,
        markingGroupNumber: model.markingGroupNumber,
      })
    }
  },
  {
    immediate: true,
  }
)

getCustomQueryConfigList()

const shortQueryConfig = computed<ExtractApiParams<'setCustomQueryConfig'>['params'] | void>(() => {
  if (shortQueryConfigIndex.value === undefined) {
    return void 0
  }
  return customQueryConfigList?.value?.[shortQueryConfigIndex.value]?.params
})

watch(shortQueryConfig, () => {
  if (!shortQueryConfig.value) {
    elFormRef?.value?.resetFields()
  } else {
    Object.assign(model, omit(shortQueryConfig.value, 'timeStart', 'timeEnd'), {
      time: [shortQueryConfig.value.timeStart, shortQueryConfig.value.timeEnd],
    })
  }
})

const Span7 = defineColumn(_, _, { span: 7 })
const Span6 = defineColumn(_, _, { span: 6 })
const OneRow = Span7(_, 'row-1')
const TwoRow = Span7(_, 'row-2')
const ThreeRow = Span7(_, 'row-3')
const FourRow = Span7(_, 'row-4')
const ElevenRow = Span6(_, 'row-11')

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

const items = computed<EpFormItem[]>(() => [
  OneRow({
    label: '科目',
    prop: 'subjectCode',
    slotType: 'select',
    slot: {
      placeholder: '科目',
      options: subjectList.value,
      onChange: changeModelValue('subject'),
      disabled: true,
    },
  }),
  OneRow({
    prop: 'mainNumber',
    label: '大题',
    slotType: 'select',
    slot: {
      placeholder: '大题',
      options: mainQuestionList.value,
      onChange: changeModelValue('question'),
      disabled: true,
    },
  }),
  TwoRow({
    prop: 'markingGroupNumber',
    label: '小组',
    slotType: 'select',
    slot: {
      placeholder: '评卷小组',
      options: groupListWithAll.value,
      onChange: changeModelValue('group'),
    },
  }),
  ThreeRow({
    label: '时间',
    slotType: 'dateTime',
    prop: 'time',
    slot: {
      startPlaceholder: '开始时间',
      endPlaceholder: '结束时间',
      clearable: true,
      type: 'datetimerange',
      valueFormat: 'YYYYMMDDHHmmss',
    },
  }),
  FourRow({
    label: '分数',
    slotType: 'inputNumber',
    prop: 'scoreStart',
  }),
  FourRow({
    label: '至',
    labelWidth: useVW(35),
    slotType: 'inputNumber',
    prop: 'scoreEnd',
  }),
  Span7(
    {
      label: '评卷员',
      slotType: 'select',
      prop: 'markerId',
      slot: {
        options: markerList?.value?.map((marker) => ({ value: marker.id, label: marker.name || marker.loginName })),
        clearable: true,
      },
    },
    undefined
  ),
  Span7({ label: '密号', slotType: 'input', prop: 'secretNumber' }, undefined),
  Span7(
    {
      label: '抽查情况',
      slotType: 'select',
      prop: 'checked',
      slot: {
        options: [
          { value: '', label: '全部' },
          { value: true, label: '已抽查' },
          { value: false, label: '未抽查' },
        ],
      },
    },
    undefined
  ),
  Span7(
    {
      label: '仲裁卷',
      slotType: 'select',
      prop: 'arbitration',
      slot: {
        options: [
          { value: false, label: '不含仲裁卷' },
          { value: true, label: '包含仲裁卷' },
        ],
      },
    },
    undefined
  ),
  ElevenRow({ slotName: 'button-group' }),
  ElevenRow({
    labelWidth: 20,
    slotName: 'short',
  }),
])

function getSearchParams(obj: Record<string, string | number | boolean>) {
  const query = filterEmpty(obj)
  let params: Record<string, string> = {}
  for (let k in query) {
    params[k] = `${query[k]}`
  }
  return params
}

/** 抽查 */
const onSearch = async () => {
  try {
    const valid = await elFormRef?.value?.validate()
    valid &&
      push({
        name: 'MarkingInquiryResult',
        query: getSearchParams({
          ...omit(model, 'time'),
          timeStart: model.time?.[0],
          timeEnd: model.time?.[1],
        }),
      })
  } catch (error) {
    console.error(error)
  }
}

const visible = ref<boolean>(false)
const shortName = ref<string>('')

/** 保存为快捷查询 */
const toggleVisible = (show: boolean) => {
  visible.value = show
}
const onSetCustomQueryConfig = async () => {
  try {
    await setCustomQueryConfig({
      name: shortName.value,
      params: {
        ...omit(model, 'time'),
        timeStart: model.time?.[0],
        timeEnd: model.time?.[1],
      },
    })
    toggleVisible(false)
    elFormRef?.value?.resetFields()
    shortQueryConfigIndex.value = void 0
    getCustomQueryConfigList()
  } catch (error) {
    console.error(error)
  }
}
</script>

<style scoped lang="scss">
.mark-inquiry-view {
}
</style>
