import {
  Image,
  Icon,
  showLoadingToast,
  showSuccessToast,
  showFailToast,
  Popup,
  Swipe,
  SwipeItem
} from 'vant';
import {
  PropType,
  defineComponent,
  nextTick,
  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';
import deepClone from '@/helpers/deep-clone';

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,
      showButton: true,
      index: props.startPosition + 1,
      saveLoading: false,
      preLoading: 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();
          item?.onExitScreen();
        }
      });
    };

    onMounted(() => {
      forms.show = props.show;
      // console.log(window.document.body.clientWidth);
      document.documentElement.style.setProperty(
        '--window-page-width',
        (window.document.body.clientWidth || window.document.body.offsetWidth) +
          'px'
      );

      onChnageLeftWidth(forms.index - 1);
    });

    const onChnageLeftWidth = (index: number) => {
      document.documentElement.style.setProperty(
        '--window-page-position-left',
        (window.document.body.clientWidth || window.document.body.offsetWidth) *
          index +
          'px'
      );
    };

    watch(
      () => props.show,
      () => {
        forms.show = props.show;
        forms.index = props.startPosition + 1;
        forms.preLoading = props.show;
        onChnageLeftWidth(props.startPosition);
        // console.log(forms.preLoading, 'show');
        // nextTick(() => {
        //   // 判断打开的内容是否为视频，是则自动播放
        //   const defaultUrl = props.images[props.startPosition];
        //   console.log(defaultUrl, 'defaultUrl');
        //   if (checkFile(defaultUrl, 'video') && props.show) {
        //     console.log(1111, videoRef.value);
        //     //   videoRef.value[props.startPosition]?.onPlay();
        //     videoRef.value.forEach((item: any, child: any) => {
        //       if (child === props.startPosition) {
        //         console.log(item, 'item');
        //         item?.onPlay();
        //       }
        //     });
        //   }
        // });
      }
    );
    watch(
      () => props.startPosition,
      () => {
        forms.index = props.startPosition + 1;
        onChnageLeftWidth(props.startPosition);
      }
    );

    return () => (
      <Popup
        teleport={props.teleport}
        v-model:show={forms.show}
        overlay-class={styles.overlayPreview}
        class={['van-image-preview', styles.imagePreview]}>
        {forms.show ? (
          <>
            {forms.showButton && (
              <>
                <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;
                // forms.preLoading = true;
                onPlay(index);
                onChnageLeftWidth(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;
                          // if (forms.index === index + 1 && forms.preLoading) {
                          //   console.log(el, 'player');
                          //   el?.onPlay();
                          //   forms.preLoading = false;
                          // }
                        }}
                        // onReady={player => {
                        //   if (
                        //     props.startPosition === index &&
                        //     forms.preLoading
                        //   ) {
                        //     console.log(player, 'player');
                        //     player?.play();
                        //     forms.preLoading = false;
                        //   }
                        // }}
                        src={url}
                        onPlay={() => onPlay(index)}
                        preLoading={false}
                        // onEnterfullscreen={() => (forms.showButton = false)}
                        // onExitfullscreen={() => (forms.showButton = true)}
                      />
                    </div>
                  )}
                </SwipeItem>
              ))}
            </Swipe>
          </>
        ) : (
          ''
        )}
      </Popup>
    );
  }
});
