import { PropType, computed, defineComponent, ref } from 'vue';
import styles from './index.module.less';
import {
  NButton,
  NEllipsis,
  NSpace,
  NImage,
  NTag,
  NModal,
  NProgress,
  NTooltip,
  useMessage,
  NDivider
} from 'naive-ui';
import iconDelete from '@/views/prepare-lessons/images/icon-delete-default.png';
import iconEdit from './images/icon-edit.png';
// import iconDelete from './images/icon-delete2.png';
import iconBackLook from './images/icon-back-look.png';
import iconReport from './images/icon-report.png';
import { useUserStore } from '/src/store/modules/users';
import CardPreview from '/src/components/card-preview';
import { vaildMusicScoreUrl, vaildUrl } from '/src/utils/urlUtils';
import { musicPracticeRecordDetail } from '/src/views/prepare-lessons/api';
import { checkUrlType, iframeDislableKeyboard } from '/src/utils';
import TheNoticeBar from '/src/components/TheNoticeBar';
import { modalClickMask } from '/src/state';
type ItemType = {
  id: string | number;
  trainingType: 'PRACTICE' | 'EVALUATION';
  musicId: string | number;
  coverImg: string;
  musicName: string;
  typeList: string[];
  audioPlayTypeArray?: string[];
  allTimes?: number;
  trainingTimes?: number;
  recordId?: string | number; // 评测记录编号
};

export default defineComponent({
  name: 'train-type',
  props: {
    type: {
      type: String as PropType<'prepare' | 'homework'>,
      default: 'homework'
    },
    item: {
      type: Object as PropType<ItemType>,
      default: () => ({})
    },
    isDelete: {
      type: Boolean,
      default: false
    },
    isDisabled: {
      type: Boolean,
      default: false
    },
    isLarge: {
      type: Boolean,
      default: false
    },
    /** 是否下架 */
    offShelf: {
      type: Boolean,
      default: false
    },
    isCLassWork: {
      type: Boolean,
      default: false
    },
    from: {
      type: String,
      default: ''
    }
  },
  emits: ['click', 'delete', 'edit', 'offShelf'],
  setup(props, { emit }) {
    const userStore = useUserStore();
    const message = useMessage();
    const removeVisiable = ref(false);
    const previewShow = ref(false);
    const preivewItem = ref({
      type: 'MUSIC',
      content: props.item.musicId,
      title: props.item.musicName
    });
    const onDetail = () => {
      // const origin = /(localhost|192)/.test(location.host)
      //   ? 'https://dev.kt.colexiu.com'
      //   : location.origin;
      // const src = `${origin}/instrument?platform=pc&modelType=practise&id=${props.item.musicId}&Authorization=${userStore.getToken}`;
      // window.open(src, '_blank');
      // console.log(props.item, 'item');
      // console.log(props.item, '1212');
      preivewItem.value = {
        type: 'MUSIC',
        content: props.item.musicId,
        title: props.item.musicName
      };
      previewShow.value = true;
    };

    const reportSrc = ref('');
    const detailVisiable = ref(false);
    const gotoRecode = (row: any) => {
      if (!row.id) {
        message.error('暂无评测记录');
        return;
      }
      const tockn = userStore.getToken;
      reportSrc.value =
        vaildMusicScoreUrl() +
        `/instrument/#/evaluat-report?id=${row.id}&Authorization=${tockn}`;
      detailVisiable.value = true;
    };

    const onBackLook = async () => {
      try {
        if (!props.item?.recordId) {
          message.error('暂无数据');
          return;
        }
        const { data } = await musicPracticeRecordDetail({
          id: props.item.recordId
        });
        if (data.videoFilePath || data.recordFilePath) {
          let lookTitle = '';
          if (data.videoFilePath) {
            lookTitle = checkUrlType(data.videoFilePath);
          } else {
            lookTitle = checkUrlType(data.recordFilePath);
          }
          const lookUrl = data.videoFilePath || data.recordFilePath;
          preivewItem.value.content = lookUrl;
          preivewItem.value.title = props.item.musicName;
          if (lookTitle === 'video') {
            preivewItem.value.type = 'VIDEO';
          } else if (lookTitle === 'audio') {
            preivewItem.value.type = 'SONG';
          }
          previewShow.value = true;
        } else {
          message.error('暂无数据');
        }
      } catch {
        //
      }
    };

    const isPass = computed(() => {
      const item = props.item;
      if (item) {
        if (item.trainingType === 'EVALUATION') {
          return (item.trainingTimes || 0) >= (item.allTimes || 0)
            ? true
            : false;
        } else {
          return (item.trainingTimes
            ? parseInt(item.trainingTimes / 60 + '')
            : 0) >= (item.allTimes || 0)
            ? true
            : false;
        }
      } else {
        return false;
      }
    });

    const isDownload = computed(() => {
      if (
        props.isDisabled &&
        !props.isCLassWork &&
        props.item.trainingType === 'EVALUATION'
      ) {
        return true;
      } else {
        return false;
      }
    });

    return () => (
      <div
        class={[
          styles.trainType,
          props.item.trainingType === 'EVALUATION' ? styles.evaluationType : ''
        ]}
        onClick={() => emit('click', props.item)}>
        <div
          class={[
            styles['train-content'],
            props.isDisabled && !props.isCLassWork && styles.trainDisabled,
            props.isLarge && styles.trainDisabled
          ]}
          onClick={() => {
            if (props.isDisabled && !props.isCLassWork) {
              return;
            }
            onDetail();
          }}>
          <NImage
            src={props.item.coverImg}
            previewDisabled
            objectFit="contain"
          />
          <NSpace class={styles.audioPlayTypeSection}>
            {props.item.audioPlayTypeArray?.includes('SING') && (
              <NTooltip trigger="hover" showArrow={false}>
                {{
                  trigger: () => (
                    <span class={[styles.iconType, styles.iconSing]}></span>
                  ),
                  default: '演唱场景'
                }}
              </NTooltip>
            )}
            {props.item.audioPlayTypeArray?.includes('PLAY') && (
              <NTooltip trigger="hover" showArrow={false}>
                {{
                  trigger: () => (
                    <span class={[styles.iconType, styles.iconPlay]}></span>
                  ),
                  default: '演奏场景'
                }}
              </NTooltip>
            )}
          </NSpace>
          {props.isDisabled && !props.isCLassWork ? (
            <div class={styles.disPreview}>
              <NProgress
                percentage={
                  props.item.trainingType === 'EVALUATION'
                    ? (Number(props.item.trainingTimes) /
                        Number(props.item.allTimes)) *
                      100
                    : (Number(props.item.trainingTimes) /
                        60 /
                        Number(props.item.allTimes)) *
                      100
                }
                offset-degree={180}
                type="circle"
                rail-color={'8b8b8b'}
                color={isPass.value ? '#6CFFC1' : '#FF7794'}
                style="width: 120px; margin: 0  0 10px;">
                <div class={styles.BProgress}>
                  {props.item.trainingType === 'EVALUATION' ? (
                    <h4>
                      {props.item.trainingTimes}

                      <span>分</span>
                    </h4>
                  ) : (
                    <h4>
                      {props.item.trainingTimes
                        ? parseInt(props.item.trainingTimes / 60 + '')
                        : 0}
                      <span>分钟</span>
                    </h4>
                  )}

                  <p>
                    {props.item.trainingType === 'EVALUATION'
                      ? '学生分数'
                      : '实际练习'}{' '}
                  </p>
                </div>
              </NProgress>
              <p class={styles.disPreviewDivide}>
                {props.item.trainingType === 'EVALUATION'
                  ? '达标分数'
                  : '练习时长要求'}
                {props.item.allTimes}
                {props.item.trainingType === 'EVALUATION' ? '分' : '分钟'}
              </p>
            </div>
          ) : null}

          {/* <div class={styles.preview} onClick={onDetail}>
              <NButton strong secondary class={styles.previewBtn}>
                预览
              </NButton>
            </div> */}
          {props.isDelete && (
            <img
              src={iconDelete}
              class={styles.iconDelete}
              onClick={(e: MouseEvent) => {
                e.stopPropagation();
                emit('delete', props.item);
              }}
            />
          )}
        </div>
        <div class={styles['train-footer']}>
          <div class={styles.trainInfo}>
            <div class={styles.trainName}>
              <span class={[styles.type, styles[props.item.trainingType]]}>
                {props.item.trainingType === 'EVALUATION' ? '评测' : '练习'}
              </span>
              {/* <NEllipsis tooltip={false}>{props.item.musicName}</NEllipsis> */}
              <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.isDisabled ? null : (
            <NSpace size={12}>
              <n-button
                quaternary
                disabled={!props.isDelete}
                class={styles.operation}
                onClick={(e: MouseEvent) => {
                  e.stopPropagation();
                  emit('edit', props.item);
                }}>
                <NTooltip showArrow={false}>
                  {{
                    trigger: () => <i class={styles.iconEdit}></i>,
                    // <img src={iconEdit} />
                    default: '编辑'
                  }}
                </NTooltip>
              </n-button>
              {/* <n-button
                quaternary
                disabled={!props.isDelete}
                class={styles.operation}
                onClick={(e: MouseEvent) => {
                  e.stopPropagation();
                  // onDelete();
                  // removeVisiable.value = true;
                  emit('delete', props.item);
                }}>
                <NTooltip showArrow={false}>
                  {{
                    trigger: () => <img src={iconDelete} />,
                    default: '删除'
                  }}
                </NTooltip>
              </n-button> */}
            </NSpace>
          )}

          {/* 只有评测的时候才有 */}
          {props.isDisabled &&
          !props.isCLassWork &&
          props.item.trainingType === 'EVALUATION' &&
          props.item?.recordId ? (
            <>
              <NSpace size={12}>
                <n-button
                  quaternary
                  disabled={props.isDelete}
                  class={styles.operation}
                  onClick={(e: MouseEvent) => {
                    e.stopPropagation();
                    gotoRecode({ id: props.item.recordId });
                  }}>
                  <NTooltip showArrow={false}>
                    {{
                      trigger: () => <img src={iconReport} />,
                      default: '评测报告'
                    }}
                  </NTooltip>
                </n-button>
                <n-button
                  quaternary
                  disabled={props.isDelete}
                  class={styles.operation}
                  onClick={(e: MouseEvent) => {
                    e.stopPropagation();
                    // onDetail();
                    // musicPracticeRecordId;
                    onBackLook();
                  }}>
                  <NTooltip showArrow={false}>
                    {{
                      trigger: () => <img src={iconBackLook} />,
                      default: '查看回放'
                    }}
                  </NTooltip>
                </n-button>
              </NSpace>
            </>
          ) : (
            ''
          )}
        </div>

        {/* 判断是否下架 */}
        {props.offShelf && (
          <div class={styles.offShelfBg}>
            <p class={styles.offShelfTips}>该资源已被下架</p>
            <NButton
              type="primary"
              class={styles.offShelfBtn}
              onClick={() => emit('offShelf')}>
              确认
            </NButton>
          </div>
        )}

        <NModal
          maskClosable={modalClickMask}
          v-model:show={removeVisiable.value}
          preset="card"
          class={['modalTitle', styles.removeVisiable]}
          title={'提示'}>
          <div class={styles.studentRemove}>
            <p>您确定是否删除？</p>

            <NSpace class={styles.btnGroupModal} justify="center">
              <NButton
                round
                type="primary"
                onClick={() => {
                  removeVisiable.value = false;
                  emit('delete', props.item);
                }}>
                确定
              </NButton>
              <NButton round onClick={() => (removeVisiable.value = false)}>
                取消
              </NButton>
            </NSpace>
          </div>
        </NModal>

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

        <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>
    );
  }
});
