import {
  FormInst,
  FormItemRule,
  FormRules,
  NButton,
  NCascader,
  NDrawer,
  NDrawerContent,
  NForm,
  NFormItem,
  NInput,
  NInputNumber,
  NModal,
  NRadio,
  NRadioGroup,
  NSelect,
  NSpace,
  NSpin,
  NSwitch,
  NTag,
  NUpload,
  useMessage
} from 'naive-ui'
import { defineComponent, inject, onMounted, reactive, ref, watch } from 'vue'
import { fetchMaterailDetail, materialSave, updateMaterailData } from '../api'
import { materialType } from '../educationalData'
import UploadFile from '@/components/upload-file'
import { lessonType } from '@/views/knowledge-manage/knowledgeTypeData'
import SelectMusicSheet from './selectMusicSheet'

export default defineComponent({
  name: 'addMaterial',
  emits: ['handleSuccess', 'close'],
  props: ['item', 'isLook'],
  setup(props, { emit }) {
    const message = useMessage()
    const loading = ref(false)
    const formRef = ref<FormInst | null>(null)
    const formContentRef = ref<any>()
    const saveModel = reactive({
      name: '',
      sn: '', //序号
      materialCategoryId: '', //素材分类
      // adviseStudyTimeSecond: null,
      type: materialType.视频,
      content: '', // 视频、图片链接或者是曲目编号
      courseTypeCode: [], // 课程类型
      enableFlag: true //启用状态
    })
    onMounted(async () => {
      if (props?.item?.id) {
        loading.value = true
        const res: any = await fetchMaterailDetail(props.item.id)
        if (res?.code == 200) {
          Object.keys(saveModel).forEach((key: any) => {
            if (res?.data?.[key]) {
              if (key === 'adviseStudyTimeSecond') (saveModel as any)[key] = res.data[key] + ''
              else if (key === 'courseTypeCode')
                (saveModel as any)[key] = res.data[key]?.split(',') || []
              else (saveModel as any)[key] = res.data[key]
            }
            if (key === 'enableFlag') (saveModel as any)[key] = res.data[key]
          })
          if (saveModel.type === 'SONG') {
            musicOpentions.music = {
              musicSheetName: res.data.contentDesc
            }
          }
          console.log('🚀 ~ saveModel', saveModel)
        }
        loading.value = false
      }
    })
    function validateContent(rule: FormItemRule, value: string) {
      if (!value) {
        return saveModel.type === materialType.视频
          ? new Error('请上传视频')
          : saveModel.type === materialType.图片
          ? new Error('请上传图片')
          : new Error('请选择曲目')
      }
      return true
    }
    function validateAdviseStudyTimeSecond(rule: FormItemRule, value: string) {
      if (!value) {
        return new Error('请填写时间')
      }
      if (!/^\+?[1-9]\d*$/.test(value)) {
        return new Error('请填写正确的时间')
      }
      return true
    }
    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'] }],
      sn: [{ required: true, message: '分段编号', trigger: ['blur', 'change'] }],
      materialCategoryId: [
        { required: true, message: '请选择素材分类', trigger: ['blur', 'change'] }
      ],
      adviseStudyTimeSecond: [
        {
          validator: validateAdviseStudyTimeSecond,
          trigger: ['change']
        }
      ],
      content: [{ validator: validateContent, trigger: ['blur', 'change', 'input'] }],
      courseTypeCode: [
        {
          validator: validateCourseTypeCode,
          message: '请选择课程类型',
          trigger: ['blur', 'change']
        }
      ]
    }
    const categoryList = inject('categoryList', { list: [] }).list || []
    const submit = () => {
      formRef.value?.validate(async (err) => {
        if (!err) {
          const params: any = {
            ...saveModel,
            courseTypeCode: saveModel.courseTypeCode?.join(',') || ''
          }
          let res: any = null
          if (props?.item?.id) {
            params.id = props.item.id
            res = await updateMaterailData(params)
          } else {
            res = await materialSave(params)
          }
          if (res?.code == 200) {
            message.success('保存成功')
            emit('handleSuccess')
          } else {
            message.warning('保存失败')
          }
        }
      })
    }

    // 改变素材类型
    const changeType = () => {
      saveModel.content = ''
      musicOpentions.music = ''
    }

    // 添加曲谱
    const musicOpentions = reactive({
      show: false,
      music: '' as any
    })
    const hanldeSelectMusic = (musicItem: any) => {
      musicOpentions.music = musicItem
      saveModel.content = musicItem.id
      musicOpentions.show = false
      formContentRef.value?.restoreValidation()
      // console.log('🚀 ~ musicItem', musicItem)
    }
    return () => (
      <div>
        <NSpin show={loading.value}>
          <NForm
            disabled={props.isLook ? true : false}
            ref={formRef}
            onSubmit={submit}
            labelPlacement="top"
            model={saveModel}
            rules={rules}
            require-mark-placement="left"
          >
            <NSpace justify="space-between" item-style={{ flex: 1 }}>
              <NFormItem label="素材名称" path="name">
                <NInput v-model:value={saveModel.name} />
              </NFormItem>
              <NFormItem label="分段编号" path="sn">
                <NInput v-model:value={saveModel.sn} />
              </NFormItem>
            </NSpace>
            <NSpace justify="space-between" item-style={{ flex: 1 }}>
              <NFormItem label="素材分类" path="materialCategoryId">
                <NCascader
                  v-model:value={saveModel.materialCategoryId}
                  options={categoryList}
                  checkStrategy="child"
                  childrenField="subMaterialCategoryList"
                  expandTrigger="hover"
                  valueField="id"
                  labelField="name"
                />
              </NFormItem>
              {/* <NFormItem label="建议学习时长" path="adviseStudyTimeSecond" required>
                <NInput
                  v-model:value={saveModel.adviseStudyTimeSecond}
                  v-slots={{
                    suffix: () => '秒'
                  }}
                />
              </NFormItem> */}
            </NSpace>
            <NSpace justify="space-between" item-style={{ flex: 1 }}>
              <NFormItem label="课程类型" path="courseTypeCode">
                <NSelect
                  multiple
                  clearable
                  disabled={props?.item ? true : false}
                  value={saveModel.courseTypeCode}
                  onUpdateValue={(val: any) => {
                    saveModel.courseTypeCode = val
                  }}
                  options={lessonType}
                />
              </NFormItem>
              <NFormItem label="是否启用">
                <NSwitch v-model:value={saveModel.enableFlag} />
              </NFormItem>
            </NSpace>
            <NFormItem label="素材类型" required labelPlacement="left" path="type">
              <NRadioGroup v-model:value={saveModel.type} onUpdateValue={() => changeType()}>
                <NRadio value={materialType.视频}>视频</NRadio>
                <NRadio value={materialType.图片}>图片</NRadio>
                <NRadio value={materialType.曲目}>曲目</NRadio>
              </NRadioGroup>
            </NFormItem>

            <NFormItem label="上传素材" path="content" ref={formContentRef} required>
              {saveModel.type === materialType.曲目 ? (
                <NSpace>
                  <NButton
                    disabled={props.isLook}
                    type="primary"
                    onClick={() => (musicOpentions.show = true)}
                  >
                    选择曲谱
                  </NButton>
                  {musicOpentions.music && (
                    <NInput readonly value={musicOpentions.music?.musicSheetName}></NInput>
                  )}
                </NSpace>
              ) : (
                <UploadFile
                  accept={
                    saveModel.type === materialType.视频
                      ? 'video/*'
                      : saveModel.type === materialType.图片
                      ? 'image/*'
                      : ''
                  }
                  path="courseware/"
                  listType={saveModel.type === materialType.图片 ? 'image-card' : 'image'}
                  v-model:fileList={saveModel.content}
                  size={1024}
                  disabled={props.isLook}
                  onReadFileInputEventAsArrayBuffer={() => {
                    formContentRef.value?.restoreValidation()
                  }}
                ></UploadFile>
              )}
            </NFormItem>
          </NForm>
          {props.isLook ? (
            ''
          ) : (
            <NSpace justify="end">
              <NButton type="default" onClick={() => emit('close')}>
                取消
              </NButton>
              <NButton type="primary" onClick={submit}>
                保存
              </NButton>
            </NSpace>
          )}
        </NSpin>
        <NDrawer width="80vw" height="100vh" v-model:show={musicOpentions.show}>
          <NDrawerContent title="选择曲谱" closable>
            <SelectMusicSheet onSelect={(row: any) => hanldeSelectMusic(row)} />
          </NDrawerContent>
        </NDrawer>
      </div>
    )
  }
})
