<template>
  <div v-show="showLogin" class="share-exercise">
    <div class="login">
      <div class="login-type">
        <div :class="['login-type-item', { active: 'TEACHER' === form.user_type }]" @click="form.user_type = 'TEACHER'">
          教师
        </div>
        <div :class="['login-type-item', { active: 'STUDENT' === form.user_type }]" @click="form.user_type = 'STUDENT'">
          学生
        </div>
      </div>
      <el-form ref="loginForm" :model="form" :rules="rules" label-position="right">
        <el-form-item prop="user_name">
          <el-input v-model="form.user_name" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="form.password" type="password" show-password />
        </el-form-item>
        <el-form-item prop="verification_code_image_text" class="verification-code">
          <el-input v-model="form.verification_code_image_text" placeholder="验证码" @keyup.enter.native="signIn" />
          <el-image
            v-if="image_content_base64.length > 0"
            :src="`data:image/jpg;base64,${image_content_base64}`"
            @click="updateVerificationCode"
          />
        </el-form-item>
        <el-form-item>
          <el-button class="submit" type="primary" @click="signIn">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="tip">{{ tip }}</div>
  </div>
</template>

<script>
import { GetShareRecordInfo, PageQueryExerciseList } from '@/api/exercise';
import md5 from 'md5';
import { GetVerificationCodeImage, GetLogo } from '@/api/app';
import { setConfig } from '@/utils/auth';

export default {
  name: 'ShareExercise',

  data() {
    const { query } = this.$route;
    const { share_record_id } = query;

    return {
      query,
      share_record_id,
      share_record: {
        access_popedom: -1,
        exercise_id: '',
      },
      showLogin: false,
      // 登录表单
      form: {
        user_type: 'STUDENT',
        user_name: '',
        password: '',
        is_password_md5: 'true',
        verification_code_image_id: '',
        verification_code_image_text: '',
      },
      rules: {
        user_name: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur',
          },
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur',
          },
        ],
        verification_code_image_text: [{ required: true, trigger: 'blur', message: '验证码不能为空' }],
      },
      image_content_base64: '',
    };
  },
  computed: {
    tip() {
      if (this.share_record.access_popedom === -1) return '正在加载...';
      return this.share_record.access_popedom === 1
        ? '分享链接为练习题答题链接，登录后可以开始答题'
        : '分享链接为练习题编辑链接，登录后可以开始编辑练习题';
    },
  },
  created() {
    let info = navigator.userAgent;
    // 通过正则表达式的test方法判断是否包含“Mobile”字符串
    let isPhone = /mobile|iPad/i.test(info);
    // 如果包含“Mobile”（是手机设备）则返回true
    if (isPhone) {
      window.location.href = `${window.location.origin}/GCLS-Mobile/#/open/share/exercise?share_record_id=${this.share_record_id}`;
    } else {
      this.getShareRecordInfo();
    }
  },
  methods: {
    getShareRecordInfo() {
      GetShareRecordInfo({
        share_record_id: this.share_record_id,
      })
        .then(({ share_record }) => {
          this.share_record = share_record;
        })
        .then(() => {
          PageQueryExerciseList({ page_capacity: 0, cur_page: 1, store_type: 0, search_content: '' })
            .then(() => {
              this.exerciseLink();
            })
            .catch(() => {
              this.updateVerificationCode();
              this.getLogo();
              this.showLogin = true;
            });
        })
        .catch(() => {});
    },

    exerciseLink() {
      // 1. 教师在没有权限的情况下，不能访问编辑练习题
      // 2. 学生不能访问编辑练习题
      if (
        (!this.$store.state.user.popedom_code_list.includes(2000007) &&
          this.form.user_type === 'TEACHER' &&
          this.share_record.access_popedom === 1) ||
        (this.form.user_type === 'STUDENT' && this.share_record.access_popedom === 1)
      ) {
        this.$message.error('您没有权限访问该页面');
        return;
      }
      if (this.share_record.access_popedom === 1) {
        this.$router.push({ path: '/exercise', query: { id: this.share_record.exercise_id } });
      }
      if (this.share_record.access_popedom === 2) {
        this.$router.push({
          path: '/answer',
          query: this.query,
        });
      }
    },

    updateVerificationCode() {
      GetVerificationCodeImage().then(({ image_id, image_content_base64: image }) => {
        this.form.verification_code_image_id = image_id;
        this.image_content_base64 = image;
      });
    },

    getLogo() {
      GetLogo().then((res) => {
        setConfig(res);
      });
    },

    signIn() {
      this.$refs.loginForm.validate((valid) => {
        if (!valid) return false;

        let _form = { ...this.form, password: md5(this.form.password).toUpperCase() };
        this.$store
          .dispatch('user/login', _form)
          .then(() => {
            this.exerciseLink();
          })
          .catch(() => {
            this.updateVerificationCode();
          });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.share-exercise {
  width: 100%;
  height: 100%;
  padding-top: 20%;
  background-color: $content-color;

  .login {
    width: 50vw;
    max-width: 1200px;
    padding: 24px;
    margin: auto;
    background-color: #f0f0f0;
    border: $border;
    border-radius: 4px;

    &-type {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 400px;
      padding: 2px;
      margin: 0 auto;
      margin-bottom: 12px;
      background-color: #fafafa;
      border-radius: 4px;

      &-item {
        width: 200px;
        height: 36px;
        line-height: 36px;
        color: $text-color;
        text-align: center;
        cursor: pointer;

        &.active {
          color: $main-color;
          background-color: $fill-color;
          border-radius: 4px;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 10%);
        }
      }
    }

    :deep(.el-form) {
      max-width: 400px;
      margin: 0 auto;

      .verification-code {
        .el-input {
          width: calc(100% - 90px);
          margin-right: 10px;

          &__inner {
            background-color: #fff;
          }
        }

        .el-image {
          height: 30px;
          vertical-align: bottom;
          cursor: pointer;
        }
      }

      .submit {
        width: 100%;
      }
    }
  }

  .tip {
    width: 100%;
    padding: 8px 0;
    margin-top: 40px;
    text-align: center;
    background-color: #fff;
    border-top: $border;
    border-bottom: $border;
  }
}
</style>
