<template>
  <div class="flex direction-column">
    <div class="flex items-center fill-blank p-medium-base">
      <span class="subject-name">{{ subjectInfo?.name }}</span>
      <confirm-button
        class="m-l-auto"
        size="small"
        ok-text="新增"
        cancel-text="返回"
        @confirm="onAddMainQuestion"
        @cancel="back"
      ></confirm-button>
    </div>
    <div class="flex-1 p-base">
      <el-card shadow="never">
        <base-table size="small" :data="tableData" :columns="columns">
          <template #column-operation="{ row }">
            <el-button type="primary" link @click="onEditSubQuestion(row)">编辑</el-button>
            <el-popconfirm :width="useVW(220)" hide-icon :title="`确认删除题目?`" @confirm="onDelete(row)">
              <template #reference>
                <el-button type="primary" link>删除</el-button>
              </template>
            </el-popconfirm>
            <el-button v-if="row.firstMain" type="primary" link @click="onEditMainQuestion(row)">大题设置</el-button>
          </template>
        </base-table>
      </el-card>
    </div>
    <base-dialog v-model="visibleSubQuestionEditor" unless :footer="false" destroy-on-close>
      <base-form
        ref="formRef"
        :label-width="useVW(72)"
        :model="editSubInfo"
        :items="items"
        :rules="rules"
        :disabled="saving"
      >
        <template #form-item-mainQuestion> {{ [editSubInfo.mainNumber, editSubInfo.mainTitle].join('-') }} </template>
        <template #form-item-subQuestion> {{ editSubInfo.subNumber }} </template>
        <el-form-item class="m-t-base">
          <confirm-button :loading="saving" @confirm="onSubmit" @cancel="toggleVisible(false)"></confirm-button>
        </el-form-item>
      </base-form>
    </base-dialog>
  </div>
</template>

<script setup lang="ts" name="SubjectStructManage">
/** 科目试卷结构管理 */
import { reactive, ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElButton, ElCard, ElFormItem, ElPopconfirm, ElMessage } from 'element-plus'
import ConfirmButton from '@/components/common/ConfirmButton.vue'
import BaseTable from '@/components/element/BaseTable.vue'
import BaseForm from '@/components/element/BaseForm.vue'
import BaseDialog from '@/components/element/BaseDialog.vue'
import useFetch from '@/hooks/useFetch'
import useForm from '@/hooks/useForm'
import useVW from '@/hooks/useVW'

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

const { back, push } = useRouter()

const props = defineProps<{ id: number | string }>()

const { fetch: getSubjectInfo, result: subjectInfo } = useFetch('getSubjectInfo')
const { fetch: getSubQuestionList, result: subQuestionList } = useFetch('getSubQuestionList')

type SubQuestion = ExtractArrayValue<ExtractApiResponse<'getSubQuestionList'>>
type WithFirstMainTag = SubQuestion & { firstMain: boolean }
const tableData = computed<Array<WithFirstMainTag>>(() => {
  const MainMap: Record<number, boolean> = {}
  return subQuestionList.value?.map((sub) => {
    const mainHas = !!MainMap[sub.mainNumber]
    if (!mainHas) {
      MainMap[sub.mainNumber] = true
    }
    return { ...sub, firstMain: !mainHas }
  })
})

const columns: EpTableColumn[] = [
  { label: '大题号', prop: 'mainNumber' },
  { label: '大题名称', prop: 'mainTitle' },
  { label: '小题号', prop: 'subNumber' },
  { label: '小题满分', prop: 'totalScore' },
  { label: '间隔分', prop: 'intervalScore' },
  { label: '操作', slotName: 'operation' },
]

if (props.id) {
  getSubjectInfo({ id: +props.id }).then((info) => {
    getSubQuestionList({ subjectCode: info.code })
  })
}

/** 新增大题 */
function onAddMainQuestion() {
  if (subjectInfo.value.code) {
    push({ name: 'EditStruct', params: { subjectCode: subjectInfo.value.code } })
  }
}

/** 编辑大题 */
function onEditMainQuestion(row: ExtractArrayValue<ExtractApiResponse<'getSubQuestionList'>>) {
  if (subjectInfo.value.code) {
    push({ name: 'EditStruct', params: { subjectCode: subjectInfo.value.code, mainNumber: row.mainNumber } })
  }
}

const { fetch: editSubQuestion, loading: saving } = useFetch('editSubQuestion')

const editSubInfo = reactive<Partial<ExtractArrayValue<ExtractApiResponse<'getSubQuestionList'>>>>({})

const { formRef, elFormRef } = useForm()

const rules = computed<EpFormRules>(() => {
  return {
    intervalScore: [{ required: true, message: '请填写间隔分' }],
  }
})

const items = computed<EpFormItem[]>(() => {
  return [
    { label: '大题', slotName: 'mainQuestion' },
    { label: '小题号', slotName: 'subQuestion' },
    {
      label: '间隔分',
      prop: 'intervalScore',
      slotType: 'inputNumber',
      slot: { placeholder: '间隔分', stepStrictly: true, step: 1 },
    },
  ]
})

const visibleSubQuestionEditor = ref<boolean>(false)

function toggleVisible(visible: boolean) {
  visibleSubQuestionEditor.value = visible
}

/** 编辑小题 */
function onEditSubQuestion(row: ExtractArrayValue<ExtractApiResponse<'getSubQuestionList'>>) {
  Object.assign(editSubInfo, row)
  toggleVisible(true)
}

async function onSubmit() {
  try {
    const valid = await elFormRef?.value?.validate()
    valid && (await editSubQuestion({ id: editSubInfo.id, intervalScore: editSubInfo.intervalScore }))
    ElMessage.success(`保存成功`)
    subjectInfo?.value?.code && getSubQuestionList({ subjectCode: subjectInfo.value.code })
    toggleVisible(false)
  } catch (error) {
    console.error(error)
  }
}

/** 删除 */
const { fetch: deleteSubQuestion } = useFetch('deleteSubQuestion')
function onDelete(row: ExtractArrayValue<ExtractApiResponse<'getSubQuestionList'>>) {
  row.id &&
    deleteSubQuestion({ id: row.id }).then(() => {
      subjectInfo?.value?.code && getSubQuestionList({ subjectCode: subjectInfo.value.code })
    })
}
</script>

<style scoped lang="scss"></style>
