<script setup>
import { ref, reactive, watch } from "vue";
import Table from "@/components/Table/index.vue";
import FilterGroup from "@/components/FilterGroup";
import PaperAnalysisDia from "../components/PaperAnalysisDia";
import {
  getSubjectPaperList,
  getPaperAnalyzeById,
  getPaperStageList,
} from "@/api";
import usePaperStore from "@/store/modules/paper";
import { storeToRefs } from "pinia";
import { useRouter } from "vue-router";
import { newPage } from "@/utils";

const props = defineProps({
  showFilter: {
    type: Boolean,
    default: true,
  },
  custom: {
    type: Boolean,
    default: false,
  },
  data: {
    type: Array,
    default: null,
  },
});

const router = useRouter();
const { search, paperConfig } = storeToRefs(usePaperStore());

const options = reactive([
  {
    label: "年级",
    optional: true,
    children: [],
  },
  {
    label: "年份",
    optional: true,
    children: Array.from({ length: 10 }, (i, idx) => ({
      label: 2024 - idx,
      value: 2024 - idx,
    })),
  },
  {
    label: "排序",
    optional: true,
    children: [
      {
        label: "更新时间",
        children: [
          {
            label: "升序",
            value: "t1.update_time#asc",
          },
          {
            label: "降序",
            value: "t1.update_time#desc",
          },
        ],
      },
    ],
  },
]);
const filter = reactive([[], [], ["t1.update_time#desc"]]);

const xbTable = reactive({
  loading: false,
  columns: [
    { prop: "name", label: "名称" },
    { prop: "updateTime", label: "更新时间" },
    { prop: "lookNum", label: "浏览次数" },
    { prop: "typeName", label: "类型" },
    { label: "操作", slot: "operation" },
  ],
  tableData: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
  },
});

if (props.custom) {
  watch(
    () => props.data,
    (newVal) => {
      xbTable.tableData = newVal;
    },
    {
      deep: true,
    }
  );
}

// 表格分页
function handleTablePageChange(val) {
  xbTable.pagination.pageSize = val.limit;
  xbTable.pagination.pageNum = val.page;
}

async function getData() {
  if (!search.value.stagePid || !search.value.subjectId) return;
  xbTable.loading = true;
  try {
    const res = await getSubjectPaperList({
      pageNum: xbTable.pagination.pageNum,
      pageSize: xbTable.pagination.pageSize,
      stagePid: search.value.stagePid,
      subjectId: search.value.subjectId,
      chapterId: search.value.chapterId,
      type: search.value.type,
      provinces: search.value.provinces,
      category: category.value,
      stageId: filter[0][0],
      years: filter[1][0],
      orderByColumn: filter[2][0]?.split("#")[0],
      isAsc: filter[2][0]?.split("#")[1],
    });
    xbTable.pagination.total = res.total;
    xbTable.tableData = res.rows;
  } catch (err) {
    console.log(err);
  } finally {
    xbTable.loading = false;
  }
}

const showAnalysis = ref(false);
const analysisData = ref({});
async function handleClick(type, data) {
  switch (type) {
    case 1:
      data.loading = true;
      try {
        const res = await getPaperAnalyzeById(data.id);
        analysisData.value = res.data;
        showAnalysis.value = true;
      } catch (err) {
        console.log(err);
      } finally {
        data.loading = false;
      }
      break;
    case 2:
      // newPage(`${location.origin}/paper/details?id=${data.id}`);
      router.push(`/paper/details?id=${data.id}`);
      break;
  }
}

const category = computed(() => {
  if (paperConfig.value.showLabelType === 2) return 1;
  if (paperConfig.value.showLabelType === 3) return 2;
  if (paperConfig.value.showLabelType === 4) return 3;
});
async function init() {
  if (!search.value.stagePid || !search.value.subjectId) return;

  if (!category.value) return;
  const { data: res } = await getPaperStageList({
    pid: 0,
    stagePid: search.value.stagePid,
    subjectId: search.value.subjectId,
    category: category.value,
  });
  options[0].children = res.map((i) => ({
    label: i.stageName,
    value: i.stageId,
  }));
}

if (!props.custom) {
  watchEffect(() => {
    getData();
  });
}

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

defineExpose({
  page: xbTable.pagination,
});
</script>

<template>
  <div>
    <FilterGroup
      v-if="showFilter"
      class="box"
      v-model="filter"
      :options="options"
    />
    <Table
      class="box"
      :xbTable="xbTable"
      @tablePageChange="handleTablePageChange"
    >
      <template v-slot:operation="scope">
        <el-button
          :loading="scope.row.loading"
          link
          type="primary"
          icon="PieChart"
          @click="handleClick(1, scope.row)"
          >分析</el-button
        >
        <el-button
          link
          type="primary"
          icon="View"
          @click="handleClick(2, scope.row)"
          >查看</el-button
        >
      </template>
    </Table>
    <PaperAnalysisDia v-model="showAnalysis" :data="analysisData" />
  </div>
</template>

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