import {
  FormInst,
  FormItemRule,
  FormRules,
  NButton,
  NForm,
  NFormItem,
  NInput,
  NSpace,
  NSelect,
  NSpin,
  useMessage,
  NRadio,
  NRadioGroup,
  NInputNumber
} from 'naive-ui'
import { SelectMixedOption } from 'naive-ui/es/select/src/interface'
import { defineComponent, onMounted, reactive, ref } from 'vue'
import { knowledgePointSave, knowledgePointUpdate } from '../../api'
import { knowledgeTypeData } from '../../knowledgeTypeData'

export default defineComponent({
  name: 'KnowledgeModel',
  emits: ['handleSuccess', 'close'],
  props: ['item'],
  setup(props, { emit }) {
    const message = useMessage()
    const loading = ref(false)
    const formRef = ref<FormInst | null>(null)
    const saveModel = reactive({
      id: props?.item?.id ? props?.item?.id : null,
      name: props?.item?.name || '',
      courseTypeCode: props?.item?.courseTypeCode?.split(',') || [], //课程类型
      autoPlayFlag: props?.item?.autoPlayFlag == true ? 1 : 0,
      totalMaterialTimeSecond: props?.item?.totalMaterialTimeSecond,
      parentId: props?.item?.parentId || 0 // 默认第一层级
    })
    function validateCourseTypeCode(rule: FormItemRule, value: []) {
      if (Array.isArray(value) && !value.length) {
        return new Error('请选择课程类型')
      }
      return true
    }
    const rules: FormRules = {
      name: [{ required: true, message: '请输入知识点名称', trigger: ['blur', 'change'] }],
      courseTypeCode: [
        {
          validator: validateCourseTypeCode,
          message: '请选择课程类型',
          trigger: ['blur', 'change']
        }
      ]
    }

    const handleOptions = () => {
      let _obj: SelectMixedOption[] = []
      Object.keys(knowledgeTypeData).map((key) => {
        _obj.push({
          label: knowledgeTypeData[key],
          value: key
        })
      })
      return _obj
    }
    const hanldeAdd = () => {
      formRef.value?.validate(async (err) => {
        console.log('🚀 ~ err', err)
        if (!err) {
          const params: any = {
            ...saveModel,
            courseTypeCode: saveModel.courseTypeCode?.join(',') || ''
          }
          let res: any = null
          let isCreate = ''
          if (saveModel.id) {
            res = await knowledgePointUpdate(params)
          } else {
            res = await knowledgePointSave(params)
            isCreate = res.data
          }
          if (res?.code == 200) {
            message.success('保存成功')
            emit('handleSuccess', isCreate)
          } else {
            message.warning('保存失败')
          }
        }
      })
    }
    return () => (
      <div>
        <NSpin show={loading.value}>
          <NForm
            ref={formRef}
            labelPlacement="top"
            model={saveModel}
            rules={rules}
            require-mark-placement="left"
          >
            <NFormItem label="知识点名称" path="name">
              <NInput v-model:value={saveModel.name} />
            </NFormItem>
            <NFormItem label="课程类型" path="courseTypeCode">
              <NSelect
                multiple
                disabled={props?.item ? true : false}
                v-model:value={saveModel.courseTypeCode}
                options={handleOptions()}
                clearable
              />
            </NFormItem>
            <NFormItem
              label="建议学习时长"
              path="totalMaterialTimeSecond"
              rule={[
                {
                  required: true,
                  type: 'number',
                  min: 0,
                  message: '请输入正确建议学习时长',
                  trigger: 'blur'
                }
              ]}
            >
              <NInputNumber
                placeholder="请输入建议学习时长"
                showButton={false}
                v-model:value={saveModel.totalMaterialTimeSecond}
                v-slots={{
                  suffix: () => 's(秒)'
                }}
              />
            </NFormItem>
            <NFormItem label="自动播放下一知识点" path="autoPlayFlag">
              <NRadioGroup v-model:value={saveModel.autoPlayFlag}>
                <NRadio value={1}>是</NRadio>
                <NRadio value={0}>否</NRadio>
              </NRadioGroup>
            </NFormItem>
          </NForm>
          <NSpace justify="end">
            <NButton onClick={() => emit('close')}>取消</NButton>
            <NButton type="primary" onClick={hanldeAdd}>
              保存
            </NButton>
          </NSpace>
        </NSpin>
      </div>
    )
  }
})
