import Pagination from '@/components/pagination'
import SaveForm from '@/components/save-form'
import { filterTimes } from '@/utils/dateUtil'
import { getLessonType, lessonType } from '@/views/knowledge-manage/knowledgeTypeData'
import {
  DataTableColumn,
  FormRules,
  NButton,
  NDataTable,
  NDatePicker,
  NForm,
  NFormItem,
  NInput,
  NModal,
  NSelect,
  NSpace,
  NSpin,
  NTabPane,
  NTabs,
  useMessage
} from 'naive-ui'
import { computed, defineComponent, onMounted, reactive, ref } from 'vue'
import { useRoute } from 'vue-router'
import {
  lessonCoursewareExaminationMapperDetail,
  lessonCoursewareExaminationMapperUpSet,
  unitExaminationPage
} from '../../api'

export default defineComponent({
  name: 'AddUnitTest',
  props: {
    courseTypeCode:{
      type: String,
      default: ''
    },
    list: {
      type: Array,
      default: () => []
    },
    item: {
      type: Object,
      default: () => {}
    }
  },
  emits: ['close'],
  setup(props, { emit }) {
    const message = useMessage()
    const route = useRoute()
    const query = route.query
    const loading = ref(false)
    const formRef = ref()
    const classList = computed(() => {
      return props.list.map((n: any) => {
        return {
          label: n.name,
          value: n.id
        }
      })
    })
    const saveModel = reactive({
      id: null,
      name: '',
      desc: '',
      lessonCoursewareId: query.id,
      parentCoursewareDetailId: null as any,
      details: [
        {
          level: 1,
          unitExaminationId: '',
          unitExaminationName: '',
          lessonCoursewareExaminationMapperId: ''
        },
        {
          level: 2,
          unitExaminationId: '',
          unitExaminationName: '',
          lessonCoursewareExaminationMapperId: ''
        },
        {
          level: 3,
          unitExaminationId: '',
          unitExaminationName: '',
          lessonCoursewareExaminationMapperId: ''
        }
      ]
    })
    const formRules: FormRules = {
      name: [{ required: true, message: '请填写测验名称', trigger: ['blur', 'change'] }],
      desc: [{ required: true, message: '请填写测验描述', trigger: ['blur', 'change'] }],
      parentCoursewareDetailId: [
        { required: true, message: '请选择上一节课程', trigger: ['blur', 'change'] }
      ]
    }
    /** 查询详情 */
    const getDetail = async () => {
      if (!props.item.id) return
      loading.value = true
      try {
        const res: any = await lessonCoursewareExaminationMapperDetail(props.item.id)
        if (res?.code == 200) {
          Object.keys(saveModel).map((key: any) => {
            if (key == 'details') {
              for (let i = 0; i < saveModel.details.length; i++) {
                if (res.data.details[i]) {
                  saveModel.details[i] = res.data.details[i]
                }
              }
            } else {
              ;(saveModel as any)[key] = res.data[key]
            }
          })
        }
      } catch (error) {}
      loading.value = false
    }
    const submit = () => {
      formRef.value.validate(async (err: any) => {
        if (!err) {
          const body = {
            ...saveModel
          }
          console.log('🚀 ~ body', body)
          try {
            const res: any = await lessonCoursewareExaminationMapperUpSet(body)
            if (res.code == 200) {
              message.success('保存成功')
              emit('close', true)
            }
          } catch (error) {}
        }
      })
    }
    const modalData = reactive({
      open: false,
      active: 0
    })
    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, //	名称、编号
      courseTypeCode: props.courseTypeCode //
    })
    // 获取数据
    const getList = async () => {
      data.loading = true
      try {
        const { time, ...reset } = searchForm
        const res: any = await unitExaminationPage({
          page: data.pagination.page,
          rows: data.pagination.rows,
          enableFlag: true, // 启用状态
          ...reset,
          ...filterTimes(time, ['updateStartTime', 'updateEndTime']),
          courseTypeCode: props.courseTypeCode,
        })
        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(() => {
      getDetail()
      getList()
    })
    const columns = (): DataTableColumn[] => {
      return [
        {
          title: '测验名称',
          key: 'name',
          width: 230,
          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: 'timeMinutes',
          render(row: any) {
            return row.timeMinutes + '分钟'
          }
        },
        {
          title: '更新时间',
          key: 'updateTime'
        },
        {
          title: '更新人',
          key: 'operatorName'
        },
        {
          title: '操作',
          key: 'action',
          render(row: any) {
            return (
              <NButton
                text
                type="primary"
                onClick={() => {
                  saveModel.details[modalData.active].unitExaminationName = row.name
                  saveModel.details[modalData.active].unitExaminationId = row.id
                  modalData.open = false
                }}
              >
                选择
              </NButton>
            )
          }
        }
      ]
    }
    return () => (
      <div>
        <NSpin show={loading.value}>
          <NForm ref={formRef} model={saveModel} rules={formRules}>
            <NFormItem label="测验名称" path="name" required>
              <NInput v-model:value={saveModel.name} />
            </NFormItem>
            <NFormItem label="测验描述" path="desc" required>
              <NInput
                type="textarea"
                rows={3}
                maxlength={100}
                showCount
                v-model:value={saveModel.desc}
              />
            </NFormItem>
            <NFormItem label="测验课程" path="parentCoursewareDetailId" required>
              <NSelect
                options={classList.value}
                v-model:value={saveModel.parentCoursewareDetailId}
              ></NSelect>
            </NFormItem>
            <NFormItem
              label="单团学生阶段自测"
              path={`details[0].unitExaminationId`}
              required
              rule={{
                required: true,
                message: '请选择单团阶段自测',
                trigger: ['blur', 'blur']
              }}
            >
              <NInput
                placeholder="请选择阶段自测"
                readonly
                onClick={() => {
                  modalData.open = true
                  modalData.active = 0
                }}
                v-model:value={saveModel.details[0].unitExaminationName}
              ></NInput>
            </NFormItem>
            <NFormItem
              label="双团学生阶段自测"
              path={`details[1].unitExaminationId`}
              required
              rule={{
                required: true,
                message: '请选择双团阶段自测',
                trigger: ['blur', 'blur']
              }}
            >
              <NInput
                placeholder="请选择阶段自测"
                readonly
                onClick={() => {
                  modalData.open = true
                  modalData.active = 1
                }}
                v-model:value={saveModel.details[1].unitExaminationName}
              ></NInput>
            </NFormItem>
            <NFormItem
              label="多团学生阶段自测"
              path={`details[2].unitExaminationId`}
              required
              rule={{
                required: true,
                message: '请选择多团阶段自测',
                trigger: ['blur', 'blur']
              }}
            >
              <NInput
                placeholder="请选择阶段自测"
                readonly
                onClick={() => {
                  modalData.open = true
                  modalData.active = 2
                }}
                v-model:value={saveModel.details[2].unitExaminationName}
              ></NInput>
            </NFormItem>
            <NSpace justify="end">
              <NButton onClick={() => emit('close')}>取消</NButton>
              <NButton type="primary" onClick={submit}>
                保存
              </NButton>
            </NSpace>
          </NForm>
        </NSpin>
        <NModal
          showIcon={false}
          title="选择阶段自测"
          preset="dialog"
          style={{ width: '80vw' }}
          v-model:show={modalData.open}
        >
          <SaveForm
            style={{ padding: 0 }}
            ref={saveForm}
            label-width=""
            model={searchForm}
            onSubmit={onSubmit}
            onSetModel={(val: any) => Object.assign(searchForm, val)}
            saveKey="AddUnitTest-key"
          >
            <NSpace>
              <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="time" label="时间">
                <NDatePicker 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>
            </NSpace>
          </SaveForm>
          <NDataTable
            scrollX={800}
            maxHeight={'500px'}
            loading={data.loading}
            columns={columns()}
            data={data.list}
            row-key={(row: any) => row.categoryId}
          ></NDataTable>
          <NSpace
            style={{ padding: '10px 0' }}
            justify="space-between"
            align="center"
            wrapItem={false}
          >
            <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="AddUnitTest-key"
            ></Pagination>
          </NSpace>
        </NModal>
      </div>
    )
  }
})
