import Pagination from '@/components/pagination'
import SaveForm from '@/components/save-form'
import { lessonType } from '@/views/knowledge-manage/knowledgeTypeData'
import {
  DataTableColumn,
  NButton,
  NCascader,
  NDataTable,
  NFormItem,
  NInput,
  NSelect,
  NSpace
} from 'naive-ui'
import { computed, defineComponent, onMounted, reactive, ref } from 'vue'
import {
  examinationKnowledgePointCategoryPage,
  examinationQuestionPage,
  examinationQuestionPageAndAnswer
} from '../../api'
import styles from '../index.module.less'
import { difficultyCoefficients, questionTypeCode } from '../question-bank'

export default defineComponent({
  name: 'add-question-list',
  emits: ['select'],
  props: {
    selectList: {
      type: Array,
      default: () => []
    }
  },
  setup(props, { emit }) {
    const saveForm = ref()
    const checkList = computed(() => {
      const list = props.selectList?.map((n: any) => n.id) || []
      return list
    })
    const data = reactive({
      pagination: {
        page: 1,
        rows: 10,
        total: 0
      },
      loading: false,
      list: [] as any,
      categorys: [] as any,
      selectList: [] as any
    })
    const searchForm = reactive({
      score: null, //分值
      difficultyCoefficient: null, //难度
      questionTypeCode: null, //题目类型,可用值:RADIO,CHECKBOX,PLAY,SORT,LINK
      keyword: null, //	题目名称、编号
      categoryId: null, //	考点编号
      courseTypeCode: null //
    })
    const columns = (): DataTableColumn[] => {
      return [
        {
          type: 'selection',
          disabled: (row: any) => {
            return checkList.value.includes(row.id)
          }
        },
        {
          title: '题目名称',
          key: 'name',
          width: 230,
          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: 'difficultyCoefficient',
          render(row: any) {
            const rowName =
              difficultyCoefficients.find(
                (n: any) => n.value?.toLocaleUpperCase() === row.difficultyCoefficient
              )?.label || row.difficultyCoefficient
            row.difficultyCoefficientName = rowName
            return rowName
          }
        },
        {
          title: '分值',
          key: 'totalScore'
        }
      ]
    }

    // 获取数据
    const getList = async () => {
      data.loading = true
      try {
        const res: any = await examinationQuestionPageAndAnswer({
          page: data.pagination.page,
          rows: data.pagination.rows,
          ...searchForm
        })
        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 = formatList(res.data.rows)
        }
      } catch (error) {}
    }

    const formatList = (item: any) => {
      item.forEach((child: any) => {
        if (child.children && child.children.length) {
          formatList(child.children)
        } else {
          child.children = null
        }
      })
      return item
    }

    const onSubmit = () => {
      data.pagination.page = 1
      getList()
    }
    onMounted(() => {
      getType()
      getList()
    })
    return () => (
      <div class={styles.questionBank}>
        <SaveForm
          ref={saveForm}
          style={{ 'box-shadow': 'none', marginBottom: 0, paddingTop: 0 }}
          label-width=""
          model={searchForm}
          onSubmit={onSubmit}
          onSetModel={(val: any) => Object.assign(searchForm, val)}
          saveKey="add-question-list-key"
        >
          <NFormItem path="keyword" label="关键字">
            <NInput
              placeholder="请输入题目名称/编号"
              v-model:value={searchForm.keyword}
              onKeydown={(e) => {
                if (e.code === 'Enter') {
                  onSubmit()
                }
              }}
              clearable
            />
          </NFormItem>
          <NFormItem path="score" label="分值">
            <NInput
              placeholder="请输入分值"
              v-model:value={searchForm.score}
              onKeydown={(e) => {
                if (e.code === 'Enter') {
                  onSubmit()
                }
              }}
              clearable
            />
          </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}
              options={data.categorys}
              checkStrategy="child"
              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>
        <NDataTable
          loading={data.loading}
          maxHeight="60vh"
          columns={columns()}
          data={data.list}
          row-key={(row: any) => row.id}
          defaultCheckedRowKeys={checkList.value}
          v-model:checkedRowKeys={data.selectList}
        ></NDataTable>

        <NSpace justify="space-between" align="center" style={{ padding: '8px 0' }}>
          <Pagination
            style={{ margin: 0 }}
            v-model:page={data.pagination.page}
            v-model:pageSize={data.pagination.rows}
            v-model:pageTotal={data.pagination.total}
            onList={getList}
            sync
            saveKey="add-question-list-page-key"
          ></Pagination>

          <NSpace>
            <NButton onClick={() => emit('select')}>取消</NButton>
            <NButton
              type="primary"
              onClick={() => {
                const list = data.list
                  .map((n: any) => (data.selectList.includes(n.id) ? n : null))
                  .filter(Boolean)
                console.log("🚀 ~ list", list)
                emit('select', list)
              }}
            >
              确定
            </NButton>
          </NSpace>
        </NSpace>
      </div>
    )
  }
})
