<script setup>
import { ref, reactive, onMounted, computed, nextTick } from "vue";
import { Search } from "@element-plus/icons-vue";
import FilterGroup from "@/components/FilterGroup";
import Question from "@/components/Question";
import {
  getSubjectStageChannelType,
  getSubjectTitleList,
  updateSubjectTitleCollect,
  getSubjectTitleAnalyze,
} from "@/api";
import usePaperStore from "@/store/modules/paper";
import { storeToRefs } from "pinia";
import { formatTitleToPaper } from "@/utils";
import { useRouter } from "vue-router";
import { newPage } from "@/utils";

const props = defineProps({
  showTool: {
    type: Boolean,
    default: true,
  },
  showFilter: {
    type: Boolean,
    default: true,
  },
  custom: {
    type: Boolean,
    default: false,
  },
  data: {
    type: Array,
    default: null,
  },
});
const emits = defineEmits(["refresh", "changePage"]);

const router = useRouter();
const { search, searchFun, paperConfig } = storeToRefs(usePaperStore());
const { addQuestions, removeQuestions, jumpToKnowledge, switchFilter } =
  usePaperStore();

const filterLoading = ref(false);
const options = reactive([
  {
    label: "题型",
    children: [],
  },
  {
    label: "难度",
    optional: true,
    children: [
      {
        label: "容易",
        value: 11,
      },
      {
        label: "较易",
        value: 12,
      },
      {
        label: "普通",
        value: 13,
      },
      {
        label: "较难",
        value: 14,
      },
      {
        label: "困难",
        value: 15,
      },
    ],
  },
  {
    label: "年份",
    optional: true,
    children: Array.from({ length: 10 }, (i, idx) => ({
      label: 2024 - idx,
      value: 2024 - idx,
    })),
  },
  {
    label: "排序",
    optional: true,
    children: [
      {
        label: "组卷次数",
        children: [
          {
            label: "升序",
            value: "1_0",
          },
          {
            label: "降序",
            value: "1_1",
          },
        ],
      },
      {
        label: "真题次数",
        children: [
          {
            label: "升序",
            value: "2_0",
          },
          {
            label: "降序",
            value: "2_1",
          },
        ],
      },
      {
        label: "试题难度",
        children: [
          {
            label: "升序",
            value: "3_1",
          },
          {
            label: "降序",
            value: "3_0",
          },
        ],
      },
    ],
  },
]);
const filter = reactive([[], [], [], []]);

const questions = ref([]);
// 过滤已出题目
const filterJob = ref(false);
// 实际引用
const showData = computed(() => {
  const d = props.custom ? props.data : questions.value;
  if (filterJob.value) {
    return d.filter((i) => i.jobFlag !== 1);
  }
  return d;
});

const _keyword = ref("");
const keyword = ref("");

async function init() {
  try {
    // 必须先获取完前置条件后再去查数据，否则会重复请求
    // if (
    //   !search.value.stagePid ||
    //   !search.value.subjectId ||
    //   (!search.value.chapterId && paperConfig.value.showLabelType !== 1) ||
    //   (!search.value.bookId && paperConfig.value.showLabelType !== 1)
    // )
    //   return;
    filterLoading.value = true;

    const { data: res } = await getSubjectStageChannelType({
      pid: 0,
      stagePid: search.value.stagePid,
      subjectId: search.value.subjectId,
    });
    options[0].children = res.map((i) => {
      let obj = {
        label: i.name,
        value: i.baseId,
      };
      if (i.children && i.children.length > 0) {
        obj.children = i.children.map((j) => ({
          label: j.name,
          value: j.baseId,
        }));
      }
      return obj;
    });
    filter[0][0] = options[0].children[0].value;
  } catch (err) {
    console.log(err);
    options[0].children = [];
    filter[0][0] = "";
  } finally {
    filterLoading.value = false;
  }
}

const page = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});
function changeSize() {
  page.pageNum = 1;
  getData();
}
function changeCurrent() {
  getData();
}

const loading = ref(false);
async function getData() {
  window.scrollTo({
    top: 0,
    behavior: "smooth",
  });
  // 必须先获取完前置条件后再去查数据，否则会重复请求
  // if (
  //   !search.value.stagePid ||
  //   !search.value.subjectId ||
  //   !filter[0][0] ||
  //   (!search.value.chapterId && paperConfig.value.showLabelType !== 1) ||
  //   (!search.value.bookId && paperConfig.value.showLabelType !== 1)
  // )
  //   return;
  loading.value = true;
  try {
    const res = await getSubjectTitleList({
      pageNum: page.pageNum,
      pageSize: page.pageSize,
      stagePid: search.value.stagePid,
      subjectId: search.value.subjectId,
      chapterId: search.value.chapterId,
      bookId: search.value.bookId,
      knowledgeId: search.value.knowledgeId,
      provinces: search.value.provinces,
      channelTypeId: filter[0][0],
      difficulty: filter[1][0],
      years: filter[2][0],
      orderByColumn: filter[3][0]?.split("#")[0],
      isAsc: filter[3][0]?.split("#")[1],
      title: keyword.value,
    });
    page.total = res.total;
    questions.value = [];
    await nextTick();
    questions.value = formatTitleToPaper(res.rows);
  } catch (err) {
    console.log(err);
  } finally {
    loading.value = false;
  }
}

// 收藏
async function onCollect(data, cb) {
  try {
    await updateSubjectTitleCollect({
      stagePid: data.stagePid,
      subjectId: data.subjectId,
      titleId: data.id,
    });
    data.collectFlag === 0 ? (data.collectFlag = 1) : (data.collectFlag = 0);
    emits("refresh", "collect");
  } catch (err) {
    console.log(err);
  } finally {
    cb();
  }
}

// 添加试题
function onCombination(data, selected) {
  if (selected) {
    removeQuestions([data]);
  } else {
    addQuestions([data]);
  }
}

// 引用跳转
function onQuote(data) {
  // newPage(`${location.origin}/paper/details?id=${data.paperId}`);
  router.push(`/paper/details?id=${data.id}`);
}

// 知识点跳转
function onKnowledge(data) {
  router.push("/paper/basket");
  switchFilter(1);
  jumpToKnowledge(data);
}

// 添加本页所有试题
function handleBatchAdd() {
  addQuestions(questions.value);
}

// 展开解析
async function onAnalysis(data) {
  if (data.show) return;
  const { data: res } = await getSubjectTitleAnalyze({
    baseId: data.baseId,
    stagePid: data.stagePid,
    subjectId: data.subjectId,
  });

  const arr = props.custom ? props.data : questions.value;
  const idx = arr.findIndex((i) => i.id === data.id);
  arr[idx] = formatTitleToPaper([res])[0];
  arr[idx].show = true;
}

onMounted(() => {
  if (props.custom) return;
  watchEffect(() => {
    init();
  });
});

function initData() {
  if (props.custom) return;
  getData();
}

searchFun.value = initData;

defineExpose({
  page,
  initData,
});
</script>

<template>
  <div>
    <FilterGroup
      v-if="showFilter"
      v-loading="filterLoading"
      class="box"
      v-model="filter"
      :options="options"
      @change="getData"
    />
    <div v-if="showTool" class="box tool-bar">
      <div>
        <!-- <el-input
        v-model="_keyword"
        style="width: 30%"
        size="large"
        placeholder="从结果中搜索"
        :suffix-icon="Search"
        @change="(val) => (keyword = val)"
        clearable
      /> -->
      </div>
      <div class="tool-total">
        <el-checkbox v-model="filterJob">过滤已出题目</el-checkbox>
        <el-button type="primary" @click="handleBatchAdd"
          >添加本页所有试题到试题篮</el-button
        >
      </div>
    </div>
    <div class="questions" v-loading="loading">
      <Question
        class="box"
        v-for="(item, idx) in showData"
        :key="item.id"
        :data="item"
        :index="idx + 1"
        @onCollect="onCollect"
        @onCombination="onCombination"
        @onQuote="onQuote"
        @onKnowledge="onKnowledge"
        @onAnalysis="onAnalysis"
      />
      <!-- <el-affix position="bottom" :offset="0"> -->
      <el-pagination
        class="box"
        style="justify-content: flex-end"
        :page-sizes="[10]"
        layout="total, prev, pager, next, jumper, ->"
        background
        v-model:current-page="page.pageNum"
        v-model:page-size="page.pageSize"
        :total="page.total"
        @current-change="changeCurrent"
        @size-change="changeSize"
      />
      <!-- </el-affix> -->
    </div>
  </div>
</template>

<style lang="scss" scoped>
.box {
  width: 100%;
  background: #fff;
  padding: 16px;
  margin-bottom: 16px;
  border-radius: 4px;
}

.tool-bar {
  padding: 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .tool-total {
    display: flex;
    align-items: center;
    .el-button {
      margin-left: 32px;
    }
  }
}
</style>
