<script setup lang="ts">
import subjectApi from '@/api/subject/subject'
import TextbookDia from './TextbookDia/index.vue'
import ChapterTree from './ChapterTree/index.vue'
import { subjectStore, groupPaperStore } from '@/stores'
import { XMessage } from '@/hooks'
import { useRoute, useRouter } from 'vue-router'
import { cleanBooks } from '../../../../api/subject/config'
import { OSS_URL } from '@/utils'

const route = useRoute()
const router = useRouter()

const { subject } = subjectStore()
const { groupPaperParams } = toRefs(groupPaperStore())

const textbookList = ref<anyObj[]>([])

const showTextbookDia = ref(false)
const textbookData = ref<anyObj>({})
// 选中的章节或知识点
const selectTextbookList = ref<anyObj[]>([])

const loading = ref(true)
async function init() {
  loading.value = true
  try {
    const res = await subjectApi.getUserTextBookList({
      size: -1,
      subjectId: subject.id,
    })
    cleanBooks(res.rows)
    textbookList.value = res.rows
    // 进度值先清0
    textbookList.value.forEach(i => {
      i.progress = 0
    })
  } catch (err) {
    console.log(err)
  } finally {
    loading.value = false
  }
}

function onClick(data: anyObj) {
  showTextbookDia.value = true
  textbookData.value = data
}

function textBookDiaConfirm(chapter: anyObj[], currentChapter: anyObj[], progress: number) {
  const idx = selectTextbookList.value.findIndex(
    i => i.textBookId === textbookData.value.textBookId,
  )
  // 设置进度
  textbookData.value.progress = progress * 100
  if (idx === -1) {
    if (chapter?.length) {
      selectTextbookList.value.push({
        ...textbookData.value,
        chapter,
      })
    }
  } else {
    // 设置进度
    selectTextbookList.value[idx].progress = textbookData.value.progress
    if (chapter?.length) {
      selectTextbookList.value[idx].chapter = chapter
    } else {
      selectTextbookList.value.splice(idx, 1)
    }
  }

  const textbookIdx = textbookList.value.findIndex(
    i => i.textBookId === textbookData.value.textBookId,
  )
  textbookIdx === -1 || (textbookList.value[textbookIdx].chapter = currentChapter)
}

// 过滤参数，去掉不需要的参数
function filterParams(list: anyObj[]) {
  function filterFun(arr: anyObj[]): anyObj[] {
    return arr?.map(i => {
      if (!i) return {}
      const res: anyObj = {
        id: i.id,
        name: i.name,
      }
      i.subjectId && (res.subjectId = i.subjectId)
      i.knowledgeVoList?.length && (res.knowledgeVoList = filterFun(i.knowledgeVoList))
      i.children?.length && (res.children = filterFun(i.children))
      return res
    })
  }
  return list.map(i => {
    return {
      textBookId: i.textBookId,
      textBookName: i.textBookName,
      chapter: filterFun(i.chapter),
    }
  })
}

function handleStart() {
  if (selectTextbookList.value.length <= 0) {
    return XMessage.error('请先选择学习范围')
  }
  groupPaperParams.value = {
    paperScore: filterParams(selectTextbookList.value),
    subjectId: subject.id,
    trainType: route.params.type === '0' ? 1 : 2,
  }
  router.push({ path: '/subject/doWork', query: { subjectId: subject.id, resourceType: 7 } })
}

onActivated(() => {
  selectTextbookList.value = []
  textbookList.value = []
  textbookData.value = {}
  init()
})
</script>

<template>
  <div class="page">
    <BackBar
      :leftText="`【${subject.name}】${route.params.type === '0' ? '章节组卷' : '知识点组卷'}`"
    ></BackBar>
    <div class="main">
      <div class="left">
        <book-shelf :progress="true" :books="textbookList as any" :width="1080" @select="onClick" />
      </div>
      <div class="right">
        <div
          class="right-tag"
          :style="{
            background: `url(${OSS_URL}/urm/groupPaper_tag_bg.svg) 100%/cover no-repeat`,
          }"
        >
          <span data-content="组卷范围：">组卷范围：</span>
        </div>
        <el-scrollbar v-if="selectTextbookList.length">
          <div v-for="i in selectTextbookList" :key="i.textbookId" class="selectList-item">
            <el-collapse>
              <el-collapse-item :name="i.textbookId">
                <template #title>
                  <div class="title_0">
                    {{ `${i.clean.fullName}（${i.progress / 100}%）` }}
                  </div>
                  <div class="icon-box">
                    <Icon
                      class="arrow-icon"
                      name="textbook_arrow_up_grey"
                      size="24"
                      style="margin: 0 32px"
                    />
                  </div>
                </template>
                <ChapterTree :options="i.chapter" :type="Number(route.params.type)"></ChapterTree>
              </el-collapse-item>
            </el-collapse>
          </div>
        </el-scrollbar>
        <Empty
          v-else
          type="learn"
          :content="`选择对应教材，勾选章节${route.params.type === '0' ? '' : '知识点'}进行组卷哦～`"
        ></Empty>
      </div>
    </div>
    <mj-button type="warn" tilt width="272" height="80" size="32" @click="handleStart"
      >立即组卷</mj-button
    >
    <TextbookDia
      v-model="showTextbookDia"
      :subjectId="subject.id"
      :data="textbookData"
      @ok="textBookDiaConfirm"
    />
  </div>
</template>

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

  .main {
    height: calc(100% - 80px);
    display: flex;
    // gap: $space-8;
    .left {
      flex-shrink: 0;
      width: 1104px;
      margin-right: 16px;

      .book-shelf {
        margin-top: 2.75vh;
        height: 84.17vh;
        left: -10px;
      }
    }
    .right {
      width: 672px;
      flex-shrink: 0;
      position: relative;
      margin-top: 2.67vh;
      height: calc(100% - 3.83vh);
      flex: 1;
      border-radius: 1.67vh;
      // overflow: hidden;
      background: linear-gradient(180deg, #f0faff 0%, #fafdff 100%);
      box-shadow: 0 0.33vh 0.33vh 0 rgba(0, 0, 0, 0.25);
      .el-scrollbar {
        border-radius: 1.67vh;
        .selectList-item {
          :deep(.el-collapse) {
            border-bottom: none;
            border-top: none;
            .el-collapse-item__wrap {
              -webkit-transition:
                0s height,
                0s padding-top,
                0s padding-bottom;
              transition:
                0s height,
                0s padding-top,
                0s padding-bottom;
              border: none;
            }
            .el-collapse-item__content {
              padding-bottom: 0;
            }
            .el-collapse-item__header {
              height: 6.67vh;
              font-size: $font-size-5;
              line-height: 1.5em;
              font-weight: 400;
              color: $font-tag-color;
              border: none;
              position: relative;
              justify-content: space-between;
              .arrow-icon {
                transition: all 0.3s ease-in-out;
              }
              &.is-active {
                .arrow-icon {
                  transform: rotate(180deg);
                }
                .title_0 {
                  background: #90fcf7;
                  & + .icon-box {
                    background: linear-gradient(180deg, #90fcf7 0%, #62e3fd 125%);
                  }
                }
              }

              .el-icon {
                display: none;
              }

              &::after {
                position: absolute;
                left: 24px;
                bottom: 0;
                content: '';
                display: block;
                width: calc(100% - 48px);
                height: 0.17vh;
                background: repeating-linear-gradient(
                  to right,
                  rgba(0, 0, 0, 0.15),
                  rgba(0, 0, 0, 0.15) 8px,
                  transparent 8px,
                  transparent 16px /* 线条间隔 */
                );
              }
              .title_0 {
                width: calc(100% - 66px);
                height: 6.67vh;
                line-height: 6.67vh;
                background: #dafafd;
                text-align: left;
                padding-left: 24px;
                @include single_ellipsis;
                & + .icon-box {
                  height: 100%;
                  display: flex;
                  align-items: center;
                  background: #dafafd;
                }
              }
            }
            .el-collapse-item:last-child {
              margin-bottom: 0;
            }
          }
          background: linear-gradient(180deg, #f0faff 0%, #fafdff 100%);
        }
      }
      &-tag {
        position: absolute !important;
        width: 258px;
        height: 6.17vh;
        padding: 0.67vh 24px 1.5vh;
        top: -6.17vh;
        left: 0;

        span {
          color: #fff;
          font-family: $font-special;
          font-size: 2.67vh;
          line-height: 4vh; /* 150% */
          @include font-stroke($font-color, 4px);
        }
      }
    }
  }
  .mj-button {
    position: absolute;
    top: 2vh;
    right: 64px;
  }
}
</style>
