<template>
  <div class="related-clause">
    <ProTable :tool-button="false" :columns="columns.first" :data="[firstClause || {}]" :pagination="false">
      <!-- 表格 header -->
      <template #tableHeader>
        <yx-title class="mb10">首见条文</yx-title>
      </template>
    </ProTable>
    <el-divider />
    <ProTable
      row-key="id"
      :tool-button="false"
      :columns="columns.related"
      :data="sortRelatedList"
      :pagination="false"
      @sort-change="sortChange"
    >
      <!-- 表格 header -->
      <template #tableHeader>
        <yx-title class="mb10">相关条文</yx-title>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button
          v-auth="['article:first:set']"
          type="primary"
          link
          :icon="Setting"
          @click="settingAction(scope.row)"
          :disabled="disabledButton"
        >
          设置首见条文
        </el-button>
        <el-button
          v-auth="['article:first:update']"
          type="primary"
          link
          :icon="Edit"
          @click="editAction(scope.row)"
          :disabled="disabledButton"
        >
          编辑
        </el-button>
        <el-button
          v-auth="['article:first:delete']"
          type="primary"
          link
          :icon="Delete"
          @click="deleteAction(scope.row)"
          :disabled="disabledButton"
        >
          删除
        </el-button>
      </template>
    </ProTable>
    <ClauseDialog ref="dialogRef" />
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, defineProps, withDefaults } from "vue";
import { useRoute, useRouter, onBeforeRouteUpdate } from "vue-router";
import { Delete, Edit, Setting } from "@element-plus/icons-vue";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps } from "@/components/ProTable/interface";
import { useHandleData } from "@/hooks/useHandleData";
import { Clause } from "@/api/interface";
import { StyleId, AnnoStatusEnum } from "@/enums";
import { logicDeleteClause, getRelateClauseList, relateSetFirst } from "@/api/modules/corpus/first-clause";
import ClauseDialog from "@/components/ClauseFormDialog/index.vue";

// props
const props = withDefaults(defineProps<{ firstClause: Clause.ClauseInfo }>(), {
  firstClause: () => ({}) as Clause.ClauseInfo
});

// hooks
const route = useRoute();
const router = useRouter();

// ref
const dialogRef = ref<null | typeof ClauseDialog>(null);
const sortType = ref<null | "descending" | "ascending">(null);
const relatedList = ref<Clause.ClauseInfo[]>([]);

// computed

// 表格排序后数据 ()
const sortRelatedList = computed<Clause.ClauseInfo[]>(() => {
  const result = [...relatedList.value];

  // 降序
  if (sortType.value === "descending") {
    return result.sort((a, b) => {
      if (typeof a.publicationDate !== "number") {
        return 1;
      }
      if (typeof b.publicationDate !== "number") {
        return -1;
      }
      return b.publicationDate - a.publicationDate;
    });
  } else {
    // 生序
    return result.sort((a, b) => {
      if (typeof a.publicationDate !== "number") {
        return 1;
      }
      if (typeof b.publicationDate !== "number") {
        return -1;
      }
      return a.publicationDate - b.publicationDate;
    });
  }
  return result;
});

// 条文内容、所属疾病、书名、卷篇、作者、朝代、成书年代、体裁、版本信息
const columns = computed<Record<"first" | "related", ColumnProps<Clause.ClauseInfo>[]>>(() => {
  const common: ColumnProps[] = [
    { prop: "bookName", label: "书名" },
    { prop: "chapter", label: "卷篇" },
    { prop: "author", 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 : "--"}`
    }
  ];
  return {
    first: [
      { prop: "firstArticleNo", label: "首见条文编号", render: ({ row }) => `SJ${row.firstArticleNo}` },
      { prop: "articleContent", label: "条文内容" },
      { prop: "diseaseName", label: "所属疾病" },
      ...common,
      { prop: "styleId", label: "体裁", enum: StyleId.getAllEnumValues() },
      { prop: "version", label: "版本信息" }
    ],
    related: [
      { type: "index", label: "序号", width: 80 },
      { prop: "articleContent", label: "条文内容" },
      ...common,
      { prop: "version", label: "版本信息" },
      { prop: "operation", label: "操作", width: 330, fixed: "right" }
    ]
  };
});

// 禁用按钮 (首见条文状态为审核通过/已上传时，所有操作按钮禁用)
const disabledButton = computed(() => props.firstClause.annotationStatus >= AnnoStatusEnum.PASSED);
// function
// 获取相关列表数据
async function getTableList() {
  const res = await getRelateClauseList({ id: Number(route.query.id) });
  relatedList.value = res.data || [];
}
getTableList();

// 设置首见条文见
const settingAction = async (row: Clause.ClauseInfo) => {
  let tipText = `是否设置当前条文为首见条文，手动设置首见条文后，系统将不再根据年份自动替换当前条文!`;
  const { publicationDate } = props.firstClause;
  if (typeof publicationDate === "number" && typeof row.publicationDate === "number" && publicationDate < row.publicationDate) {
    tipText = `当前相关条文的成书年代晚于SJ${row.firstArticleNo}的成书年代，是否替换当前首见条文设置为新首见条文`;
  }
  await useHandleData(relateSetFirst, { id: row.id }, tipText);
  router.replace({ query: { id: row.id } });
};

onBeforeRouteUpdate(to => {
  to.meta.tab = "2";
});
// 编辑
function editAction(row: Clause.ClauseInfo) {
  dialogRef.value?.open(row, { formProps: { editable: true, mode: "edit" } }).then(getTableList);
}

// 删除
const deleteAction = async (row: Clause.ClauseInfo) => {
  await useHandleData(logicDeleteClause, { articleIds: [row.id] }, `是否删除当前条文，删除后该条文将移至【条文回收站】`);
  getTableList();
};

// 排序
function sortChange({ order }: { order: typeof sortType.value }) {
  sortType.value = order;
}
</script>

<style lang="scss" scoped>
.related-clause {
  display: flex;
  flex-direction: column;
  height: 100%;
  :deep(.table-main) {
    &:first-child {
      flex: none;
      height: auto;
    }
  }
}
</style>
