import {
  Image,
  Icon,
  showLoadingToast,
  showSuccessToast,
  showFailToast,
  Popup,
  Swipe,
  SwipeItem
} from 'vant';
import {
  PropType,
  defineComponent,
  onMounted,
  reactive,
  ref,
  watch
} from 'vue';
import styles from './index.module.less';
import iconPreviewClose from '@/common/images/icon-preview-close.png';
import iconPreviewDownload from '@/common/images/icon-preview-download.png';
import { promisefiyPostMessage } from '@/helpers/native-message';
import { checkFile } from '@/helpers/toolsValidate';
import MVideo from '../m-video';
import { state } from '@/state';
import { browser } from '@/helpers/utils';

export default defineComponent({
  name: 'm-image-preview',
  props: {
    show: {
      tyep: Boolean,
      default: false
    },
    images: {
      type: Array as PropType<string[]>,
      default: () => []
    },
    showIndex: {
      type: Boolean,
      default: true
    },
    startPosition: {
      type: Number,
      default: 0
    },
    loop: {
      type: Boolean,
      default: false
    },
    showDownload: {
      type: Boolean,
      default: true
    },
    teleport: {
      type: String,
      default: ''
    }
  },
  emits: ['update:show'],
  setup(props, { emit }) {
    const forms = reactive({
      show: false,
      index: props.startPosition + 1,
      saveLoading: false
    });

    const onSave = async (img: string) => {
      if (forms.saveLoading) return;
      forms.saveLoading = true;
      showLoadingToast({ message: '下载中...', forbidClick: true });
      try {
        const res = await promisefiyPostMessage({
          api: 'saveFile',
          content: {
            img,
            type: checkFile(img, 'image') ? 'image' : 'video'
          }
        });
        if (res?.content?.status === 'success') {
          showSuccessToast('保存成功');
        } else {
          showFailToast('保存失败');
        }
      } catch {
        //
      }
      forms.saveLoading = false;
    };

    const videoRef: any = ref([]);
    const onPlay = (index: any) => {
      videoRef.value.forEach((item: any, child: any) => {
        if (child !== index) {
          item?.onStop();
        }
      });
    };

    onMounted(() => {
      forms.show = props.show;
    });

    watch(
      () => props.show,
      () => {
        forms.show = props.show;
        forms.index = props.startPosition + 1;
      }
    );
    watch(
      () => props.startPosition,
      () => {
        forms.index = props.startPosition + 1;
      }
    );

    onMounted(() => {
      // navBarHeight;
      // document.documentElement.style.setProperty(
      //   '--header-height',
      //   height + 'px'
      // );
    });
    return () => (
      <Popup
        teleport={props.teleport}
        v-model:show={forms.show}
        overlay-class={styles.overlayPreview}
        class={['van-image-preview', styles.imagePreview]}>
        {forms.show ? (
          <>
            <Icon
              name={iconPreviewClose}
              class="van-image-preview__close-icon van-image-preview__close-icon--top-left van-haptics-feedback"
              style={{
                top: state.navBarHeight
                  ? state.navBarHeight + 'px'
                  : 'var(--van-padding-md)'
              }}
              onClick={() => {
                onPlay(-1);
                emit('update:show', false);
              }}
            />
            <div
              class={'van-image-preview__index'}
              style={{
                top: state.navBarHeight
                  ? state.navBarHeight + 'px'
                  : 'var(--van-padding-md)'
              }}>
              {forms.index} / {props.images.length}
            </div>
            {props.showDownload && browser().isApp ? (
              <Icon
                name={iconPreviewDownload}
                class="van-image-preview__close-icon van-image-preview__close-icon--top-right van-haptics-feedback"
                style={{
                  top: state.navBarHeight
                    ? state.navBarHeight + 'px'
                    : 'var(--van-padding-md)'
                }}
                onClick={() => {
                  console.log(
                    forms.index,
                    'index',
                    props.images[forms.index - 1]
                  );

                  onSave(props.images[forms.index - 1]);
                }}
              />
            ) : (
              ''
            )}
            <Swipe
              autoplay={0}
              loop={false}
              class={'van-image-preview__swipe'}
              showIndicators={false}
              initialSwipe={props.startPosition}
              onChange={(index: number) => {
                forms.index = index + 1;
                onPlay(index);
              }}
              lazyRender>
              {props.images.map((url: string, index: number) => (
                <SwipeItem
                  class={'van-image-preview__swipe-item'}
                  onClick={() => {
                    onPlay(-1);
                    emit('update:show', false);
                  }}>
                  {checkFile(url, 'image') ? (
                    <Image class="van-image-preview__image" src={url} />
                  ) : (
                    <div
                      class="van-image-preview__image"
                      onClick={(e: MouseEvent) => {
                        e.stopPropagation();
                        e.preventDefault();
                      }}>
                      <MVideo
                        ref={(el: any) => (videoRef.value[index] = el)}
                        src={url}
                        onPlay={() => onPlay(index)}
                        preLoading={false}
                      />
                    </div>
                  )}
                </SwipeItem>
              ))}
            </Swipe>
          </>
        ) : (
          ''
        )}
      </Popup>
    );
  }
});
