<template>
  <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="true"
      @sort-change="sortChange"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="{ isSelected, selectedListIds }">
        <template v-if="!isAudit">
          <el-button
            v-auth="['article:audit:process']"
            type="primary"
            :disabled="!isSelected"
            :icon="Check"
            @click="bacthAuditAction(selectedListIds)"
          >
            批量审核
          </el-button>
          <el-button
            v-auth="['article:audit:process']"
            type="primary"
            :disabled="!isSelected"
            :icon="Close"
            @click="batchReturnAction(selectedListIds)"
            plain
          >
            批量退回
          </el-button>
        </template>
        <el-button
          v-else
          v-auth="['article:audit:upload']"
          type="primary"
          :disabled="!isSelected"
          :icon="Finished"
          @click="uploadAction(selectedListIds, true)"
        >
          批量上传
        </el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button v-if="!isAudit" v-auth="['article:audit:process']" type="primary" link @click="auditAction(scope.row)">
          审核
        </el-button>
        <template v-else>
          <el-button v-auth="['article:audit:process']" type="primary" link @click="auditAction(scope.row)"> 重新审核 </el-button>
          <el-button v-auth="['article:audit:upload']" type="primary" link @click="uploadAction([scope.row.id])">
            上传
          </el-button>
        </template>
      </template>
    </ProTable>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, defineProps, defineExpose } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { Check, Close, Finished } from "@element-plus/icons-vue";
import { AnnoAudit, Clause } from "@/api/interface";
import { useHandleData } from "@/hooks/useHandleData";
import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { StyleId, AnnoStatusEnum } from "@/enums";
import { getAnnoAuditList, auditProcess, uploadArticel } from "@/api/modules/annotation/audit";
import { getDictOptions, getAllUserList } from "@/api/modules/common";

//props
const props = defineProps({
  isAudit: {
    type: Boolean,
    default: () => false
  }
});
// useHooks
const router = useRouter();
// ref
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
  sortBy: ""
});
// 表格配置项
const columns = reactive<ColumnProps<Clause.ClauseInfo>[]>([
  { type: "selection", width: 50 },
  {
    prop: "firstArticleNo",
    label: "首见条文编号",
    render: ({ row }) => `SJ${row.firstArticleNo}`
  },
  { prop: "articleContent", label: "条文内容" },
  {
    prop: "diseaseId",
    label: "所属疾病",
    render: scope => scope.row.diseaseName || "--",
    enum: () => getDictOptions("disease"),
    fieldNames: { label: "dictLabel", value: "dictCode" },
    search: { el: "select", order: 1, props: { filterable: true } }
  },
  {
    prop: "bookId",
    label: "书名",
    render: scope => scope.row.bookName || "--",
    enum: () => getDictOptions("book"),
    fieldNames: { label: "dictLabel", value: "dictCode" },
    search: { el: "select", order: 2, props: { filterable: true } }
  },
  { prop: "chapter", label: "卷篇" },
  { prop: "styleId", label: "体裁", enum: StyleId.getAllEnumValues(), search: { el: "select", order: 3 } },
  ...(props.isAudit
    ? ([
        {
          prop: "reviewedBy",
          label: "审核员",
          enum: () => getAllUserList(),
          fieldNames: { label: "nickName", value: "userId" },
          search: { el: "select", order: 4, props: { filterable: true } }
        },
        { prop: "reviewedTime", label: "审核时间", sortable: "custom" }
      ] as any)
    : ([
        {
          prop: "annotationBy",
          label: "标注员",
          enum: () => getAllUserList(),
          fieldNames: { label: "nickName", value: "userId" },
          search: { el: "select", order: 4, props: { filterable: true } }
        },
        { prop: "annotationSubmitTime", label: "提交时间", sortable: "custom" }
      ] as any)),
  { prop: "operation", label: "操作", width: 240, fixed: "right" }
]);
// 分页列表获取数据
const getTableList = (params: AnnoAudit.ReqAnnoAuditParams) => {
  return getAnnoAuditList({ ...params, allocationType: props.isAudit ? 4 : 3 });
};

// 上传操作
const uploadAction = async (ids: string[] | number[], isBatch = false) => {
  await useHandleData(
    uploadArticel,
    { articleIds: ids },
    `是否上传当前${ids.length}条数据，上传后条文将不可修改条文内容和标注信息！`
  );
  proTable.value?.getTableList();
  isBatch && proTable.value?.clearSelection();
};

// 审核操作/重新审核操作
const auditAction = async (params: Clause.ClauseInfo) => {
  router.push({ name: "AnnoAuditDetail", query: { id: params.id } });
};

// 批量审核操作
const bacthAuditAction = async (ids: string[] | number[]) => {
  await useHandleData(
    auditProcess,
    { articleIds: ids, auditStatus: AnnoStatusEnum.PASSED, refuseReason: "" },
    `批量审核默认为【审核通过】结果，确认当前${ids.length}条条文标注结果合格！`
  );
  proTable.value?.getTableList();
  proTable.value?.clearSelection();
};

// 退回操作 -- 与产品确认过，不需要二次确认
const batchReturnAction = async (ids: string[] | number[]) => {
  await auditProcess({ articleIds: ids as number[], auditStatus: AnnoStatusEnum.REJECTED, refuseReason: "" });
  ElMessage.success("操作成功");
  proTable.value?.getTableList();
  proTable.value?.clearSelection();
};

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

defineExpose({
  getTableList() {
    proTable.value?.getTableList();
  }
});
</script>
<style lang="scss" scoped>
.table-box {
  width: 100%;
}
</style>
