<template>
  <div class="main-box">
    <PageToolbar class="mt1 mb10" />
    <div class="view-box">
      <div class="base-info">
        <ProTable :tool-button="false" :columns="columns.clause" :data="[clauseInfo]" :pagination="false">
          <!-- 表格操作 -->
          <template #operation="scope">
            <el-button type="primary" link :icon="Setting" @click="settingAction(scope.row)"> 设置为首见条文 </el-button>
          </template>
        </ProTable>
      </div>
      <el-divider />
      <div class="table-box">
        <ProTable
          ref="proTable"
          row-key="firstArticleNo"
          :tool-button="false"
          :columns="columns.similarity"
          :request-api="getTableList"
          :init-param="initParam"
          :form-props="{ labelWidth: 120 }"
          @sort-change="sortChange"
        >
          <!-- 表格操作 -->
          <template #operation="scope">
            <el-button type="primary" link :icon="View" @click="viewAction(scope.row)"> 详情 </el-button>
            <el-button type="primary" link :icon="Link" @click="relatedAction(scope.row)"> 关联本条首见条文 </el-button>
          </template>
        </ProTable>
      </div>
    </div>
    <ClauseDialog ref="dialogRef" />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, h } from "vue";
import { useRoute, useRouter } from "vue-router";
import { View, Link, Setting } from "@element-plus/icons-vue";
import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { useHandleData } from "@/hooks/useHandleData";
import { usePageLeave } from "@/hooks/usePageLeave";
import { Clause, TraceOrigin } from "@/api/interface";
import { StyleId } from "@/enums";
import { getDictOptions } from "@/api/modules/common";
import { relativeFirstArticle, getSimilarityListById, getClauseDetail, setFirstClause } from "@/api/modules/corpus/trace-origin";
import ClauseDialog from "@/components/ClauseFormDialog/index.vue";

// hooks
usePageLeave("TraceOrigin");

// ProTable 实例
const proTable = ref<ProTableInstance>();
const dialogRef = ref<null | typeof ClauseDialog>(null);
const clauseInfo = ref({} as Clause.ClauseInfo);
const initParam = reactive({
  sortBy: ""
});
const columns = computed<Record<"clause" | "similarity", ColumnProps<TraceOrigin.ResSimilarityDataList>[]>>(() => {
  const common: ColumnProps<TraceOrigin.ResSimilarityDataList>[] = [
    { prop: "articleContent", label: "条文内容", search: { el: "input", order: 2 } },
    {
      prop: "diseaseId",
      label: "所属疾病",
      render: scope => scope.row.diseaseName || "--",
      enum: () => getDictOptions("disease"),
      fieldNames: { label: "dictLabel", value: "dictCode" },
      search: { el: "select", order: 3, props: { filterable: true } }
    },
    {
      prop: "bookId",
      label: "书名",
      render: scope => scope.row.bookName || "--",
      enum: () => getDictOptions("book"),
      fieldNames: { label: "dictLabel", value: "dictCode" },
      search: { el: "select", order: 4, props: { filterable: true } }
    },
    { prop: "chapter", 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: 5, props: { filterable: true } }
    },
    {
      prop: "publicationDate",
      label: "成书年代",
      sortable: "custom",
      search: { el: "grace-year-input", custom: true, order: 6 },
      render: ({ row }) =>
        row.publicationDate < 0
          ? `公元前${-row.publicationDate}`
          : `${typeof row.publicationDate === "number" ? row.publicationDate : "--"}`
    },
    { prop: "styleId", label: "体裁", enum: StyleId.getAllEnumValues() }
  ];
  // 关闭搜索
  const filterSearch = (options: ColumnProps<TraceOrigin.ResSimilarityDataList>[]) => {
    return options.map(item => ({ ...item, search: undefined }));
  };
  return {
    clause: [...filterSearch(common), { prop: "operation", label: "操作", width: 250, fixed: "right" }],
    // 相似词条列表
    similarity: [
      {
        prop: "firstArticleNo",
        label: "首见条文编号",
        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;
              }
            }
          }
        },
        render: ({ row }) => `SJ${row.firstArticleNo}`
      },
      ...common,
      {
        prop: "similarityValue",
        label: "相似度",
        search: {
          el: "input-number-range",
          defaultValue: [30],
          custom: true,
          order: 7
        },
        sortable: "custom",
        render: ({ row }) => (row.similarityValue || row.similarityValue === 0 ? `${row.similarityValue}%` : "--")
      },
      { prop: "operation", label: "操作", width: 250, fixed: "right" }
    ]
  };
});
// hooks
const route = useRoute();
const router = useRouter();

async function loadDetail() {
  const res = await getClauseDetail({ id: Number(route.query.id) });
  clauseInfo.value = res.data || ({} as Clause.ClauseInfo);
}
loadDetail();

// 获取列表数据
async function getTableList(params: any) {
  const searchParams: TraceOrigin.ReqSimilarityParams = { ...params, id: Number(route.query.id) };
  if (searchParams.similarityValue) {
    const [begin, end] = searchParams.similarityValue;
    begin && (searchParams.similarityMin = begin);
    end && (searchParams.similarityMax = end);
    delete searchParams.similarityValue;
  }

  return getSimilarityListById(searchParams);
}

// 设置首见条文见
const settingAction = async (row: Clause.ClauseInfo) => {
  await useHandleData(setFirstClause, { id: row.id }, `设置当前条文为首见条文`);
  router.back();
};

// 关联本条首见条文
const relatedAction = async (row: Clause.ClauseInfo) => {
  const params = {
    id: clauseInfo.value.id,
    firstArticleId: row.id
  };
  console.log("时间1", row.publicationDate);
  console.log("时间2", clauseInfo.value.publicationDate);

  if (
    row.publicationDate > clauseInfo.value.publicationDate &&
    row.publicationDate !== null &&
    clauseInfo.value.publicationDate !== null
  ) {
    await useHandleData(
      relativeFirstArticle,
      params,
      `当前待溯源条文的成书年代早于SJ${row.firstArticleNo}的成书年代，是否关联当前首见条文`
    );
  } else {
    await useHandleData(relativeFirstArticle, params, `设置当前条文与编号为SJ${row.firstArticleNo}的首见条文进行关联`);
  }
  router.back();
};

// 详情
function viewAction(row: Clause.ClauseInfo) {
  dialogRef.value?.open(row, { title: "详情", formProps: { mode: "view", editable: false } });
}

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

<style lang="scss" scoped>
.main-box {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 0;
  padding-bottom: 10px;
  .view-box {
    display: flex;
    flex: 1;
    flex-direction: column;
    padding-right: 10px;
    padding-left: 10px;
    .table-box {
      width: 100%;
    }
    .base-info :deep(.table-main) {
      flex: none;
      height: auto;
    }
  }
}
</style>
