import {
  computed,
  defineComponent,
  nextTick,
  onMounted,
  reactive,
  ref
} from 'vue';
import styles from './index.module.less';
import {
  NButton,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NScrollbar,
  NSelect,
  NSpace,
  NSwitch,
  useMessage
} from 'naive-ui';
import UploadFile from './upload-file';
import { useCatchStore } from '/src/store/modules/catchData';
import iconImage from '@common/images/icon-image.png';
import iconVideo from '@common/images/icon-video.png';
import iconAudio from '@common/images/icon-audio.png';
import iconMusic from '@common/images/icon-music.png';
import iconPPT from '@common/images/icon-ppt.png';
import iconUploadDelete from '../../../images/btn-remove.png';
import { materialSave, materialUpdateAll } from '../../../api';
import { NaturalTypeEnum } from '@/enums/pageEnum';
import { scrollToErrorForm } from '/src/utils';

// 判断链接后辍
export const formatUrlType = (url: string) => {
  if (!url) return '';
  if (url?.indexOf('.mp3') > -1) {
    return NaturalTypeEnum.SONG;
  } else if (url?.indexOf('.mp4') > -1) {
    return NaturalTypeEnum.VIDEO;
  } else if (url?.indexOf('.ppt') > -1) {
    return NaturalTypeEnum.PPT;
  } else {
    return NaturalTypeEnum.IMG;
  }
};

export default defineComponent({
  name: 'upload-modal',
  props: {
    list: {
      type: Array,
      default: () => []
    },
    editStatus: {
      type: Boolean,
      default: true
    }
  },
  emits: ['close', 'confirm', 'editAll'],
  setup(props, { emit }) {
    const catchStore = useCatchStore();
    const formRef = ref();
    const message = useMessage();

    const uploadRef = ref();
    const uploadList = ref([] as any);
    const uploadForms = reactive({
      list: [] as any[],
      uploading: false,
      uploadUrl: '',
      name: '',
      subjectIds: [] as any
    });

    // 判断类型
    const formatType = (type: string) => {
      let typeImg = iconImage;
      switch (type) {
        case 'IMG':
          typeImg = iconImage;
          break;
        case 'VIDEO':
          typeImg = iconVideo;
          break;
        case 'SONG':
          typeImg = iconAudio;
          break;
        case 'MUSIC':
          typeImg = iconMusic;
          break;
        case 'PPT':
          typeImg = iconPPT;
          break;
      }
      return typeImg;
    };

    const onSubmit = async () => {
      //
      formRef.value?.validate(async (err: any) => {
        if (err) {
          nextTick(scrollToErrorForm);
          return;
        }
        uploadForms.uploading = true;
        try {
          const body: any[] = [];
          uploadForms.list.forEach(item => {
            body.push({
              subjectIds: item.subjectIds.join(','),
              openFlag: item.openFlag,
              coverImg: item.coverImg,
              name: item.name,
              type: item.type,
              enableFlag: 1,
              content: item.content,
              id: item.id || null
            });
          });
          if (isUpdate.value) {
            // await materialUpdateAll(body);
            emit('editAll', body);
            uploadForms.list = [];
          } else {
            await materialSave(body);
            message.success('保存成功');
            uploadForms.list = [];
            emit('close', true);
            emit('confirm');
          }
        } catch {
          //
        }
        uploadForms.uploading = false;
      });
    };

    const handleRemove = (index: number) => {
      uploadForms.list.splice(index, 1);
    };

    const isUpdate = computed(() => (props.list.length > 0 ? true : false));

    onMounted(async () => {
      const list = props.list || [];
      const temps: any[] = [];
      list.forEach((item: any) => {
        temps.push({
          subjectIds: item.subjectId
            ? item.subjectId
                .split(',')
                .map((subjectId: any) => Number(subjectId))
            : [],
          openFlag: item.openFlag,
          coverImg: item.coverImg,
          name: item.title,
          type: item.type,
          sourceFrom: item.sourceFrom,
          enableFlag: item.enableFlag,
          content: item.content,

          id: item.id
        });
      });
      uploadForms.list = temps || [];

      // console.log(temps, 'uploadForms');
      await catchStore.getSubjects();
    });

    // 全选
    const chioseAll = (item: any, list: any) => {
      item.subjectIds = list.map((item: any) => {
        return item.id;
      }) as any;
    };
    return () => (
      <div class={styles.uploadModal}>
        <NScrollbar style={{ 'max-height': '55vh' }}>
          <NForm
            ref={formRef}
            labelPlacement="left"
            labelWidth={120}
            model={uploadForms}
            class={styles.formModal}>
            <NSpace class={styles.formSpace}>
              {uploadForms.list.map((item: any, index: number) => (
                <div class={styles.formItem} key={index}>
                  <div class={styles.previewModal}>
                    <NImage
                      class={[styles.titleType]}
                      src={formatType(item.type)}
                      previewDisabled
                      objectFit="cover"
                    />
                    {/* 编辑时不能删除 */}
                    {!isUpdate.value && (
                      <img
                        class={[styles.iconUploadDelete]}
                        src={iconUploadDelete}
                        onClick={() => handleRemove(index)}
                      />
                    )}

                    <NImage
                      class={[styles.cover, styles.image]}
                      lazy
                      previewDisabled
                      src={item.coverImg}
                      objectFit="cover"
                    />

                    <div class={styles.commonType}>
                      是否公开：
                      <NSwitch
                        size="small"
                        v-model:value={item.openFlag}
                        disabled={
                          item.sourceFrom === 'TEACHER' && item.type === 'MUSIC'
                        }
                      />
                    </div>
                  </div>
                  <NFormItem
                    showFeedback={false}
                    path={`list.${index}.name`}
                    rule={[
                      {
                        required: true,
                        message: '请输入资源名称',
                        trigger: ['input', 'blur']
                      }
                    ]}>
                    <NInput
                      v-model:value={item.name}
                      placeholder="请输入资源名称"
                      maxlength={25}
                      clearable
                    />
                  </NFormItem>
                  <NFormItem
                    path={`list[${index}].subjectIds`}
                    showFeedback={false}
                    rule={[
                      {
                        required: true,
                        message: '请选择素材可用声部',
                        trigger: 'change',
                        type: 'array'
                      }
                    ]}>
                    <NSelect
                      v-model:value={item.subjectIds}
                      placeholder="请选择素材可用声部(可多选)"
                      options={catchStore.getSubjectList}
                      labelField="name"
                      valueField="id"
                      multiple
                      maxTagCount={2}
                      clearable
                      v-slots={{
                        action: () => (
                          <>
                            <NButton
                              text
                              style=" --n-width: 100% "
                              onClick={() =>
                                chioseAll(item, catchStore.getSubjectList)
                              }>
                              全选
                            </NButton>
                          </>
                        )
                      }}
                    />
                  </NFormItem>
                </div>
              ))}

              {/* {!isUpdate.value && (
                <div class={styles.formItem}>
                  <UploadFile
                    v-model:fileList={uploadForms.uploadUrl}
                    accept=".jpg,jpeg,.png,audio/mp3,video/mp4"
                    showFileList={false}
                    ref={uploadRef}
                    // cropper
                    multiple
                    max={10}
                    // options={{
                    //   autoCropWidth: 320,
                    //   autoCropHeight: 180,
                    //   fixedBox: true
                    // }}
                    onFinished={(val: any) => {
                      console.log(val, 'val');
                      uploadList.value.push({
                        subjectIds: uploadForms.subjectIds || [],
                        openFlag: true,
                        coverImg: val.coverImg,
                        name: uploadForms.name || '',
                        type: formatUrlType(val.content),
                        enableFlag: 1,
                        content: val.content
                      });
                      // uploadForms.list.push({
                      //   subjectIds: uploadForms.subjectIds || [],
                      //   openFlag: true,
                      //   coverImg: val.coverImg,
                      //   name: uploadForms.name || '',
                      //   type: formatUrlType(val.content),
                      //   enableFlag: 1,
                      //   content: val.content
                      // });
                      const timer = setTimeout(() => {
                        uploadForms.list.push(...uploadList.value);
                        uploadList.value = [];
                        uploadForms.uploadUrl = '';
                        uploadForms.name = '';
                        uploadForms.subjectIds = [];
                        uploadRef.value.handleClearFile();
                      }, 1000);
                    }}
                  />
                  <NFormItem showFeedback={false}>
                    <NInput
                      v-model:value={uploadForms.name}
                      placeholder="请输入资源名称"
                      maxlength={25}
                      clearable
                    />
                  </NFormItem>
                  <NFormItem showFeedback={false}>
                    <NSelect
                      v-model:value={uploadForms.subjectIds}
                      placeholder="请选择素材可用声部(可多选)"
                      options={catchStore.getSubjectList}
                      labelField="name"
                      valueField="id"
                      multiple
                      maxTagCount={2}
                      clearable
                      v-slots={{
                        action: () => (
                          <>
                            <NButton
                              text
                              style=" --n-width: 100% "
                              onClick={() =>
                                chioseAll(
                                  uploadForms,
                                  catchStore.getSubjectList
                                )
                              }>
                              全选
                            </NButton>
                          </>
                        )
                      }}
                    />
                  </NFormItem>
                </div>
              )} */}
            </NSpace>
          </NForm>
        </NScrollbar>

        <NSpace class={styles.btnGroup} justify="center">
          <NButton round onClick={() => emit('close')}>
            {props.editStatus ? '取消' : '上一步'}
          </NButton>
          <NButton
            round
            type="primary"
            loading={uploadForms.uploading}
            disabled={uploadForms.list.length === 0}
            onClick={onSubmit}>
            确定
          </NButton>
        </NSpace>
      </div>
    );
  }
});
