import UploadFile from '@/components/upload-file'
import { lessonType } from '@/views/knowledge-manage/knowledgeTypeData'
import {
  NButton,
  NButtonGroup,
  NForm,
  NFormItem,
  NInput,
  NRadio,
  NRadioGroup,
  NSelect,
  NSpace,
  NSpin,
  useMessage
} from 'naive-ui'
import { defineComponent, onMounted, reactive, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import styles from '../index.module.less'
import { lessonCoursewareDetail, lessonCoursewareSave, lessonCoursewareUpdate } from '../../api'

export default defineComponent({
  name: 'createCourseware',
  emits: ['next'],
  props: {
    course: {
      type: Object,
      default: () => {}
    }
  },
  setup(props, { emit }) {
    const message = useMessage()
    const route = useRoute()
    const router = useRouter()
    const query = route.query
    const loading = ref(false)
    const formRef = ref()
    const searchForm = reactive<any>({
      coverImg: '', //封面
      orchestraType: 'SINGLE_DELIVERY', // 乐团类型
      lessonTargetDesc: '', // 课件目标
      name: '', // 课件名称
      courseTypeCode: ''
    })
    const rules = {
      coverImg: [{ required: true, message: '请上传课件封面', trigger: ['blur', 'change'] }],
      lessonTargetDesc: [
        { required: true, message: '请填写课件目标', trigger: ['blur', 'change'] }
      ],
      name: [{ required: true, message: '请填写课件名称', trigger: ['blur', 'change'] }],
      courseTypeCode: [{ required: true, message: '请选择课程类型', trigger: ['blur', 'change'] }]
    }
    const getDetail = async () => {
      if (!query.id) return
      loading.value = true
      try {
        const { data } = await lessonCoursewareDetail(query.id)
        searchForm.coverImg = data.coverImg
        searchForm.orchestraType = data.orchestraType
        searchForm.lessonTargetDesc = data.lessonTargetDesc
        searchForm.name = data.name
        searchForm.courseTypeCode = data.courseTypeCode
        searchForm.enableFlag = data.enableFlag
      } catch (error) {}
      loading.value = false
    }
    onMounted(() => {
      //   getDetail()
      if (props.course) {
        searchForm.coverImg = props.course.coverImg
        searchForm.orchestraType = props.course.orchestraType
        searchForm.lessonTargetDesc = props.course.lessonTargetDesc
        searchForm.name = props.course.name
        searchForm.courseTypeCode = props.course.courseTypeCode
        searchForm.enableFlag = props.course.enableFlag
      }
      console.log('🚀 ~ props', props.course)
    })
    watch(
      () => searchForm.coverImg,
      (newVal, oldVal) => {
        formRef.value.validate()
      }
    )

    const handleCreate = (next?: string) => {
      formRef.value.validate(async (err: any) => {
        console.log(err)
        if (!err) {
          const body = {
            ...searchForm
          }
          let id: any = ''
          if (query.id) {
            //修改
            id = body.id = query.id
            try {
              const res: any = await lessonCoursewareUpdate(body)
              if (res.code === 200) {
                message.success('保存成功')
              }
              if (next) {
                emit('next')
              }
            } catch (error) {}
          } else {
            //创建
            try {
              const res: any = await lessonCoursewareSave(body)
              if (res?.data?.id) {
                message.success('保存成功')
                id = res?.data?.id
                router.push({
                  path: 'coursewareDetail',
                  query: {
                    id
                  }
                })
              }
            } catch (error) {}
          }
        }
      })
    }
    return () => (
      <div class={styles.createCourseware}>
        <NSpin v-model:show={loading.value}>
          <NForm
            ref={formRef}
            model={searchForm}
            rules={rules}
            disabled={query.isLook ? true : false}
          >
            <NFormItem label="课件名称" path="name" required>
              <NInput v-model:value={searchForm.name} />
            </NFormItem>
            <NFormItem label="乐团类型" path="orchestraType" required>
              <NSpace>
                <NButton
                  disabled={query.isLook ? true : false}
                  type={searchForm.orchestraType == 'SINGLE_DELIVERY' ? 'primary' : 'default'}
                  onClick={() => (searchForm.orchestraType = 'SINGLE_DELIVERY')}
                >
                  单交付团
                </NButton>
                <NButton
                  disabled={query.isLook ? true : false}
                  type={searchForm.orchestraType == 'MULTIPLE_DELIVERY' ? 'primary' : 'default'}
                  onClick={() => (searchForm.orchestraType = 'MULTIPLE_DELIVERY')}
                >
                  多交付常规团
                </NButton>
                <NButton
                  disabled={query.isLook ? true : false}
                  type={
                    searchForm.orchestraType == 'MULTIPLE_DELIVERY_SCHOOL' ? 'primary' : 'default'
                  }
                  onClick={() => (searchForm.orchestraType = 'MULTIPLE_DELIVERY_SCHOOL')}
                >
                  多交付校团
                </NButton>
              </NSpace>
            </NFormItem>
            <NFormItem label="课程类型" path="courseTypeCode" required>
              <NSelect
                disabled={route.query.id ? true : false}
                placeholder="课程类型"
                clearable
                v-model:value={searchForm.courseTypeCode}
                options={lessonType}
              />
            </NFormItem>
            <NFormItem label="教学目标" path="lessonTargetDesc" required>
              <NInput
                type="textarea"
                rows={4}
                maxlength={500}
                v-model:value={searchForm.lessonTargetDesc}
                showCount
              />
            </NFormItem>
            <NFormItem label="教材封面" path="coverImg" required>
              <UploadFile
                disabled={query.isLook ? true : false}
                path="courseware/"
                v-model:fileList={searchForm.coverImg}
              />
            </NFormItem>
            <NSpace>
              <NButton
                disabled={query.isLook ? true : false}
                type="primary"
                onClick={() => handleCreate()}
              >
                保 存
              </NButton>
              {query.id && (
                <NButton
                  onClick={() => {
                    handleCreate('next')
                  }}
                >
                  下一步
                </NButton>
              )}
            </NSpace>
          </NForm>
        </NSpin>
      </div>
    )
  }
})
