<script setup>
import { ref, reactive, onMounted, computed, watchEffect } from "vue";
import { Search, Delete, Files, ArrowDown } from "@element-plus/icons-vue";
import FilterGroup from "@/components/FilterGroup";
import { useRoute, useRouter } from "vue-router";
import usePaperStore from "@/store/modules/paper";
import { storeToRefs } from "pinia";
import { getStageListWithSubject, getProvinceList } from "@/api";
import { genId, newPage } from "@/utils";

defineProps({
  component: Object,
  path: {
    type: String,
    default: "",
  },
  hideFilter: {
    type: Boolean,
    default: false,
  },
});

const route = useRoute();
const router = useRouter();
const { paper, paperConfig, search, questionTotal } = storeToRefs(
  usePaperStore()
);
const { switchFilter, clearQuestionGroup, clearPaper } = usePaperStore();

const filter = reactive([
  {
    id: 1,
    type: "group",
    label: "学科",
    arrow: true,
    value: [],
    options: [],
  },
  {
    id: 2,
    label: "地区",
    type: "group",
    value: [],
    arrow: true,
    options: [
      {
        label: "地区",
        value: "1",
        children: [],
      },
    ],
  },
  {
    id: 3,
    label: "章节选题",
    value: 3,
    active: [0],
  },
  {
    id: 4,
    label: "知识点选题",
    value: 4,
    active: [1],
  },
  // {
  //   id: 5,
  //   label: "试卷库",
  //   type: "list",
  //   value: 5,
  //   active: [2, 3, 4],
  //   options: [
  //     {
  //       label: "同步专区",
  //       value: 5,
  //       active: 2,
  //     },
  //     {
  //       label: "备考专区",
  //       value: 6,
  //       active: 3,
  //     },
  //     {
  //       label: "升学专区",
  //       value: 7,
  //       active: 4,
  //     },
  //   ],
  // },
]);
const labelName = computed(
  () =>
    `${filter[0].value[0]?.parentNode.label} ·
${filter[0].value[0]?.node.label}` || "学科"
);
const provinceName = computed(() => filter[1].value[0]?.node.label || "地区");

const showDrawer = ref(false);
function handleOpen() {
  showDrawer.value = true;
}

function beforeSwitchFilter(type) {
  router.push("/paper/basket");
  switchFilter(type);
}

// 切换筛选
function handleLabel(data) {
  switch (data.value) {
    case 3:
      beforeSwitchFilter(0);
      break;
    case 4:
      beforeSwitchFilter(1);
      break;
    case 5:
      beforeSwitchFilter(2);
      break;
    case 6:
      beforeSwitchFilter(3);
      break;
    case 7:
      beforeSwitchFilter(4);
      break;
  }
}

// 前往组卷中心
function handleGo() {
  router.push("/paper/combinationCenter");
  showDrawer.value = false;
}

const formatOptions = (data) =>
  data.map((i) => {
    let obj = {
      id: i.id,
      label: i.subject || i.name,
      value: genId(),
    };
    if (i.subjectVoList) {
      obj.children = formatOptions(i.subjectVoList);
    }
    return obj;
  });

async function init() {
  try {
    // 获取学科
    const [{ data: subjectRes }, { rows: provinceRes }] = await Promise.all([
      getStageListWithSubject(),
      getProvinceList(),
    ]);

    // 学科
    const subjectOptions = formatOptions(subjectRes);
    filter[0].options = subjectOptions;

    const stage = subjectOptions.find((i) => i.id === search.value.stagePid);
    if (!search.value.stagePid || !stage) {
      filter[0].value[0] = {
        node: subjectOptions[0].children[0],
        parentNode: subjectOptions[0],
      };
      filter[0].label = labelName.value;
      const stage = subjectOptions[0];
      const subject = subjectOptions[0].children[0];
      search.value.stagePid = stage.id;
      search.value.subjectId = subject.id;
      paperConfig.value.subjectName = stage.label;
      paperConfig.value.chapterName = subject.label;
    } else {
      // 加载缓存
      const subject = stage.children.find(
        (i) => i.id === search.value.subjectId
      );
      filter[0].value[0] = {
        node: subject,
        parentNode: stage,
      };
      filter[0].label = labelName.value;
    }

    // 地区
    const provinceOptions = formatOptions([
      {
        id: "",
        name: "全国",
      },
      ...provinceRes,
    ]);
    const province = provinceOptions.find(
      (i) => i.id === search.value.provinces
    );
    filter[1].options[0].children = provinceOptions;
    filter[1].value[0] = {
      node: province || provinceOptions[0],
      parentNode: {},
    };
    filter[1].label = provinceName.value;
  } catch (err) {
    console.log(err);
  }
}

// 更新学科
watch(
  () => filter[0].value,
  () => {
    filter[0].label = labelName.value;
    const subject = filter[0].value[0].parentNode;
    const chapter = filter[0].value[0].node;
    search.value.stagePid = subject.id;
    search.value.subjectId = chapter.id;
    if (
      ["/paper/testCollection", "/paper/paperCollection"].includes(route.path)
    )
      return;
    router.push("/paper/basket");
  }
);

// 更新地区名
watch(
  () => filter[1].value,
  (newVal) => {
    filter[1].label = provinceName.value;
    search.value.provinces = newVal[0].node.id;
    router.push("/paper/basket");
  }
);

let cacheStagePid = search.value.stagePid,
  cacheSubjectId = search.value.subjectId;
watchEffect(() => {
  if (!filter[0].options.length) return;
  const { stagePid, subjectId } = search.value;
  if (cacheStagePid !== stagePid || cacheSubjectId !== subjectId) {
    clearPaper(false);
  }
  cacheStagePid = stagePid;
  cacheSubjectId = subjectId;
  const subject = filter[0].options.find((i) => i.id === stagePid);
  const chapter =
    subject.children.find((i) => i.id === subjectId) || subject.children[0];
  filter[0].value[0].parentNode = subject;
  filter[0].value[0].node = chapter;
  paperConfig.value.subjectName = subject.label;
  paperConfig.value.chapterName = chapter.label;
  filter[0].label = labelName.value;
});

onMounted(() => {
  init();
});

const options = [
  {
    label: "试题",
    value: 0,
  },
  // {
  //   label: "试卷",
  //   value: 1,
  // },
];

const keyword = ref();
function onSubmit() {
  search.value.keyword = keyword.value;
  // newPage(`${location.origin}/paper/search`);
  router.push("/paper/search");
}
onMounted(() => {
  search.value.keyword = "";
});
</script>

<template>
  <div>
    <el-affix :z-index="2001">
      <div class="paper-header">
        <div class="paper-header-search">
          <el-select
            v-model="search.keywordType"
            size="large"
            style="width: 100px; margin-right: 4px"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-input
            v-model="keyword"
            style="width: 40%"
            size="large"
            placeholder="请输入"
            :suffix-icon="Search"
            clearable
            @keyup.enter="onSubmit"
            @change="onSubmit"
          />
        </div>
        <div v-show="!hideFilter" class="paper-header-filter">
          <ul>
            <el-popover
              v-for="(item, idx) in filter"
              :key="idx"
              placement="bottom-start"
              :width="200"
              trigger="hover"
              popper-class="paper-popover"
              :disabled="!item.type"
            >
              <template #reference>
                <li
                  :class="{
                    active:
                      route.name === 'Basket' &&
                      item.active?.includes(paperConfig.showLabelType),
                  }"
                  @click="handleLabel(item)"
                >
                  {{ item.label }}
                  <el-icon v-if="item.arrow"><ArrowDown /></el-icon>
                </li>
              </template>
              <template v-if="item.type === 'group'">
                <FilterGroup
                  v-model="item.value"
                  :options="item.options"
                  isSingle
                />
              </template>
              <div v-if="item.type === 'list'" class="filter-list">
                <ul>
                  <li
                    :class="{
                      active:
                        route.name === 'Basket' &&
                        paperConfig.showLabelType === list.active,
                    }"
                    v-for="list in item.options"
                    :key="list.label"
                    @click="handleLabel(list)"
                  >
                    {{ list.label }}
                  </li>
                </ul>
              </div>
            </el-popover>
          </ul>
        </div>
      </div>
    </el-affix>
    <div class="basket" id="test-basket" @click="handleOpen">
      <div class="basket-total">
        {{ questionTotal }}/{{ paperConfig.maxQuantity }}
      </div>
      <div class="basket-title">
        <el-icon><Files /></el-icon>
      </div>
    </div>
    <el-drawer
      v-model="showDrawer"
      title="试题总量"
      direction="rtl"
      class="basket-drawer"
      close-on-click-modal
      lock-scroll
    >
      <template v-if="paper.content.length">
        <div class="basket-list">
          <div class="basket-item" v-for="item in paper.content">
            <div>{{ item.type }}</div>
            <div class="basket-item-total">
              {{ item.children?.length || 0 }}题
              <el-icon color="#F56C6C" @click="clearQuestionGroup(item)"
                ><Delete
              /></el-icon>
            </div>
          </div>
        </div>
        <div class="basket-buttons">
          <el-button type="danger" @click="clearPaper">清空篮子</el-button>
          <el-button type="primary" @click="handleGo">组卷中心</el-button>
        </div>
      </template>

      <el-empty v-else></el-empty>
    </el-drawer>
    <!-- <component :is="component" :key="path" /> -->
  </div>
</template>

<style lang="scss" scoped>
.paper-header {
  width: 100%;
  background: #fff;
  padding: 0 40px;
  box-sizing: border-box;
  box-shadow: var(--el-box-shadow-light);
  &-search {
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  &-filter {
    height: 40px;

    ul {
      list-style-type: none;
      display: flex;
      align-items: center;

      li {
        padding: 0 20px;
        cursor: pointer;
        display: flex;
        align-items: center;
        .el-icon {
          margin-left: 8px;
        }

        &.active {
          color: var(--el-color-primary);
        }
      }
    }
  }
}
.basket {
  position: fixed;
  right: 0;
  top: 80px;
  background: var(--el-color-primary);
  opacity: 0.9;
  width: 50px;
  height: 70px;
  color: #fff;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  border-radius: 4px 0 0 4px;
  cursor: pointer;
  font-size: 16px;
  z-index: 2001;
  &-total {
    margin-top: 15px;
    width: 100%;
    text-align: center;
  }
  &-title {
    width: 1em;
  }
}
</style>
<style lang="scss">
.paper-popover {
  width: auto !important;
  max-width: 70% !important;
  .filter-list {
    ul {
      padding: 0;
      margin: 0;
      list-style-type: none;
      li {
        cursor: pointer;
        padding: 16px 8px;
        text-align: center;
        &.active {
          color: var(--el-color-primary);
        }
      }
    }
  }
}
.basket-drawer {
  .el-drawer__body {
    padding-top: 0;
  }
  .basket-list {
    .basket-item {
      border: 1px solid #ccc;
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 40px;
      margin-bottom: 16px;
      border-radius: 4px;
      padding: 0 8px;
      .el-icon {
        margin-left: 16px;
        vertical-align: text-top;
        cursor: pointer;
      }

      &-total {
        color: #73767a;
      }
    }
  }
  .basket-buttons {
    margin-top: 40px;
    text-align: center;
  }
}
</style>
