import {
  computed,
  defineComponent,
  nextTick,
  onMounted,
  reactive,
  ref
} from 'vue';
import styles from './index.module.less';
import {
  NButton,
  NCascader,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NModal,
  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-remove2.png';
import {
  api_materialTagPage,
  materialSave,
  materialUpdateAll
} from '../../../api';
import { NaturalTypeEnum } from '@/enums/pageEnum';
import { scrollToErrorForm } from '/src/utils';
import UploadCover from '../upload-cover';
import { modalClickMask } from '/src/state';

// 判断链接后辍
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: () => []
    },
    showDelete: {
      type: Boolean,
      default: false
    },
    editStatus: {
      type: Boolean,
      default: true
    }
  },
  emits: ['close', 'confirm', 'editAll'],
  setup(props, { emit }) {
    const catchStore = useCatchStore();
    const formRef = ref();
    const message = useMessage();
    const materialTags = ref<any[]>([]);

    // const uploadRef = ref();
    // const uploadList = ref([] as any);
    const uploadForms = reactive({
      list: [] as any[],
      uploading: false,
      uploadUrl: '',
      name: '',
      instrumentIds: [] as any
    });
    const changeCover = reactive({
      uploadCoverStatus: false,
      uploadType: '',
      uploadImg: null as any,
      uploadIndex: 0
    });

    // 判断类型
    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({
              instrumentIds: item.instrumentIds.join(','),
              openFlag: item.openFlag,
              coverImg: item.coverImg,
              name: item.name,
              tagIds: item.tagIds?.join(','),
              type: item.type,
              enableFlag: 1,
              content: item.content,
              id: item.id || null
            });
          });
          if (isUpdate.value) {
            if (!props.editStatus) {
              const { data } = await materialUpdateAll(body);
              message.success('保存成功');
              uploadForms.list = [];
              emit('close', true);
              emit('confirm', data);
            } else {
              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));

    /** 获取素材标签 */
    const getMaterialTags = async () => {
      const res = await api_materialTagPage({ page: 1, rows: 1000 });
      const result = res.data.rows || [];
      if (res.code === 200 && Array.isArray(result)) {
        materialTags.value = result.map((item: any) => ({
          label: item.name,
          value: item.id
        }));
      }
    };

    onMounted(async () => {
      await catchStore.getSubjects();
      await getMaterialTags();
      const list = props.list || [];
      const temps: any[] = [];
      list.forEach((item: any) => {
        temps.push({
          instrumentIds: item.instrumentIds
            ? item.instrumentIds.split(',').map((instrument: any) => instrument)
            : [],
          openFlag: item.openFlag,
          coverImg: item.coverImg,
          name: item.title,
          type: item.type,
          sourceFrom: item.sourceFrom,
          enableFlag: item.enableFlag,
          content: item.content,
          tagIds: item.tagIds?.split(','),
          id: item.id
        });
      });
      uploadForms.list = temps || [];
    });

    // 全选
    const chioseAll = (item: any, list: any) => {
      // item.instrumentIds = list.map((item: any) => {
      //   return item.id;
      // }) as any;
      const ids = [] as any;
      list.map((item: any) => {
        if (Array.isArray(item.instruments)) {
          item.instruments.forEach((c: any) => {
            ids.push(c.value);
          });
        }
      }) as any;
      item.instrumentIds = ids;
    };
    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 || props.showDelete) && (
                      <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}>
                      {item.type !== 'IMG' ? (
                        <NButton
                          class={styles.changeCover}
                          type="default"
                          bordered={false}
                          onClick={() => {
                            changeCover.uploadIndex = index;
                            changeCover.uploadImg = item.coverImg;
                            changeCover.uploadType = item.type;
                            changeCover.uploadCoverStatus = true;
                          }}>
                          更换封面
                        </NButton>
                      ) : (
                        <span></span>
                      )}

                      <div>
                        是否公开
                        <NSwitch
                          size="small"
                          v-model:value={item.openFlag}
                          disabled={
                            item.sourceFrom === 'TEACHER' &&
                            item.type === 'MUSIC'
                          }
                        />
                      </div>
                    </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
                    class={styles.mb12}
                    path={`list[${index}].instrumentIds`}
                    showFeedback={false}
                    rule={[
                      {
                        required: true,
                        message: '请选择资源可用乐器',
                        trigger: 'change',
                        type: 'array'
                      }
                    ]}>
                    <NCascader
                      v-model:value={item.instrumentIds}
                      placeholder="请选择资源可用乐器(可多选)"
                      options={catchStore.getEnableSubjects}
                      checkStrategy="child"
                      showPath={false}
                      childrenField="instruments"
                      expandTrigger="hover"
                      labelField="name"
                      valueField="id"
                      clearable
                      filterable
                      multiple
                      maxTagCount="responsive"
                      v-slots={{
                        action: () => (
                          <NButton
                            text
                            style=" --n-width: 100% "
                            onClick={() =>
                              chioseAll(item, catchStore.getEnableSubjects)
                            }>
                            全选
                          </NButton>
                        )
                      }}
                    />
                  </NFormItem>
                  <NFormItem
                    path={`list[${index}].tagIds`}
                    showFeedback={false}>
                    <NSelect
                      placeholder="请选择资源标签(最多选择3个)"
                      options={materialTags.value}
                      clearable
                      filterable
                      multiple
                      maxTagCount="responsive"
                      value={item.tagIds}
                      onUpdate:value={(newValue: any) => {
                        if (newValue.length > 3) {
                          // 如果超过 3 个，截取前 3 个
                          item.tagIds = newValue.slice(0, 3);
                          message.info('最多选择3个标签');
                        } else {
                          item.tagIds = newValue;
                        }
                      }}
                    />
                  </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>

        <NModal
          maskClosable={modalClickMask}
          v-model:show={changeCover.uploadCoverStatus}
          preset="card"
          showIcon={false}
          class={['modalTitle ', styles.uploadCover]}
          blockScroll={false}>
          <UploadCover
            img={changeCover.uploadImg}
            onClose={() => (changeCover.uploadCoverStatus = false)}
            onConfirm={(val: any) => {
              if (changeCover.uploadType === 'IMG') {
                uploadForms.list[changeCover.uploadIndex].content = val;
              }
              uploadForms.list[changeCover.uploadIndex].coverImg = val;
            }}
          />
        </NModal>
      </div>
    );
  }
});
