<script setup lang="ts">
// import SubjectDia from './SubjectDia.vue'
// import { getDict } from '@/hooks'
import { userStore, subjectStore } from '@/stores'
import { storeToRefs } from 'pinia'
import userApi from '@/api/system/user'
import { useRouter } from 'vue-router'
import { getSubjectsByGrade, grades } from '../../api/subject/config'
import { XMessage } from '@/hooks'
// import { dialog } from '@/components/mj/mj-dialog'

const OSS_URL = import.meta.env.VITE_OSS_URL
const pattern = `url(${OSS_URL}/urm/subject_item_pattern.svg) left/cover no-repeat`

const router = useRouter()
const { userInfo } = storeToRefs(userStore())
const { selectSubject } = subjectStore()

// const showSubjectDia = ref(false)
// const TargetType = getDict('learn_target', true).enum
// const target = computed(() => TargetType[String(userInfo.value.learnTargetType)] || '请选择')

const subjectData = ref<anyObj[]>([])
const subjectLoading = ref(false)
async function initSubject() {
  if (!userInfo.value.learnGradeId) return
  subjectLoading.value = true
  try {
    const res = getSubjectsByGrade(userInfo.value.learnGradeId)
    cacheLearnGradeId = userInfo.value.learnGradeId
    subjectData.value = res.map((i: anyObj) => ({
      id: i.subjectId,
      name: i.name,
      subject: i.subject,
      pictureUrl: i.pictureUrl,
    }))
  } finally {
    subjectLoading.value = false
  }
}

// 切换学级
// const grade = computed(() => userInfo.value.learnGradeId)
const gradeData = ref<anyObj[]>([])
function initGrade() {
  gradeData.value = grades.map((i: anyObj) => ({
    value: i.id,
    label: i.name,
  }))
}
async function selectChange(item: anyObj) {
  try {
    await userApi.updateUserLearn({
      learnGradeId: item.value,
    })
    // userInfo.value.learnGradeId = item.value
    initSubject()
  } catch (err) {
    // grade.value = userInfo.value.learnGradeId;
  }
}

// 警告
function onClick(data: anyObj) {
  const gradeMatch = gradeData.value.some(i => i.value === userInfo.value.learnGradeId)
  if (!gradeMatch) {
    XMessage.error('请选择年级')
    return
  }
  selectSubject(data)
  router.push(`/subject/textbook?id=${data.id}`)
}

let cacheLearnGradeId: string
onActivated(() => {
  // 确保 learnGradeId 为字符串类型，与下拉选项值匹配（API 可能返回数字类型）
  if (userInfo.value.learnGradeId) {
    userInfo.value.learnGradeId = String(userInfo.value.learnGradeId)
  } else if (gradeData.value.length) {
    userInfo.value.learnGradeId = gradeData.value[0].value
  }
  // 学科没有变动不刷新
  if (subjectData.value.length && cacheLearnGradeId === userInfo.value.learnGradeId) return
  initSubject()
})
onMounted(() => {
  initGrade()
})
</script>

<template>
  <div class="page">
    <div class="head">
      <BackBar leftText="学习目标" />
      <Select
        v-model="userInfo.learnGradeId"
        :selectList="gradeData as any"
        @selectChange="selectChange"
        @click.stop
      ></Select>
      <!-- <mj-button width="272" height="80" tilt type="warn" @click="showSubjectDia = true">
        <span>{{ target }}</span>
        <Icon class="btn-icon" name="more_arrow_right" size="40" />
      </mj-button> -->
    </div>
    <Empty v-if="subjectLoading" type="loading" />
    <el-scrollbar v-else class="main">
      <div
        :class="{
          list: true,
          less: subjectData.length <= 5,
          more: subjectData.length > 9,
        }"
      >
        <div v-for="item in subjectData" :key="item.id" class="item" @click="onClick(item)">
          <img class="cover" :src="item.pictureUrl" />
          <div class="title">{{ item.subject }}</div>
        </div>
      </div>
    </el-scrollbar>
    <!-- <SubjectDia v-model="showSubjectDia" /> -->
  </div>
</template>

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

  .head {
    display: flex;
    align-items: center;
    column-gap: 3.67vh;
  }
  .main {
    width: 100%;
    height: 92%;
    padding-top: $space-8_h;
    .list {
      height: calc(100% - 6.67vh);
      display: grid;
      grid-template-columns: repeat(3, 576px);
      grid-auto-rows: 25.33vh;
      gap: $space-4_h;
      .item {
        border-radius: $radius-5;
        border: 0.67vh solid #fff;
        background: #fff;
        overflow: hidden;
        position: relative;
        cursor: pointer;
        .cover {
          width: 100%;
          height: 10.83vw;
          object-fit: cover;
        }
        .title {
          position: absolute;
          bottom: 0;
          width: 100%;
          height: 6.67vh;
          color: #fff;
          font-family: $font-special;
          font-size: $font-size-7;
          line-height: 6.67vh;
          background: #000;
          text-align: center;
          background: v-bind(pattern);
        }
      }

      &.less {
        grid-template-columns: 600px 600px 520px;
        grid-auto-rows: 38.33vh;
        gap: $space-4_h $space-4_h;
        .item {
          .cover {
            height: 30.33vh;
          }
          &:first-child {
            grid-column: span 2;
          }
          // &:nth-child(3) {
          //     margin-right: 0;
          //     // 裁剪28px 608 - 28 - 16(边)
          //     // 花纹裁剪 564 - 8 / 564 - 16
          //     clip-path: polygon(0 0, 100% 0, 100% 0, 564px 100%, 0% 100%);
          //     .title {
          //         clip-path: polygon(0 0, 100% 0, 556px 0, 548px 100%, 0% 100%);
          //     }
          // }

          // &:nth-child(4) {
          //     clip-path: polygon(44px 0, 100% 0, 100% 0, 100% 100%, 0% 100%);
          //     .title {
          //         clip-path: polygon(8px 0, 100% 0, 100% 0, 100% 100%, 0% 100%);
          //     }
          // }
        }
      }

      // &.more {
      //   padding-bottom: 6.67vh;
      // }
    }
  }
}
</style>
