import { computed, defineComponent, ref } from 'vue';
import {
  NImage,
  NDivider,
  NButton,
  NModal,
  useMessage,
  ImageRenderToolbarProps
} from 'naive-ui';
import TheNoticeBar from '/src/components/TheNoticeBar';
import styles from './index.module.less';
import { PageEnum } from '/src/enums/pageEnum';
import nodata from '../images/nomore.png';
import CardPreview from '/src/components/card-preview';
import { checkUrlType, iframeDislableKeyboard } from '/src/utils';
import { useUserStore } from '/src/store/modules/users';
import { vaildMusicScoreUrl } from '/src/utils/urlUtils';
import { saveAs } from 'file-saver';
import { modalClickMask } from '/src/state';

export default defineComponent({
  name: 'work-item',
  props: {
    item: {
      type: Object,
      default: () => ({})
    }
  },
  setup(props) {
    const userStore = useUserStore();
    const message = useMessage();
    const previewShow = ref(false);
    const preivewItem = ref({
      type: 'MUSIC',
      content: props.item.musicId,
      title: props.item.musicName,
      studentName: props.item.studentName
    });
    const reportSrc = ref('');
    const detailVisiable = ref(false);

    // 下载资源
    const onDownload = (src: any) => {
      if (!src) {
        message.error('下载失败');
        return;
      }
      const fileUrl = src;
      // props.item.studentName
      const title =
        props.item.musicName +
        (props.item.studentName ? '-' + props.item.studentName : '');
      const suffix = src.substring(src.lastIndexOf('.'));
      // 发起Fetch请求
      fetch(fileUrl)
        .then(response => response.blob())
        .then(blob => {
          saveAs(blob, (title || new Date().getTime() + '') + suffix);
        })
        .catch(() => {
          message.error('下载失败');
        });
    };
    return () => (
      <div
        class={[
          styles.workItem,
          (props.item.fileList?.expireFlag ||
            props.item.trainingStatus === 'UNSUBMITTED') &&
            styles['work-content-disabled']
        ]}>
        <div
          class={[styles['work-content']]}
          style={{
            cursor:
              props.item.trainingStatus === 'UNSUBMITTED'
                ? 'default'
                : 'pointer'
          }}>
          {/* ("文件类型：评测：EVALUATION，IMG:图片，SOUND:音频，VIDEO:视频")
        private String fileType; */}
          {!props.item.fileList?.fileType && (
            <NImage
              src={nodata}
              class={styles.nodata}
              previewDisabled
              objectFit="contain"
            />
          )}

          {props.item.fileList?.fileType === 'IMG' && (
            <NImage
              src={props.item.fileList?.filePath}
              objectFit="contain"
              renderToolbar={({ nodes }: ImageRenderToolbarProps) => {
                return [
                  nodes.prev,
                  nodes.next,
                  nodes.rotateCounterclockwise,
                  nodes.rotateClockwise,
                  nodes.resizeToOriginalSize,
                  nodes.zoomOut,
                  <div
                    class={'n-base-icon'}
                    onClick={() => onDownload(props.item.fileList?.filePath)}>
                    <svg
                      viewBox="0 0 16 16"
                      version="1.1"
                      xmlns="http://www.w3.org/2000/svg">
                      <g
                        stroke="none"
                        stroke-width="1"
                        fill="none"
                        fill-rule="evenodd">
                        <g fill="currentColor" fill-rule="nonzero">
                          <path d="M3.5,13 L12.5,13 C12.7761424,13 13,13.2238576 13,13.5 C13,13.7454599 12.8231248,13.9496084 12.5898756,13.9919443 L12.5,14 L3.5,14 C3.22385763,14 3,13.7761424 3,13.5 C3,13.2545401 3.17687516,13.0503916 3.41012437,13.0080557 L3.5,13 L12.5,13 L3.5,13 Z M7.91012437,1.00805567 L8,1 C8.24545989,1 8.44960837,1.17687516 8.49194433,1.41012437 L8.5,1.5 L8.5,10.292 L11.1819805,7.6109127 C11.3555469,7.43734635 11.6249713,7.4180612 11.8198394,7.55305725 L11.8890873,7.6109127 C12.0626536,7.78447906 12.0819388,8.05390346 11.9469427,8.2487716 L11.8890873,8.31801948 L8.35355339,11.8535534 C8.17998704,12.0271197 7.91056264,12.0464049 7.7156945,11.9114088 L7.64644661,11.8535534 L4.1109127,8.31801948 C3.91565056,8.12275734 3.91565056,7.80617485 4.1109127,7.6109127 C4.28447906,7.43734635 4.55390346,7.4180612 4.7487716,7.55305725 L4.81801948,7.6109127 L7.5,10.292 L7.5,1.5 C7.5,1.25454011 7.67687516,1.05039163 7.91012437,1.00805567 L8,1 L7.91012437,1.00805567 Z"></path>
                        </g>
                      </g>
                    </svg>
                  </div>,
                  nodes.close
                ];
              }}
            />
          )}
          {props.item.fileList?.fileType === 'SOUND' && (
            <div
              onClick={() => {
                preivewItem.value.content = props.item.fileList?.filePath;
                preivewItem.value.title = props.item.musicName;
                preivewItem.value.type = 'SONG';
                previewShow.value = true;
              }}>
              <NImage
                src={PageEnum.SONG_DEFAULT_COVER}
                previewDisabled
                objectFit="contain"
              />
            </div>
          )}
          {props.item.fileList?.fileType === 'EVALUATION' &&
            (checkUrlType(props.item.fileList?.content) === 'video' ? (
              <div
                class={styles.videoSection}
                onClick={() => {
                  preivewItem.value.content = props.item.fileList?.content;
                  preivewItem.value.title = props.item.musicName;
                  preivewItem.value.type = 'VIDEO';
                  previewShow.value = true;
                }}>
                <video
                  style={{ height: '100%' }}
                  src={props.item.fileList?.content}
                />
              </div>
            ) : (
              <div
                onClick={() => {
                  preivewItem.value.content = props.item.fileList?.content;
                  preivewItem.value.title = props.item.musicName;
                  preivewItem.value.type = 'SONG';
                  previewShow.value = true;
                }}>
                <NImage
                  src={PageEnum.SONG_DEFAULT_COVER}
                  previewDisabled
                  objectFit="contain"
                />
              </div>
            ))}
          {/* 'https://oss.dayaedu.com/ktqy/1715586967518b42c4fe5.mp4' */}
          {props.item.fileList?.fileType === 'VIDEO' && (
            <div
              class={styles.videoSection}
              onClick={() => {
                preivewItem.value.content = props.item.fileList?.filePath;
                preivewItem.value.title = props.item.musicName;
                preivewItem.value.type = 'VIDEO';
                previewShow.value = true;
              }}>
              <video
                style={{ height: '100%' }}
                src={props.item.fileList?.filePath}
              />
            </div>
          )}

          {/* 判断是否过期 */}
          {props.item.fileList?.expireFlag && (
            <div class={styles.expireBg}>文件已过期</div>
          )}

          {props.item.recordId && (
            <NButton
              color="rgba(0,0,0,0.4)"
              textColor="#fff"
              disabled={props.item.fileList?.expireFlag}
              class={styles.reportBtn}
              onClick={() => {
                if (!props.item.recordId) {
                  message.error('暂无评测记录');
                  return;
                }
                const tockn = userStore.getToken;
                reportSrc.value =
                  vaildMusicScoreUrl() +
                  `/instrument/#/evaluat-report?id=${props.item.recordId}&Authorization=${tockn}`;
                detailVisiable.value = true;
              }}>
              评测报告
            </NButton>
          )}
        </div>
        <div class={styles['work-footer']}>
          <div class={styles.trainInfo}>
            <div class={styles.trainName}>
              <span class={[styles.type, styles[props.item.trainingType]]}>
                {props.item.trainingType === 'EVALUATION' ? '评测' : '练习'}
              </span>
              <div class={styles['title-text']}>
                <TheNoticeBar text={props.item.musicName} />
              </div>
            </div>
            <div class={styles.tagList}>
              {props.item.typeList?.map((type: string, index: number) => (
                <>
                  <span>{type}</span>
                  {props.item.typeList.length - 1 > index && (
                    <NDivider vertical />
                  )}
                </>
              ))}
            </div>
          </div>

          {props.item.trainingType === 'EVALUATION' ? (
            <div class={[styles.scoreGroup, styles.scoreGroupEval]}>
              {props.item.trainingStatus !== 'UNSUBMITTED' ? (
                <>
                  {props.item.trainingTimes}
                  <span>分</span>
                </>
              ) : (
                <span class={styles.noSubmit}>未提交</span>
              )}
            </div>
          ) : (
            <div class={[styles.scoreGroup]}>
              {props.item.trainingStatus !== 'UNSUBMITTED' ? (
                <>
                  {props.item.trainingTimes
                    ? parseInt(props.item.trainingTimes / 60 + '')
                    : 0}
                  <span>分钟</span>
                </>
              ) : (
                <span class={styles.noSubmit}>未提交</span>
              )}
            </div>
          )}
        </div>

        <CardPreview
          v-model:show={previewShow.value}
          item={preivewItem.value}
        />

        <NModal
          maskClosable={modalClickMask}
          v-model:show={detailVisiable.value}
          preset="card"
          class={['modalTitle background', styles.reportModel]}
          title={'评测报告'}>
          <div class={styles.reportContainer} style={{ lineHeight: 0 }}>
            <iframe
              width={'100%'}
              height={'450px'}
              frameborder="0"
              onLoad={(val: any) => {
                iframeDislableKeyboard(val.target);
              }}
              src={reportSrc.value}></iframe>
          </div>
        </NModal>
      </div>
    );
  }
});
