import Pagination from '@/components/pagination'
import SaveForm from '@/components/save-form'
import { getLessonType, lessonType } from '@/views/knowledge-manage/knowledgeTypeData'
import {
  DataTableColumn,
  NButton,
  NCascader,
  NDataTable,
  NDrawer,
  NDrawerContent,
  NFormItem,
  NInput,
  NInputGroup,
  NInputNumber,
  NModal,
  NSelect,
  NSpace,
  NTab,
  NTabPane,
  NTabs,
  NTooltip,
  useDialog,
  useMessage
} from 'naive-ui'
import { defineComponent, onMounted, reactive, ref } from 'vue'
import { filterPointCategory } from '..'
import {
  examinationKnowledgePointCategoryDel,
  examinationKnowledgePointCategoryPage,
  examinationQuestionPage,
  examinationQuestionRemove
} from '../../api'
import styles from '../index.module.less'
import AddExamination from '../model/addExamination'
import AddQuestionBank from '../model/addQuestionBank'

//题目类型
export const questionTypeCode: { [_: string]: any } = {
  RADIO: '单选题',
  CHECKBOX: '多选题',
  PLAY: '演奏题',
  SORT: '排序题',
  LINK: '连连看'
}
//难度
export const difficultyCoefficients: any = [
  { label: '初级', value: 'ONE' },
  { label: '中级', value: 'TWO' },
  { label: '高级', value: 'THREE' }
]
export default defineComponent({
  name: 'question-bank',
  setup() {
    const saveForm = ref()
    const dialog = useDialog()
    const message = useMessage()
    const data = reactive({
      pagination: {
        page: 1,
        rows: 10,
        total: 0
      },
      loading: false,
      active: '',
      list: [] as any,
      categorys: [] as any
    })
    const searchForm = reactive({
      score: null, //分值
      maxScore: null,
      minScore: null,
      difficultyCoefficient: null, //难度
      questionTypeCode: null, //题目类型,可用值:RADIO,CHECKBOX,PLAY,SORT,LINK
      keyword: null, //	题目名称、编号
      categoryId: null, //	考点编号
      courseTypeCode: null //
    })
    const modelData = reactive({
      open: false,
      title: '添加考点',
      item: null as any
    })
    // 删除分类
    const handleDelete = (row: any) => {
      dialog.warning({
        title: '警告',
        content: '是否确认删除此题目?',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
          const res = await examinationQuestionRemove(row.id)
          if (res.data) {
            getList()
            message.success('删除成功')
          }
        }
      })
    }
    const columns = (): DataTableColumn[] => {
      return [
        {
          title: '题目名称',
          key: 'name',
          render(row: any) {
            return (
              <div>
                <div>{row.name}</div>
                <div>编号:{row.id}</div>
              </div>
            )
          }
        },
        {
          title: '题目类型',
          key: 'questionTypeCode',
          render(row: any) {
            return questionTypeCode[row.questionTypeCode]
          }
        },

        {
          title: '考点',
          key: 'examinationKnowledgePointCategoryName'
        },
        // {
        //   title: '课程类型',
        //   key: 'courseTypeCode',
        //   render(row: any) {
        //     return getLessonType(row.courseTypeCode) || '通用类型'
        //   }
        // },
        {
          title: '难度',
          key: 'difficultyCoefficient',
          render(row: any) {
            return (
              difficultyCoefficients.find(
                (n: any) => n.value?.toLocaleUpperCase() === row.difficultyCoefficient
              )?.label || row.difficultyCoefficient
            )
          }
        },
        {
          title: '分值',
          key: 'totalScore'
        },

        {
          title: '操作',
          key: 'operation',
          fixed: 'right',
          width: 180,
          render(row: any) {
            return (
              <NSpace>
                <NButton
                  type="primary"
                  text
                  v-auth="examinationQuestion/detail1750916550440779778"
                  onClick={() => {
                    modelData.item = {
                      ...row,
                      isLock: true
                    }
                    modelData.open = true
                  }}
                >
                  详情
                </NButton>
                <NButton
                  type="primary"
                  text
                  v-auth="examinationQuestion/update1750916452289871874"
                  onClick={() => {
                    modelData.title = '修改题目'
                    modelData.item = row
                    modelData.open = true
                  }}
                >
                  修改
                </NButton>
                <NButton
                  type="primary"
                  text
                  onClick={() => handleDelete(row)}
                  v-auth="examinationQuestion/remove1750916134479069186"
                >
                  删除
                </NButton>
              </NSpace>
            )
          }
        }
      ]
    }

    // 获取数据
    const getList = async () => {
      data.loading = true
      try {
        const { ...more } = searchForm
        const res: any = await examinationQuestionPage({
          page: data.pagination.page,
          rows: data.pagination.rows,
          ...more
        })
        if (Array.isArray(res?.data?.rows)) {
          data.list = res.data.rows
          data.pagination.total = res.data.total
        }
      } catch (error) {}
      data.loading = false
    }
    // 获取考点类型
    const getType = async () => {
      try {
        const res: any = await examinationKnowledgePointCategoryPage({
          page: 1,
          rows: 1000
        })
        if (Array.isArray(res?.data?.rows)) {
          data.categorys = filterPointCategory(res.data.rows, 'children')
        }
      } catch (error) {}
    }
    const onSubmit = () => {
      data.pagination.page = 1
      getList()
    }
    onMounted(() => {
      getType()
      getList()
    })
    return () => (
      <div class={styles.questionBank}>
        <SaveForm
          class={styles.form}
          ref={saveForm}
          label-width=""
          model={searchForm}
          onSubmit={onSubmit}
          onSetModel={(val: any) => Object.assign(searchForm, val)}
          saveKey="question-bank-key"
        >
          <NFormItem path="keyword" label="关键字">
            <NInput
              style={{ width: '180px' }}
              placeholder="请输入题目名称/编号"
              v-model:value={searchForm.keyword}
              onKeydown={(e) => {
                if (e.code === 'Enter') {
                  onSubmit()
                }
              }}
              clearable
            />
          </NFormItem>
          <NFormItem path="score" label="分值">
            {/* <NInput
              style={{ width: '180px' }}
              pair
              separator="-"
              // placeholder="从"
              allow-input={(value: string) => !value || /^\d+$/.test(value)}
              v-model:value={searchForm.score}
              onKeydown={(e) => {
                if (e.code === 'Enter') {
                  onSubmit()
                }
              }}
              clearable
            /> */}
            <NInputNumber
              v-model:value={searchForm.minScore}
              showButton={false}
              min={0}
              max={99999}
              placeholder="最小分值"
              onUpdate:value={() => {
                searchForm.maxScore = null
              }}
              style={{ width: '110px' }}
            />
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                lineHeight: '1',
                marginTop: '-2px',
                margin: '-2px 8px 0 8px'
              }}
            >
              -
            </div>
            <NInputNumber
              v-model:value={searchForm.maxScore}
              showButton={false}
              min={searchForm.minScore || 0}
              max={99999}
              placeholder="最大分值"
              style={{ width: '110px' }}
            />
          </NFormItem>
          <NFormItem path="questionTypeCode" label="题目类型">
            <NSelect
              placeholder="请选择题目类型"
              v-model:value={searchForm.questionTypeCode}
              options={Object.keys(questionTypeCode).map((key: string) => ({
                label: questionTypeCode[key],
                value: key
              }))}
              clearable
            />
          </NFormItem>
          {/* <NFormItem path="courseTypeCode" label='课程类型'>
            <NSelect
              placeholder="请选择课程类型"
              clearable
              v-model:value={searchForm.courseTypeCode}
              options={lessonType}
            />
          </NFormItem> */}
          <NFormItem path="categoryId" label="考点">
            <NCascader
              placeholder="请选择考点"
              v-model:value={searchForm.categoryId}
              checkStrategy="child"
              options={data.categorys}
              childrenField="children"
              expandTrigger="hover"
              valueField="categoryId"
              labelField="name"
              clearable
            />
          </NFormItem>
          <NFormItem path="difficultyCoefficient" label="难度">
            <NSelect
              placeholder="请选择难度"
              clearable
              v-model:value={searchForm.difficultyCoefficient}
              options={difficultyCoefficients}
            />
          </NFormItem>
          <NFormItem>
            <NSpace>
              <NButton type="primary" onClick={() => saveForm.value?.submit()}>
                搜索
              </NButton>
              <NButton type="default" onClick={() => saveForm.value?.reset()}>
                重置
              </NButton>
            </NSpace>
          </NFormItem>
        </SaveForm>
        <NSpace style={{ paddingBottom: '12px' }}>
          <NButton
            type="primary"
            v-auth="examinationQuestion/save1750916381125115905"
            onClick={() => {
              modelData.title = '创建题目'
              modelData.item = null
              modelData.open = true
            }}
          >
            创建题目
          </NButton>
        </NSpace>
        <NDataTable
          loading={data.loading}
          scrollX={900}
          columns={columns()}
          data={data.list}
          row-key={(row: any) => row.categoryId}
        ></NDataTable>

        <Pagination
          v-model:page={data.pagination.page}
          v-model:pageSize={data.pagination.rows}
          v-model:pageTotal={data.pagination.total}
          onList={getList}
          sync
          saveKey="question-bank-page-key"
        ></Pagination>

        <NDrawer v-model:show={modelData.open} width="80vw">
          <NDrawerContent title={modelData.title} closable>
            <AddQuestionBank
              item={modelData.item}
              categorys={data.categorys}
              onClose={() => {
                modelData.open = false
              }}
              onHandleSuccess={() => {
                modelData.open = false
                if (!modelData.item) {
                  data.pagination.page = 1
                }
                getList()
              }}
            />
          </NDrawerContent>
        </NDrawer>
      </div>
    )
  }
})
