<script setup lang="ts">
import Option from './components/Option.vue'
import { XMessage, useBindQrCode } from '@/hooks'
import { useRouter } from 'vue-router'
import { userStore } from '@/stores'
import { storeToRefs } from 'pinia'
import { setCache, getCache, delCache } from '@/utils'
import { isShufaAccount, SHUFA_PATH } from '@/page/app/app.ts'
import { getSubjectsByGrade } from '../../api/subject/config'
import sass from '@/utils/sass'
import globalApi from '@/api/global'
import userApi from '@/api/system/user'

const OSS_URL = import.meta.env.VITE_OSS_URL
const bg = `url(${OSS_URL}/urm/bg_login.svg) 100%/cover no-repeat`
const logo = sass.getLogo()
const ipGirl = `${OSS_URL}/urm/ip_girl.png`

const bindBg = `url(${OSS_URL}/urm/init_bind_bg.svg) 100%/cover no-repeat`
const qr = sass.getQrCode()

const router = useRouter()
const { userInfo } = storeToRefs(userStore())
const step = ref(getCache('init_step') ? Number(getCache('init_step')) : 0) // 当前步骤
const nextLoading = ref(false)

const { bindQrCode, loadingQrCode, initQrCode } = useBindQrCode()
const grade = ref(getCache('init_grade') || '147') // 学习阶段
const gradeData = ref<anyObj[]>([])
const gradeLoading = ref(false)

async function initGrade() {
  gradeLoading.value = true
  try {
    const {
      data: { data: res },
    } = await globalApi.getGradeList({
      size: -1,
    })
    gradeData.value = res.rows.map((i: anyObj) => ({
      id: i.id,
      name: i.name,
    }))
  } finally {
    gradeLoading.value = false
  }
}

function onChange(type: boolean, data: anyObj) {
  if (!type) {
    grade.value = data.id
  }
}

const subject = computed(() => subjectData.value.filter(i => i.select).map(i => i.id)) // 科目
const subjectData = ref<anyObj[]>([])
const subjectLoading = ref(false)

async function initSubject() {
  if (!grade.value) return
  subjectLoading.value = true
  try {
    const data = getSubjectsByGrade(grade.value)
    subjectData.value = data.map((i: anyObj) => ({
      id: i.subjectId,
      name: i.name,
      subject: i.subject,
      select: false,
    }))
  } finally {
    subjectLoading.value = false
  }
}

// 下一步
async function onNext(_step: number) {
  try {
    // 用户已经初始化，只展示绑定学习机
    // if (userInfo.value.weakSubjectIds) {
    //     await router.push('/');
    //     return;
    // }
    if (_step === 1) {
      nextLoading.value = true
      await initGrade()
      step.value += 1
      nextLoading.value = false
    }
    if (_step === 2) {
      if (!grade.value) {
        XMessage.error('请选择学习阶段')
        return
      }
      nextLoading.value = true
      await initSubject()
      step.value += 1
      nextLoading.value = false
      setCache('init_grade', grade.value)
    }
    if (_step === 3) {
      if (!subject.value.length) {
        XMessage.error('请选择薄弱科目')
        return
      }
      nextLoading.value = true
      await userApi.updateUserLearn({
        learnGradeId: grade.value,
        weakSubjectIds: subject.value.join(','),
      })
      userInfo.value.learnGradeId = grade.value
      userInfo.value.weakSubjectIds = subject.value.join(',')
      if (isShufaAccount(userInfo.value.account)) {
        await router.push(SHUFA_PATH)
      } else {
        await router.push('/')
      }
      delCache('init_step')
      delCache('init_grade')
    }
  } finally {
    nextLoading.value = false
  }
}

watch(step, newVal => {
  setCache('init_step', newVal)
})

onMounted(() => {
  initQrCode()
  if (step.value === 2) {
    initGrade()
  }
  if (step.value === 3) {
    initSubject()
  }
})
</script>

<template>
  <div
    class="page"
    :style="{
      background: bg,
    }"
  >
    <div v-if="step === 0" class="step0" @click="step += 1">
      <img class="logo" :src="logo" />
      <img class="ip" :src="ipGirl" />
      <div class="welcome">
        <LineFont text="小乐" size="40" color="#FFF01F" />
        <LineFont :text="`欢迎进入${sass.platform.appName}！`" size="32" />
      </div>
    </div>
    <div v-if="step === 1" class="step1">
      <div class="main">
        <div class="title">
          <LineFont text="绑定学习机" size="72" offset="0" />
        </div>
        <div class="content">
          <Icon name="double_arrow_right" size="160" />
          <div class="box">
            <div class="box-content">
              <span class="box-content-title">1、关注公众号</span>
              <span class="box-content-info">用手机微信扫下方二维码并关注公众号</span>
              <div class="qr-border">
                <div>
                  <img :src="qr" />
                </div>
              </div>
            </div>
          </div>
          <div class="box">
            <div class="box-content">
              <span class="box-content-title">2、绑定学习机</span>
              <span class="box-content-info">进入公众号，点击【家长助手】扫码绑定设备</span>
              <div class="qr-border">
                <div v-loading="loadingQrCode">
                  <img v-if="bindQrCode" :src="bindQrCode" />
                </div>
              </div>
            </div>
          </div>
          <div class="tip">*请关注公众号并绑定学习机，否则影响功能正常使用</div>
        </div>
        <mj-button
          type="warn"
          :loading="nextLoading"
          width="584"
          height="108"
          size="48"
          @click="onNext(1)"
          >扫好了，下一步
          <Icon class="btn-icon" name="more_arrow_right" size="56" />
        </mj-button>
      </div>
    </div>
    <div v-if="step === 2" class="step2">
      <div class="title">
        <LineFont text="请选择学习阶段" size="72" />
      </div>
      <div class="tip">在线课堂将根据您的所在年级，推荐定制化内容</div>
      <div class="list">
        <Icon v-if="gradeLoading" name="global_loading" loading size="96" />
        <template v-else>
          <Option
            v-for="item in gradeData"
            :key="item.id"
            :selected="grade === item.id"
            :data="item"
            @change="onChange"
            >{{ item.name }}
          </Option>
        </template>
      </div>
      <mj-button
        type="warn"
        :loading="nextLoading"
        width="584"
        height="108"
        size="48"
        @click="onNext(2)"
        >下一步
        <Icon class="btn-icon" name="more_arrow_right" size="56" />
      </mj-button>
    </div>
    <el-scrollbar v-if="step === 3">
      <div class="step3">
        <div class="title">
          <LineFont text="请选择薄弱科目" size="72" />
        </div>
        <div class="list">
          <Icon v-if="subjectLoading" name="global_loading" loading size="96" />
          <template v-else>
            <Option v-for="item in subjectData" :key="item.id" v-model:selected="item.select"
              >{{ item.name }}
            </Option>
          </template>
        </div>
        <mj-button
          type="warn"
          :loading="nextLoading"
          width="584"
          height="108"
          size="48"
          @click="onNext(3)"
          >开始智学新旅程
          <Icon class="btn-icon" name="more_arrow_right" size="56" />
        </mj-button>
      </div>
    </el-scrollbar>
  </div>
</template>

<style lang="scss" scoped>
.page {
  width: 100%;
  height: 100%;
  padding: $space-2_h $space-6;

  .step0 {
    height: 100%;
    position: relative;

    .logo {
      position: absolute;
      width: 13.33vh;
      height: 13.33vh;
      top: 0;
      left: 0;
      border-radius: 50%;
      border: 0.33vh solid #fff;
      box-shadow: 0 0.33vh 0.17vh 0 #00000040;
    }

    .ip {
      position: absolute;
      top: 16.67vh;
      left: 50%;
      transform: translateX(-50%);
      width: 83.33vh;
      height: 104.17vh;
    }

    .welcome {
      position: fixed;
      left: 0;
      bottom: 0;
      width: 100%;
      height: 26.67vh;
      padding: 3.33vh 240px;
      background: linear-gradient(180deg, rgba(0, 0, 0, 0.65) 0%, rgba(0, 0, 0, 0.45) 100%);

      .x-line-font {
        display: flex;
        margin-bottom: $space-2_h;
      }
    }
  }

  .step1 {
    .main {
      display: flex;
      flex-wrap: wrap;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      margin-top: $space-70;
      row-gap: 2vh;

      .title {
        width: 100%;
        text-align: center;
        display: flex;
        justify-content: center;
      }

      .content {
        width: 105vh;
        height: 61.67vh;
        background: v-bind(bindBg);
        display: flex;
        flex-wrap: wrap;
        position: relative;

        .x-icon {
          position: absolute;
          top: 25vh;
          left: 50%;
          transform: translateX(-50%);
        }

        .box {
          width: 50%;
          height: 31vh;
          margin-top: 10vh;
          display: flex;
          align-items: center;
          justify-content: center;

          &-content {
            width: 264px;
            text-align: center;
            display: flex;
            flex-wrap: wrap;
            justify-content: center;

            &-title {
              display: inline-block;
              font-family: $font-special;
              font-size: $font-size-7;
              line-height: 1.5em;
            }

            &-info {
              margin: $space-1_h 0;
              display: inline-block;
              color: $font-tag-color;
              font-size: $font-size-3;
              line-height: 1.5em;
            }
          }
        }

        .tip {
          position: absolute;
          bottom: 10vh;
          left: 50%;
          transform: translateX(-50%);
          color: #41b0ab;
          text-align: center;
          font-size: $font-size-3;
          line-height: 1.5em;
        }
      }

      .btn-icon {
        margin-left: $space-3;
      }
    }

    .qr-border {
      --w: 228px;
      width: var(--w);
      height: var(--w);
      position: relative;

      &::after {
        content: '';
        display: block;
        width: var(--w);
        height: var(--w);
        border: 0.33vh solid transparent; // 边框设置为透明
        border-radius: $radius-5;
        @include gradient(
          linear-gradient(180deg, #fff, #fff),
          linear-gradient(180deg, #fff01f, #4de75c)
        );
      }

      div {
        position: absolute;
        top: 0.33vh;
        left: 4px;
        width: var(--w);
        height: var(--w);

        :deep(.el-loading-mask) {
          border-radius: $radius-5;
        }

        img {
          border-radius: $radius-5;
          width: var(--w);
          height: var(--w);
          overflow: hidden;
          background: #fff;
          padding: $space-1;
        }
      }
    }
  }

  .step2,
  .step3 {
    padding: 0 72px;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: center;
    text-align: center;
    margin-top: $space-70;

    .title {
      width: 100%;
      display: flex;
      justify-content: center;
      margin-bottom: $space-3_h;
    }

    .tip {
      width: 100%;
      color: #fff;
      text-shadow: 0 0.17vh 0.17vh rgba(0, 0, 0, 0.25);
      font-size: $font-size-7;
      line-height: 1.5em; /* 150% */
    }

    .list {
      width: 100%;
      display: flex;
      flex-wrap: wrap;
      // gap: 56px $space-2;
      justify-content: center;
      margin: 7.33vh 0 10.33vh;

      .option {
        margin: 0 $space-2 4.67vh 0;
      }
    }

    .mj-button {
      position: relative;

      .x-icon {
        position: absolute;
        right: $space-6;
      }
    }
  }

  .step3 {
    .list {
      margin: 7.33vh 0 5vh;

      .option {
        width: 296px;
        height: 12.42vh;
      }
    }
  }
}
</style>
