<template>
  <div class="main-box">
    <div class="table-box">
      <ProTable
        ref="proTable"
        row-key="id"
        :columns="columns"
        :request-api="getTableList"
        :init-param="initParam"
        :search-col="{ xs: 1, sm: 1, md: 2, lg: 3, xl: 3 }"
        :form-props="{ labelWidth: '120px' }"
        :select-on-indeterminate="false"
        @sort-change="sortChange"
      >
        <!-- 表格 header 按钮 -->
        <template #tableHeader="{ isSelected, selectedListIds, selectedList }">
          <el-button
            v-auth="['article:first:export']"
            type="primary"
            :disabled="!isSelected"
            :icon="Download"
            plain
            @click="exportAction(selectedListIds)"
          >
            导出
          </el-button>
          <el-button
            v-auth="['article:first:delete']"
            type="success"
            :disabled="isBatchDeleteDisabled(selectedList as Clause.ClauseInfo[])"
            :icon="Delete"
            @click="deleteAction(selectedListIds, selectedList as Clause.ClauseInfo[])"
          >
            批量删除
          </el-button>
        </template>
        <template #firstArticleNo="scope">
          <span>SJ{{ scope.row.firstArticleNo || "--" }}</span>
          <el-tag v-if="scope.row.revokeFlag" class="ml5">撤回</el-tag>
        </template>
        <!-- 表格操作 -->
        <template #operation="scope">
          <el-button type="primary" link :icon="View" @click="viewAction(scope.row)"> 详情 </el-button>
          <el-button
            v-auth="['article:first:delete']"
            type="primary"
            link
            :icon="Delete"
            @click="deleteAction([scope.row.id])"
            :disabled="isDisabled(scope.row)"
          >
            删除
          </el-button>
        </template>
      </ProTable>
    </div>
  </div>
</template>
<script setup lang="ts" name="FirstClause">
import { ref, reactive, h } from "vue";
import { useRouter } from "vue-router";
import { FirstClause, Clause } from "@/api/interface";
import { useHandleData, useDownload, usePageKeepALive } from "@/hooks";
import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { StyleId, AnnoStatus, AnnoStatusEnum } from "@/enums";
import { getDictOptions } from "@/api/modules/common";
import { getFirstClauseList, logicDeleteClause, exportFirstClause } from "@/api/modules/corpus/first-clause";
import { View, Delete, Download } from "@element-plus/icons-vue";

const DETAIL_PAGE_ROUTE = "SjDetail";
// 页面缓存
usePageKeepALive([DETAIL_PAGE_ROUTE], () => {
  proTable.value?.getTableList();
});

// ProTable 实例
const proTable = ref<ProTableInstance>();
const router = useRouter();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
  sortBy: ""
});
// 表格配置项
const columns = reactive<ColumnProps<Clause.ClauseInfo>[]>([
  { type: "selection", width: 50 },
  {
    prop: "firstArticleNo",
    label: "首见条文编号",
    align: "left",
    search: {
      el: "input",
      order: 1,
      props: {
        prefixIcon: h("span", "SJ"),
        type: "number",
        max: 999999999,
        onBlur: (e: any) => {
          const searchParam = proTable.value!.searchParam;
          if (searchParam.firstArticleNo.length > e.target.max.length) {
            searchParam.firstArticleNo = e.target.max;
          }
        }
      }
    }
  },
  {
    prop: "articleContent",
    align: "left",
    label: "条文内容",
    search: { el: "input", order: 3 }
  },
  {
    prop: "diseaseId",
    label: "所属疾病",
    render: scope => scope.row.diseaseName || "--",
    enum: () => getDictOptions("disease"),
    fieldNames: { label: "dictLabel", value: "dictCode" },
    search: { el: "select", order: 2, props: { filterable: true } }
  },
  {
    prop: "bookId",
    label: "书名",
    render: scope => scope.row.bookName || "--",
    enum: () => getDictOptions("book"),
    fieldNames: { label: "dictLabel", value: "dictCode" },
    search: { el: "select", order: 5, props: { filterable: true } }
  },

  { prop: "chapter", label: "卷篇" },
  { prop: "author", label: "作者" },
  {
    prop: "dynastySort",
    label: "朝代",
    render: scope =>
      scope.row.endDynastySort && scope.row.startDynastySort !== scope.row.endDynastySort
        ? `${scope.row.startDynastyName}~${scope.row.endDynastyName}`
        : scope.row.startDynastyName || "--",
    enum: () => getDictOptions("dynasty"),
    fieldNames: { label: "dictLabel", value: "dictSort" },
    search: { el: "select", order: 7, props: { filterable: true } }
  },
  {
    prop: "publicationDate",
    label: "成书年代",
    search: { el: "grace-year-input", custom: true, order: 8, key: "publicationDate" },
    sortable: "custom",
    render: ({ row }) =>
      row.publicationDate < 0
        ? `公元前${-row.publicationDate}`
        : `${typeof row.publicationDate === "number" ? row.publicationDate : "--"}`
  },
  { prop: "styleId", label: "体裁", enum: StyleId.getAllEnumValues(), search: { el: "select", order: 6 } },
  { prop: "version", label: "版本信息" },
  {
    prop: "annotationStatus",
    label: "状态",
    tag: true,
    enum: AnnoStatus.getAllEnumValues(),
    search: { el: "select", order: 4 }
  },
  { prop: "createTime", label: "创建时间" },
  { prop: "operation", label: "操作", width: 240, fixed: "right" }
]);
// 分页列表获取数据
const getTableList = (params: FirstClause.ReqFirstClauseParams) => {
  return getFirstClauseList(params);
};

// 删除
const deleteAction = async (ids: number[], selectList?: Clause.ClauseInfo[]) => {
  let msg = `是否删除当前${ids.length}条首见条文，删除后该条文及其相关条文将移至【条文回收站】`;
  let articleIds = ids;
  if (selectList) {
    const disableList = selectList.filter(isDisabled);
    if (disableList.length > 0) {
      msg = `当前选中 ${selectList.length} 条首见条文中有 ${disableList.length} 条无法删除，是否删除其余 ${
        selectList.length - disableList.length
      } 条首见条文，删除后该条文及其相关条文将移至【条文回收站】`;
      articleIds = selectList.filter(row => !isDisabled(row)).map(row => row.id);
    }
  }
  await useHandleData(logicDeleteClause, { articleIds }, msg);
  proTable.value?.getTableList();
};

// 详情
function viewAction(row: Clause.ClauseInfo) {
  router.push({
    name: DETAIL_PAGE_ROUTE,
    query: {
      id: row.id
    }
  });
}

// 批量导出
async function exportAction(ids: string[] | number[]) {
  await useDownload(exportFirstClause, "导出首见条文", { articleIds: ids }, true, ".xlsx");
  proTable.value?.clearSelection();
}

// 排序
function sortChange({ prop, order }: any) {
  initParam.sortBy = order ? `${prop} ${order.replace("ending", "")}` : "";
  console.log("排序", initParam.sortBy);
}

// 表格多选-全部
// function selectionSelelctAll(selection: Clause.ClauseInfo[]) {
//   const tableRef: any = proTable.value?.element;
//   selection.filter(isDisabled).forEach(row => {
//     tableRef?.toggleRowSelection(row, false);
//   });
// }

// 是否禁用删除  (审核通过或者已上传不可以删除)
const isDisabled = (row: any) => row.annotationStatus >= AnnoStatusEnum.PASSED;

// 是否禁用批量删除
const isBatchDeleteDisabled = (selectedList: Clause.ClauseInfo[]) => {
  return selectedList.filter(row => !isDisabled(row)).length === 0;
};

// 禁用选择类名
// const rowClassName = ({ row }: { row: Clause.ClauseInfo }) => {
//   if (isDisabled(row)) return "disabled-row";
// };
</script>
<style lang="scss" scoped></style>
