<template>
  <el-container class="search-result">
    <el-aside class="aside" v-auth="['search:classify']">
      <div class="aside_search">
        <el-button class="common-btn" size="small" type="primary" @click="asideSearch">
          <el-icon class="mr5"> <Search /></el-icon> 搜索
        </el-button>
        <el-button class="advance-btn ml20" size="small" type="primary" @click="asideReset"> 重置 </el-button>
      </div>
      <AsideFilter v-model:dynasty-sort="searchPar.classifyDynastySortList" v-model:attr-id="searchPar.articleAttributeList" />
    </el-aside>
    <el-main class="main">
      <div class="topbar">
        <div>检索范围：<span style="font-size: 18px; color: #228fff">总库</span></div>
        <div>共找到 {{ proTable?.pageable.total }} 条数据</div>
      </div>
      <div class="table-box">
        <ProTable
          ref="proTable"
          row-key="id"
          :columns="columns"
          :init-param="initParam"
          :request-api="getTableList"
          :search-col="{ xs: 1, sm: 1, md: 2, lg: 3, xl: 3 }"
          :form-props="{ labelWidth: '120px' }"
          :select-on-indeterminate="true"
          @sort-change="sortChange"
          @filter-change="filterChange"
        >
          <!-- 表格 header 按钮 -->
          <template #tableHeader="{ isSelected, selectedListIds }">
            <el-button
              v-auth="['search:export']"
              type="primary"
              :disabled="!isSelected"
              :icon="Download"
              @click="exportAction(selectedListIds, true)"
            >
              导出
            </el-button>
          </template>
          <!-- 表格操作 -->
          <template #operation="scope">
            <el-button type="primary" link :icon="View" @click="viewAction(scope.row)"> 详情 </el-button>
            <el-button
              v-auth="['search:export']"
              type="primary"
              link
              :icon="Download"
              @click="exportAction([scope.row.id], false)"
            >
              导出
            </el-button>
            <el-button v-auth="['search:revoke']" type="primary" link :icon="RefreshLeft" @click="revokeAction(scope.row)">
              撤回
            </el-button>
          </template>
        </ProTable>
      </div>
    </el-main>
  </el-container>
</template>
<script setup lang="ts" name="SearchResult">
import { ref, reactive, defineProps, withDefaults, watch } from "vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import { Retrieval, Clause } from "@/api/interface";
import { useDownload } from "@/hooks/useDownload";
import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { StyleId } from "@/enums";
import { getRetrievalList, exportRetrieval, revokeClause } from "@/api/modules/retrieval/index";
import { View, Download, RefreshLeft } from "@element-plus/icons-vue";
import AsideFilter from "./AsideFilter.vue";

interface Props {
  searchParams: Retrieval.ReqRetrievalParams;
}
const props = withDefaults(defineProps<Props>(), {
  searchParams: () => ({}) as Retrieval.ReqRetrievalParams
});
// ProTable 实例
const proTable = ref<ProTableInstance>();
const router = useRouter();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
  highStyle: props.searchParams.highStyle,
  sortBy: "",
  classifyDynastySortList: undefined, // 分类检索-朝代
  articleAttributeList: undefined // 分类检索-条文属性
});
let searchPar = reactive<any>({
  highStyle: props.searchParams.highStyle,
  sortBy: "",
  classifyDynastySortList: undefined, // 分类检索-朝代
  articleAttributeList: undefined // 分类检索-条文属性
});
// 表格配置项
const columns = reactive<ColumnProps<Clause.ClauseInfo>[]>([
  { type: "selection", width: 50 },
  { type: "index", label: "序号", width: 80 },
  { prop: "articleContent", label: "条文内容" },
  { prop: "diseaseName", label: "所属疾病" },
  { prop: "bookName", label: "书名" },
  { prop: "chapter", label: "卷篇" },
  {
    prop: "dynastyName",
    label: "朝代",
    render: scope =>
      scope.row.endDynastySort && scope.row.startDynastySort !== scope.row.endDynastySort
        ? `${scope.row.startDynastyName}~${scope.row.endDynastyName}`
        : scope.row.startDynastyName || "--"
  },
  {
    prop: "publicationDate",
    label: "成书年代",
    sortable: "custom",
    render: ({ row }) =>
      row.publicationDate < 0
        ? `公元前${-row.publicationDate}`
        : `${typeof row.publicationDate === "number" ? row.publicationDate : "--"}`
  },
  {
    prop: "styleId",
    label: "体裁",
    columnKey: "styleId",
    filters: StyleId.getAllEnumValues().map(item => ({ text: item.label, value: item.value as any })),
    filteredValue: props.searchParams.highStyle as any,
    enum: StyleId.getAllEnumValues()
  },
  { prop: "relateArticleAmount", label: "相关条文计数", sortable: "custom" },
  { prop: "operation", label: "操作", width: 240, fixed: "right" }
]);

// watch

watch(
  () => props.searchParams,
  () => {
    proTable.value?.getTableList();
  }
);
// 查看详情
function viewAction(row: Clause.ClauseInfo) {
  router.push({
    name: "RetrievalDetail",
    query: {
      id: row.id
    }
  });
}

// 导出
async function exportAction(ids: string[] | number[], isBatch: boolean) {
  await useDownload(exportRetrieval, "导出检索结果", { articleIds: ids }, true, ".xlsx");
  if (isBatch) {
    proTable.value?.clearSelection();
  }
}
// 撤回
async function revokeAction(row: Clause.ClauseInfo) {
  await revokeClause({ id: row.id });
  proTable.value?.getTableList();
  ElMessage.success("操作成功");
}
// 分页列表获取数据
const getTableList = (params: Retrieval.ReqRetrievalParams) => {
  return getRetrievalList({ ...props.searchParams, ...params, ...searchPar });
};
const asideSearch = () => {
  proTable.value?.getTableList();
};
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const asideReset = () => {
  searchPar.classifyDynastySortList = [];
  searchPar.articleAttributeList = [];
  proTable.value?.reset();
};
// 表格筛选
function filterChange({ styleId }: any) {
  initParam.highStyle = styleId;
}

// 排序
function sortChange({ prop, order }: any) {
  searchPar.sortBy = order ? `${prop} ${order.replace("ending", "")}` : "";
  proTable.value?.getTableList();
}
</script>
<style lang="scss" scoped>
.search-result {
  width: 100%;
  height: 100%;
  .aside {
    height: 100% !important;
    background-color: #ffffff !important;
    .aside_search {
      box-sizing: border-box;
      display: flex;
      align-items: center;
      justify-content: center;
      height: 40px;
    }
    .common-btn {
      padding: 0 10px;
      color: #ffffff;
      background: #e3a000;
      &:hover {
        color: #ffffff;
        background: rgba(#e3a000, 0.7);
      }
    }
    .advance-btn {
      --el-button-bg-color: #ba7d44;
    }
  }
  .main {
    display: flex;
    flex-direction: column;
    padding: 0;
    .topbar {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 10px 20px;
      background: #ecd8be;
    }
  }
  .table-box {
    flex: 1;
    width: 100%;
  }
}
</style>
