import SaveForm from '@/components/save-form'
import { getLessonType, lessonType } from '@/views/knowledge-manage/knowledgeTypeData'
import {
  DataTableColumn,
  NBadge,
  NButton,
  NDataTable,
  NDatePicker,
  NDescriptions,
  NDescriptionsItem,
  NFormItem,
  NInput,
  NModal,
  NSelect,
  NSpace,
  NTab,
  NTabPane,
  NTabs,
  useDialog,
  useMessage
} from 'naive-ui'
import { defineComponent, onMounted, reactive, ref } from 'vue'
import {
  examinationKnowledgePointCategoryDel,
  examinationKnowledgePointCategoryPage,
  unitExaminationEnable,
  unitExaminationPage,
  unitExaminationRemove
} from '../../api'
import styles from '../index.module.less'
import AddExamination from '../model/addExamination'
import { filterTimes } from '@/utils/dateUtil'
import { useRouter } from 'vue-router'
import Pagination from '@/components/pagination'

export default defineComponent({
  name: 'unit-test-index',
  setup() {
    const router = useRouter()
    const dialog = useDialog()
    const message = useMessage()
    const data = reactive({
      pagination: {
        page: 1,
        rows: 10,
        total: 0
      },
      loading: false,
      active: '',
      list: [] as any
    })
    const saveForm = ref()
    const searchForm = reactive({
      time: null, //时间
      keyword: null, //	名称、编号
      enableFlag: null, // 启用状态
      courseTypeCode: null //
    })
    const modelData = reactive({
      open: false,
      title: '添加考点',
      item: null as any
    })
    /** 启用停用 */
    const handleChange = (row: any) => {
      dialog.warning({
        title: '警告',
        content: row.enableFlag ? '是否停用测验?' : '是否启用测验?',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
          const res = await unitExaminationEnable(row.id)
          if (res.data) {
            getList()
            message.success('修改成功')
          }
        }
      })
    }
    // 删除分类
    const handleDelete = (row: any) => {
      dialog.warning({
        title: '警告',
        content: '是否确认删除此测验?',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
          const res = await unitExaminationRemove(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: 'courseTypeCode',
          render(row: any) {
            return getLessonType(row.courseTypeCode)
          }
        },
        {
          title: '测验时长',
          key: 'courseTypeCode',
          render(row: any) {
            return row.timeMinutes + '分钟'
          }
        },
        {
          title: '信息',
          key: 'operatorName',
          render(row: any) {
            return (
              <>
                <NDescriptions labelPlacement="left" column={1}>
                  <NDescriptionsItem label="状态">
                    {row.enableFlag ? (
                      <NSpace size="small" align="center">
                        <NBadge dot type="success" />
                        <span>已启用</span>
                      </NSpace>
                    ) : (
                      <NSpace size="small" align="center">
                        <NBadge dot type="error" />
                        <span>未启用</span>
                      </NSpace>
                    )}
                  </NDescriptionsItem>
                  <NDescriptionsItem label="更新时间">{row.updateTime}</NDescriptionsItem>
                  <NDescriptionsItem label="操作">{row.operatorName}</NDescriptionsItem>
                </NDescriptions>
              </>
            )
          }
        },

        {
          title: '操作',
          key: 'operation',
          fixed: 'right',
          render(row: any) {
            return (
              <NSpace>
                <NButton
                  type={row.enableFlag ? 'error' : 'primary'}
                  text
                  onClick={() => handleChange(row)}
                >
                  {row.enableFlag ? '停用' : '启用'}
                </NButton>
                <NButton type="primary" text onClick={() => handleCreate(row)}>
                  修改
                </NButton>
                <NButton type="primary" text onClick={() => handleDelete(row)}>
                  删除
                </NButton>
              </NSpace>
            )
          }
        }
      ]
    }

    // 获取数据
    const getList = async () => {
      data.loading = true
      try {
        const { time, ...reset } = searchForm
        const res: any = await unitExaminationPage({
          page: data.pagination.page,
          rows: data.pagination.rows,
          ...reset,
          ...filterTimes(time, ['updateStartTime', 'updateEndTime'])
        })
        if (Array.isArray(res?.data?.rows)) {
          data.list = res.data.rows
          data.pagination.total = res.data.total
        }
      } catch (error) {}
      data.loading = false
    }
    const onSubmit = () => {
      data.pagination.page = 1
      getList()
    }
    onMounted(() => {
      getList()
    })

    // 创建阶段自测
    const handleCreate = (row?: any, isLock?: string) => {
      router.push({
        path: '/unitTestCreate',
        query: row
          ? {
              unitExaminationId: row.id,
              name: row.name,
              courseTypeCode: row.courseTypeCode,
              passScore: row.passScore,
              timeMinutes: row.timeMinutes
            }
          : {}
      })
    }
    return () => (
      <div class={styles.examination}>
        <SaveForm
          class={styles.form}
          ref={saveForm}
          // label-width=""
          model={searchForm}
          onSubmit={onSubmit}
          onSetModel={(val: any) => Object.assign(searchForm, val)}
          saveKey="unit-test-index-key"
        >
          <NFormItem path="keyword" label="关键字">
            <NInput
              placeholder="请输入编号/测验名称"
              v-model:value={searchForm.keyword}
              onKeydown={(e) => {
                if (e.code === 'Enter') {
                  onSubmit()
                }
              }}
              clearable
            />
          </NFormItem>
          <NFormItem path="courseTypeCode" label="课程类型">
            <NSelect
              placeholder="请选择课程类型"
              clearable
              v-model:value={searchForm.courseTypeCode}
              options={lessonType}
            />
          </NFormItem>
          <NFormItem path="enableFlag" label="状态">
            <NSelect
              placeholder="状态"
              v-model:value={searchForm.enableFlag}
              options={[
                { label: '启用', value: 1 },
                { label: '未启用', value: 0 }
              ]}
            ></NSelect>
          </NFormItem>
          <NFormItem path="time" label="时间">
            <NDatePicker
              class={styles.datepicker}
              v-model:value={searchForm.time}
              type="daterange"
              clearable
            />
          </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" onClick={() => handleCreate()}>
            创建阶段自测
          </NButton>
        </NSpace>
        <NDataTable
          scrollX={800}
          loading={data.loading}
          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="unit-test-index-key"
        ></Pagination>

        <NModal
          v-model:show={modelData.open}
          preset="dialog"
          showIcon={false}
          title={modelData.title}
          style={{ width: '400px' }}
          onClose={() => {
            modelData.item = null
          }}
        >
          <AddExamination
            item={modelData.item}
            onClose={() => {
              modelData.open = false
            }}
            onHandleSuccess={() => {
              modelData.open = false
              if (!modelData.item) {
                data.pagination.page = 1
              }
              getList()
            }}
          />
        </NModal>
      </div>
    )
  }
})
