<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: '100px' }"
        :select-on-indeterminate="false"
        :row-class-name="rowClassName"
        @sort-change="sortChange"
        @select-all="selectionSelelctAll"
      >
        <!-- 表格 header 按钮 -->
        <template #tableHeader="{ isSelected, selectedListIds }">
          <el-button v-auth="['article:import']" type="primary" :icon="Upload" @click="importAction"> 导入 </el-button>
          <el-button v-auth="['article:add']" type="primary" :icon="Plus" plain @click="addAction"> 添加 </el-button>
          <el-button
            v-auth="['article:trace:write']"
            type="success"
            :disabled="!isSelected"
            :icon="Delete"
            @click="deleteAction(selectedListIds)"
            plain
          >
            批量删除
          </el-button>
        </template>
        <!-- 条文内容 -->
        <template #articleContent="scope">
          <el-tag v-if="scope.row.delFlag === '2'">删</el-tag> {{ scope.row.articleContent || "--" }}
        </template>
        <!-- 表格操作 -->
        <template #operation="scope">
          <el-button
            v-auth="['article:trace:write']"
            type="primary"
            link
            :icon="Aim"
            @click="traceAction(scope.row)"
            :disabled="isDisabled(scope.row)"
          >
            溯源
          </el-button>
          <el-button
            v-auth="['article:trace:write']"
            type="primary"
            link
            :icon="Delete"
            @click="deleteAction([scope.row.id])"
            :disabled="isDisabled(scope.row)"
          >
            删除
          </el-button>
        </template>
      </ProTable>
    </div>
    <ClauseDialog ref="dialogRef" />
    <ImportExcelDialog
      ref="importRef"
      :file-size="50"
      title="条文"
      temp-path="./excel/trace_origin_temp.xlsx"
      :api="importTraceOrigin"
    />
  </div>
</template>
<script setup lang="ts" name="TraceOrigin">
import { ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { TraceOrigin, Clause } from "@/api/interface";
import { useHandleData, usePageKeepALive } from "@/hooks";
import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import ImportExcelDialog from "@/components/ImportExcelDialog/index.vue";
import { StyleId, TraceStatus, TraceStatusEnum } from "@/enums";
import { getTraceOriginList, deleteTraceOrigin, importTraceOrigin } from "@/api/modules/corpus/trace-origin";
import { Aim, Plus, Delete, Upload } from "@element-plus/icons-vue";
import ClauseDialog from "@/components/ClauseFormDialog/index.vue";

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

const dialogRef = ref<null | typeof ClauseDialog>(null);
const importRef = ref<typeof ImportExcelDialog>();
// ProTable 实例
const proTable = ref<ProTableInstance>();
const router = useRouter();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
  sortBy: ""
});
// 表格配置项
const columns = reactive<ColumnProps<Clause.ClauseInfo>[]>([
  { type: "selection", width: 50 },
  { type: "index", label: "序号", width: 80 },
  { prop: "articleContent", label: "条文内容", align: "left" },
  { prop: "diseaseName", width: 200, label: "所属疾病" },
  { prop: "styleId", label: "体裁", width: 200, enum: StyleId.getAllEnumValues() },
  {
    prop: "createTime",
    label: "添加时间",
    width: 220,
    sortable: "custom",
    search: {
      el: "date-picker",
      order: 1,
      props: {
        valueFormat: "YYYY-MM-DD"
      }
    }
  },
  { prop: "traceBy", label: "处理人", width: 200 },
  {
    prop: "traceStatus",
    label: "状态",
    width: 120,
    tag: true,
    enum: TraceStatus.getAllEnumValues(),
    search: { el: "select", order: 1 }
  },
  { prop: "operation", label: "操作", width: 240, fixed: "right" }
]);
// 分页列表获取数据
const getTableList = (params: TraceOrigin.ReqTraceOriginParams) => {
  return getTraceOriginList(params);
};

// 删除
const deleteAction = async (ids: number[]) => {
  await useHandleData(deleteTraceOrigin, { articleIds: ids }, `是否删除当前${ids.length}条条文`);
  proTable.value?.getTableList();
};

// 导入
function importAction() {
  importRef.value?.open().then(proTable.value?.getTableList);
}

// 添加
const addAction = async () => {
  dialogRef.value
    ?.open(undefined, { title: "添加条文", formProps: { mode: "add", editable: true, labelWidth: 130 } })
    .then(proTable.value?.getTableList);
};

// 溯源
function traceAction(row: Clause.ClauseInfo) {
  router.push({
    name: DETAIL_PAGE_ROUTE,
    query: {
      id: row.id
    }
  });
}

// 排序
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: Clause.ClauseInfo) => row.traceStatus === TraceStatusEnum.RESOLVE;

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