<template>
  <div class="p-base full mark-inquiry-view">
    <div class="full radius-base fill-blank p-large scroll-auto">
      <base-form ref="formRef" :disabled="saving" :label-width="90" :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>
          <div class="flex items-center" style="width: 100%">
            <span style="color: #666; width: 60px; font-size: 12px">快捷方式</span>
            <!-- <base-select
              v-model="shortQueryConfigIndex"
              class="flex-1"
              clearable
              value-key="secretNumber"
              :options="customQueryConfigList?.map((v, i) => ({ label: v.name, value: i }))"
              @clear="fastParamClear"
              @change="fastParamChange"
            ></base-select> -->
            <el-select
              v-model="shortQueryConfigIndex"
              class="flex-1"
              clearable
              value-key="secretNumber"
              @clear="fastParamClear"
              @change="fastParamChange"
            >
              <el-option v-for="(v, i) in customQueryConfigList" :key="i" :label="v.name" :value="i">
                <div class="flex items-center justify-between">
                  <span>{{ v.name }}</span>
                  <el-popconfirm
                    width="220"
                    confirm-button-text="确定"
                    cancel-button-text="取消"
                    title="是否删除该快捷方式？"
                    @confirm="deleteFastQuery(v, i)"
                  >
                    <template #reference>
                      <el-button type="primary" style="height: 26px" size="small" @click.stop="() => {}"
                        >删除</el-button
                      >
                    </template>
                  </el-popconfirm>
                </div>
              </el-option>
            </el-select>
          </div>
        </template>
      </base-form>
    </div>
    <base-dialog v-model="visible" title="快捷查询命名">
      <el-input v-model="shortName"></el-input>
      <template #footer>
        <confirm-button
          :loading="saving"
          @confirm="onSetCustomQueryConfig"
          @cancel="toggleVisible(false)"
        ></confirm-button>
      </template>
    </base-dialog>
  </div>
</template>

<script setup lang="ts" name="MarkingInquiry">
/** 阅卷-自定义查询 */
import { computed, reactive, ref, watch, inject } from 'vue'
import { useRouter } from 'vue-router'
import { ElButton, ElInput, ElSelect, ElOption, ElPopconfirm, ElMessage } 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 refresh: any = inject('reload')
const { push } = useRouter()
const resetMarkerId = ref<any>(void 0)
const shortQueryConfigIndex = ref<number>()

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

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,
  markingGroupNumbers: dataModel.group,
  checked: false,
  arbitration: false,
  markerId: void 0,
  scoreEnd: void 0,
  scoreStart: void 0,
  time: [],
  secretNumber: '',
  // timeEnd: void 0,
  // timeStart: void 0,
  ratioStart: void 0,
  ratioEnd: void 0,
  objectiveScoreStart: void 0,
  objectiveScoreEnd: void 0,
})

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

const { fetch: getCustomQueryConfigList, result: customQueryConfigList } = useFetch('getCustomQueryConfigList')
const { fetch: setCustomQueryConfig, loading: saving } = useFetch('setCustomQueryConfig')
// const { fetch: getMarkerList, result: markerList } = useFetch('getMarkerList')
const { fetch: getMarkerList, result: allMarkerList } = useFetch('getMarkerList')
const markerList = computed(() => {
  let mgn = model.markingGroupNumbers
  if (typeof mgn == 'number') {
    mgn = [mgn]
  }
  if ((mgn || []).includes(undefined) || typeof mgn === 'undefined' || (Array.isArray(mgn) && !mgn.length)) {
    return allMarkerList?.value || []
  } else {
    return (allMarkerList?.value || []).filter((item) => {
      return (mgn || []).includes(item.markingGroupNumber)
    })
  }
})

watch(
  () => [model.subjectCode, model.mainNumber, model.markingGroupNumbers],
  () => {
    if (model.subjectCode && model.mainNumber) {
      getMarkerList({
        subjectCode: model.subjectCode,
        mainNumber: model.mainNumber,
        // markingGroupNumber: model.markingGroupNumber,
      }).then(() => {
        if (resetMarkerId.value) {
          model.markerId = resetMarkerId.value
          resetMarkerId.value = void 0
        } else {
          model.markerId = void 0
        }
      })
    }
  },
  {
    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 fastParamClear = () => {
  // elFormRef?.value?.resetFields()
  refresh()
}
const fastParamChange = async (index: number) => {
  if (typeof index === 'number') {
    let shortQueryConfig = customQueryConfigList?.value?.[index]?.params
    if (shortQueryConfig) {
      // Object.assign(model, omit(shortQueryConfig, 'timeStart', 'timeEnd'), {
      //   time: [shortQueryConfig.timeStart, shortQueryConfig.timeEnd],
      // })
      elFormRef?.value?.resetFields()
      if (shortQueryConfig.subjectCode) {
        await getMainQuestionList({ subjectCode: shortQueryConfig.subjectCode as string })
        if (shortQueryConfig.mainNumber) {
          await getQuestionGroupList({
            subjectCode: shortQueryConfig.subjectCode,
            mainNumber: shortQueryConfig.mainNumber,
          })
        }
      }
      setTimeout(() => {
        if (shortQueryConfig.markerId) {
          resetMarkerId.value = shortQueryConfig.markerId
        }
        if (!shortQueryConfig.hasOwnProperty('markingGroupNumbers')) {
          shortQueryConfig.markingGroupNumbers = undefined
        }
        console.log('shortQueryConfig:', shortQueryConfig)
        Object.assign(model, omit(shortQueryConfig, 'timeStart', 'timeEnd'), {
          time: [shortQueryConfig.timeStart, shortQueryConfig.timeEnd],
        })
      }, 30)
    }
  }
}

const Span7 = defineColumn(_, _, { span: 7 })
const Span6 = defineColumn(_, _, { span: 6 })
const Span8 = defineColumn(_, _, { span: 8 })
const OneRow = Span7(_, 'row-1')
const TwoRow = Span7(_, 'row-2')
const ThreeRow = Span7(_, 'row-3')
const FourRow = Span7(_, 'row-4')
const FiveRow = Span7(_, 'row-5')
const SixRow = Span7(_, 'row-6')
const ElevenRow = Span8(_, 'row-15')

const rules: EpFormRules = {
  subjectCode: [{ required: true, message: '请选择科目' }],
  mainNumber: [{ required: true, message: '请选择大题' }],
}
const customGroupChange = (v: any) => {
  if (groupListWithAll.value.find((item: any) => item.value == undefined)) {
    if (model.markingGroupNumbers.includes(undefined)) {
      model.markingGroupNumbers = [void 0]
      changeModelValue('group')(model.markingGroupNumbers)
    } else {
      changeModelValue('group')(v)
    }
  } else {
    changeModelValue('group')(v)
  }
}
const transGroupOptions = computed(() => {
  return (model.markingGroupNumbers || []).includes(undefined)
    ? (groupListWithAll.value || []).map((item: any) => {
        item.value != undefined && (item.disabled = true)
        return item
      })
    : groupListWithAll.value.map((item: any) => {
        item.disabled = false
        return item
      })
})

const items = computed<EpFormItem[]>(() => [
  OneRow({
    label: '科目',
    prop: 'subjectCode',
    slotType: 'select',
    slot: {
      placeholder: '科目',
      options: subjectList.value,
      onChange: changeModelValue('subject'),
      disabled: !isExpert.value,
    },
  }),
  OneRow({
    prop: 'mainNumber',
    label: '大题',
    slotType: 'select',
    slot: {
      placeholder: '大题',
      options: mainQuestionList.value,
      onChange: changeModelValue('question'),
      disabled: !isExpert.value && !isLeader.value,
    },
  }),
  TwoRow({
    prop: 'markingGroupNumbers',
    label: '小组',
    slotType: 'select',
    slot: {
      placeholder: '评卷小组',
      options: transGroupOptions.value,
      onChange: customGroupChange,
      multiple: true,
    },
  }),
  ThreeRow({
    label: '时间',
    slotType: 'dateTime',
    prop: 'time',
    slot: {
      startPlaceholder: '开始时间',
      endPlaceholder: '结束时间',
      clearable: true,
      type: 'datetimerange',
      valueFormat: 'YYYYMMDDHHmmss',
    },
  }),
  FourRow({
    label: '客主比',
    slotType: 'inputNumber',
    prop: 'ratioStart',
    slot: {
      step: 0.1,
      stepStrictly: true,
      min: 0,
      max: 999999,
      precision: 1,
    },
  }),
  FourRow({
    label: '至',
    labelWidth: '35px',
    slotType: 'inputNumber',
    prop: 'ratioEnd',
    slot: {
      step: 0.1,
      stepStrictly: true,
      min: 0,
      max: 999999,
      precision: 1,
    },
  }),
  FiveRow({
    label: '客观分',
    slotType: 'inputNumber',
    prop: 'objectiveScoreStart',
    slot: {
      step: 1,
      stepStrictly: true,
      min: 0,
      max: 999999,
    },
  }),
  FiveRow({
    label: '至',
    labelWidth: '35px',
    slotType: 'inputNumber',
    prop: 'objectiveScoreEnd',
    slot: {
      step: 1,
      stepStrictly: true,
      min: 0,
      max: 999999,
    },
  }),
  SixRow({
    label: '大题分',
    slotType: 'inputNumber',
    prop: 'scoreStart',
    slot: {
      step: 1,
      stepStrictly: true,
      min: 0,
      max: 999999,
    },
  }),
  SixRow({
    label: '至',
    labelWidth: '35px',
    slotType: 'inputNumber',
    prop: 'scoreEnd',
    slot: {
      step: 1,
      stepStrictly: true,
      min: 0,
      max: 999999,
    },
  }),
  Span7(
    {
      label: '评卷员',
      slotType: 'select',
      prop: 'markerId',
      slot: {
        // options: markerList?.value?.map((marker) => ({
        //   value: marker.id,
        //   label: marker.loginName ? `${marker.loginName}-${marker.name}` : marker.name,
        // })),
        options: [
          ...(markerList?.value || []).map((marker) => ({
            value: marker.id,
            label: marker.loginName ? `${marker.loginName}-${marker.name}` : marker.name,
          })),
        ],
        filterable: true,
        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
  shortName.value = ''
}
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
    shortName.value = ''
    getCustomQueryConfigList()
  } catch (error) {
    console.error(error)
  }
}
const deleteFastQuery = (v: any, i: number) => {
  console.log(i, shortQueryConfigIndex.value)
  useFetch('deleteCustomQuery')
    .fetch({ id: v.id })
    .then(() => {
      ElMessage.success('删除成功')
      if (i == shortQueryConfigIndex.value) {
        shortQueryConfigIndex.value = void 0
      }
      getCustomQueryConfigList()
    })
}
</script>

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