import {
  NButton,
  NSpace,
  useMessage,
  NForm,
  NFormItem,
  NSelect,
  NImage
} from 'naive-ui';
import { defineComponent, onMounted, reactive, ref } from 'vue';
import styles from '../components/schoolInfo/index.module.less';
import CSelect from '/src/components/CSelect';
import stunentStart from '@/views/studentList/images/studentStart.png';
import studentCLose from '@/views/studentList/images/studentClose.png';
import { useUserStore } from '@/store/modules/users';
import TheQrCode from '/src/components/TheQrCode';
import { vaildUrl } from '@/utils/urlUtils';
import logo from '@/common/images/logo.png';
import studentTitle from '../images/studentTitle.png';
import studentInfo from '@/views/studentList/images/teacherCore.png';
import codewrap from '@/views/studentList/images/cordWrap.png'
import btnBg from '@/views/studentList/images/btnBg.png';
import html2canvas from 'html2canvas';

export default defineComponent({
  props: {
    activeRow: {
      type: Object,
      default: () => ({ id: '' })
    },
    gradeNumList: {
      type: Array,
      default: () => []
    },
    classArray: {
      type: Array,
      default: () => []
    }
  },
  name: 'resetStudent',
  emits: ['close', 'getList'],
  setup(props, { emit }) {
    const data = reactive({
      uploading: false
    });
    const message = useMessage();
    const userStore = useUserStore();
    const foemsRef = ref();
    const registerUrl = () => {
      const queryStr = `tenantId=${userStore.info.schoolInfos?.[0]?.tenantId}&schoolId=${userStore.info.schoolInfos?.[0]?.id}&schoolName=${userStore.info.schoolInfos?.[0]?.name}`;
      const url =
        `${location.origin}/classroom-app/#/teaher-register?` + queryStr;

      return url;
    };

    const queryStr = `tenantId=${userStore.info.schoolInfos?.[0]?.tenantId}&schoolId=${userStore.info.schoolInfos?.[0]?.id}&schoolName=${userStore.info.schoolInfos?.[0]?.name}`;
    const url =
      `${location.origin}/classroom-app/#/teaher-register?` + queryStr;
    const imgs = reactive({
      saveLoading: false,
      image: null as any,
      shareLoading: false
    });
    const downImg = () => {
      if (imgs.saveLoading) {
        return;
      }
      imgs.saveLoading = true;
      // 判断是否已经生成图片
      if (imgs.image) {
        saveImg();
      } else {
        const container: any = document.getElementById(`preview-container`);

        html2canvas(container, {
          allowTaint: true,
          useCORS: true,
          backgroundColor: null
        })
          .then(async canvas => {
            const url = canvas.toDataURL('image/png');
            console.log(url, 'url===>')
            imgs.image = url;

            saveImg();
          })
          .catch(() => {
            console.log('生成图片失败url===>')
            imgs.saveLoading = false;
          });
      }
    };

    const saveImg = async () => {
      // showLoadingToast({ message: '图片生成中...', forbidClick: true });
      setTimeout(() => {
        imgs.saveLoading = false;
      }, 100);
      const link = document.createElement('a');
      link.setAttribute('download', '新增老师' + '.png');
      // 添加时间戳，防止浏览器缓存图片
      // console.log(imgUrl,'imgUrl')

      link.href = imgs.image;
      link.click();
      // const res = await promisefiyPostMessage({
      //   api: 'savePicture',
      //   content: {
      //     base64: imgs.image
      //   }
      // });
      // if (res?.content?.status === 'success') {
      //   showSuccessToast('保存成功');
      // } else {
      //   showFailToast('保存失败');
      // }
    };
    return () => (
      <div class={[styles.addStudentWrap]}>
        <div
          onClick={() => {
            console.log('点击');
            emit('close');
          }}>
          <NImage
            src={studentCLose}
            previewDisabled
            class={styles.studentCLose}></NImage>
        </div>
        <NImage
          previewDisabled
          class={styles.stunentStart}
          src={stunentStart}></NImage>
        <NImage
          class={styles.addTitle}
          previewDisabled
          src={studentTitle}></NImage>
        <div class={styles.addStudentInfo} id="preview-container">

          <NImage
            class={styles.studentInfoBg}
            previewDisabled
            src={studentInfo}></NImage>

          <div class={styles.studentCore}>
            <img
              alt="img"
              crossorigin="anonymous"
              class={styles.schoolLogo}
              src={
                userStore.getUserInfo.schoolInfos[0].logo +
                `?some=${new Date().getTime()}`
              }></img>
            <div class={styles.studentCoreInfo}>
              <h2>{userStore.getUserInfo.schoolInfos[0].name}</h2>
              <p class={styles.studentCoreInfoSubtitle}>
                邀请您的成为
                <span>音乐数字课堂老师</span>
              </p>
              <div class={styles.codewrap}>
                {/* <img src={codewrap} class={styles.codewrapBg} alt="" /> */}
                <TheQrCode margin={0} text={url} size={119} />
              </div>
              <div class={styles.codewrapSubmit}>
                <NImage previewDisabled src={btnBg}></NImage>
                请扫描上方二维码 <span>完成注册</span>{' '}
              </div>
            </div>
          </div>
        </div>
        <div class={styles.studentBottom}>
          <p>请将二维码图片发送给老师，扫码完成注册</p>
          <div class={styles.downBtn} onClick={downImg}>
            下载图片
          </div>
        </div>
      </div>
    );
  }
});
