<template>
  <div v-show="showLogin" class="share-exercise">
    <div class="login">
      <div class="title">登录后开始{{ isEditLink ? '编辑' : '答题' }}</div>
      <div class="login-type">
        <div :class="['login-type-item', { active: 'TEACHER' === form.user_type }]" @click="form.user_type = 'TEACHER'">
          我是教师
        </div>
        <div
          v-if="!isEditLink"
          :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" placeholder="邮箱地址">
            <SvgIcon slot="prefix" size="24" icon-class="email" />
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="form.password" type="password" show-password>
            <SvgIcon slot="prefix" size="24" icon-class="key" />
          </el-input>
        </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 class="remember">
          <el-checkbox v-model="is_remember">记住我</el-checkbox>
          <span class="forgot-password">忘记密码？</span>
        </el-form-item>
        <el-form-item>
          <el-button class="submit" type="primary" @click="signIn">登录</el-button>
        </el-form-item>
        <el-form-item class="user-agreement">
          <el-checkbox v-model="is_agreement">我已阅读并同意</el-checkbox>
          <span class="link">本用户协议</span>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { GetShareRecordInfo, StartEdit } from '@/api/exercise';
import md5 from 'md5';
import { GetVerificationCodeImage, GetLogo, ParseAccessToken } 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: '',
      },
      // 用户编辑记录信息
      user_edit_record_info: {
        is_exist_edit_record: 'false', // 是否存在编辑记录
        edit_record_id: '', // 编辑记录id
      },
      showLogin: false,
      is_remember: false, // 记住我
      is_agreement: true, // 用户协议
      // 登录表单
      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: {
    // 是否编辑链接
    isEditLink() {
      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, user_edit_record_info }) => {
          this.share_record = share_record;
          this.user_edit_record_info = user_edit_record_info;
          if (this.share_record.access_popedom === 1) {
            this.form.user_type = 'TEACHER';
          }
        })
        .then(() => {
          ParseAccessToken({ access_token: this.$store.state.user.access_token })
            .then(({ is_effective }) => {
              if (is_effective === 'true') {
                this.exerciseLink();
              } else {
                this.updateVerificationCode();
                this.getLogo();
                this.showLogin = true;
              }
            })
            .catch(() => {});
        })
        .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) {
        StartEdit({ share_record_id: this.share_record_id })
          .then(() => {
            this.$router.push({
              path: '/exercise',
              query: { id: this.share_record.exercise_id, back_url: '/collaborate_question' },
            });
          })
          .catch(() => {});
      }
      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;
      });
    },

    // 获取logo
    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>
$basic-color: #f90;

.share-exercise {
  width: 100%;
  height: 100%;
  padding-top: 5%;
  background-color: $content-color;

  .login {
    width: 465px;
    padding: 48px 64px;
    margin: auto;
    background-color: #fff;
    border: $border;
    border-radius: 4px;

    .title {
      margin-bottom: 32px;
      font-size: 20px;
      color: $basic-color;
      text-align: center;
    }

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

      &-item {
        flex: 1;
        height: 36px;
        line-height: 36px;
        color: #a6a6a6;
        text-align: center;
        cursor: pointer;

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

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

      &-item--small.el-form-item {
        margin-bottom: 24px;
      }

      .el-checkbox__input.is-checked {
        + .el-checkbox__label {
          color: #2c2c2c;
        }

        .el-checkbox__inner {
          background-color: #fff;
          border-color: #2c2c2c;

          &::after {
            color: #2c2c2c;
            border-color: #2c2c2c;
          }
        }
      }

      .el-input {
        &__inner {
          height: 48px;
          padding-left: 60px;
          font-size: 16px;
          line-height: 48px;
          background-color: #fff !important;
        }

        &__prefix {
          display: flex;
          align-items: center;
          justify-content: center;
          padding: 0 16px;
        }
      }

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

          &__inner {
            padding-left: 15px;
            background-color: #fff;
          }
        }

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

      .remember {
        .el-form-item__content {
          display: flex;
          align-items: center;
          justify-content: space-between;
          font-size: 16px;

          .forgot-password {
            font-weight: bold;
            color: $basic-color;
          }

          &::before,
          &::after {
            display: none;
          }
        }
      }

      .user-agreement {
        margin-bottom: 0;

        .el-checkbox__label {
          font-size: 16px;
        }

        .link {
          font-size: 16px;
          color: $basic-color;
        }
      }

      .submit {
        width: 100%;
        height: 48px;
        background-color: $basic-color;
        border-color: $basic-color;
      }
    }
  }
}
</style>
