import {
  FormInst,
  FormItemRule,
  FormRules,
  NButton,
  NCascader,
  NDrawer,
  NDrawerContent,
  NForm,
  NFormItem,
  NInput,
  NInputGroup,
  NRadio,
  NRadioGroup,
  NSelect,
  NSpace,
  NSpin,
  NSwitch,
  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'
import Editor from '@/components/editor'

export default defineComponent({
  name: 'addMaterial',
  emits: ['handleSuccess', 'close'],
  props: ['item', 'isLook', 'categoryList'],
  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: null, //素材分类
      // adviseStudyTimeSecond: null,
      type: materialType.视频,
      phaseGoals: null,
      checkItem: null,
      materialRefs: [] as any,
      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 = {
              name: res.data.contentDesc
            }
          }
          //  else {
          //   if (res.data.materialRefs && res.data.materialRefs.length > 0) {
          //     res.data.materialRefs.forEach((row: any) => {
          //       saveModel.materialRefs.push({
          //         resourceId: row.resourceId,
          //         knowledgeType: row.knowledgeType,
          //         resourceName: row.resourceName
          //       })
          //     })
          //   }
          // }
          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']
        }
      ],
      phaseGoals: [{
        required: true, message: '请填写阶段目标' , trigger: ['blur', 'change', 'input']
      }],
      checkItem: [{
        required: true, message: '请填写检查事项', trigger: ['blur', 'change', 'input']
      }]
    }
    // 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,
      type: ''
    })
    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}
                  placeholder="请选择素材分类"
                  options={props.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>

            <NSpace justify="space-between" item-style={{ flex: 1 }}>
              <NFormItem label="上传素材" path="content" ref={formContentRef} required>
                {saveModel.type === materialType.曲目 ? (
                  <NSpace>
                    <NButton
                      disabled={props.isLook}
                      type="primary"
                      onClick={() => {
                        musicOpentions.show = true
                        musicOpentions.type = 'upload'
                      }}
                    >
                      选择曲谱
                    </NButton>
                    {musicOpentions.music && (
                      <NInput disabled value={musicOpentions.music?.name}></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>

              {saveModel.type !== 'SONG' && (
                <NFormItem label="关联曲目">
                  <NSpace>
                    <NButton
                      disabled={props.isLook}
                      type="primary"
                      onClick={() => {
                        musicOpentions.show = true
                        musicOpentions.type = 'correlation'
                      }}
                    >
                      选择曲谱
                    </NButton>
                    {saveModel.materialRefs.length > 0 && (
                      <NInputGroup>
                        <NInput disabled value={saveModel.materialRefs[0]?.resourceName}></NInput>
                        <NButton
                          type="primary"
                          disabled={props.isLook}
                          onClick={() => {
                            saveModel.materialRefs = []
                          }}
                        >
                          删除
                        </NButton>
                      </NInputGroup>
                    )}
                  </NSpace>
                </NFormItem>
              )}
            </NSpace>

            <NFormItem label="阶段目标" required labelPlacement="left" path="phaseGoals">
              <Editor v-model:value={saveModel.phaseGoals}
                  editorType="simple"
                  maxLength={1000}
                  bucketName="news-info"
                  excludeKeys={[
                    'emotion',
                    'insertTable',
                    'uploadImage',
                    'uploadVideo',
                    'bulletedList',
                    'numberedList',
                    'blockquote',
                    'divider'
                  ]} />
            </NFormItem>
            <NFormItem label="检查事项" required labelPlacement="left" path="checkItem">
            <Editor v-model:value={saveModel.checkItem}
                  maxLength={1000}
                  editorType="simple"
                  bucketName="news-info"
                  excludeKeys={[
                    'emotion',
                    'insertTable',
                    'uploadImage',
                    'uploadVideo',
                    'bulletedList',
                    'numberedList',
                    'blockquote',
                    'divider'
                  ]} />
            </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
              type={musicOpentions.type}
              onSelect={(row: any) => {
                console.log(musicOpentions.type, row)
                if (musicOpentions.type === 'upload') {
                  hanldeSelectMusic(row)
                } else {
                  saveModel.materialRefs = [
                    {
                      resourceId: row.id,
                      knowledgeType: 'MUSIC',
                      resourceName: row.name
                    }
                  ]
                  musicOpentions.show = false
                }
              }}
            />
          </NDrawerContent>
        </NDrawer>
      </div>
    )
  }
})
