<template>
  <div class="main">
    <el-card v-if="queryInfo" shadow="never" class="mt-2">
      <el-descriptions title="查询基本信息" border :column="4">
        <el-descriptions-item align="center" label="操作时间">{{
          dayjs(queryInfo.operation_time).format("YYYY-MM-DD HH:mm:ss")
        }}</el-descriptions-item>
        <el-descriptions-item align="center" label="耗时"
          >{{ queryInfo.cost_time.toFixed(2) }} ms</el-descriptions-item
        >
        <el-descriptions-item align="center" label="查询统计">{{
          queryInfo.query_count
        }}</el-descriptions-item>
        <el-descriptions-item align="center" label="结果统计">{{
          queryInfo.result_count
        }}</el-descriptions-item>
      </el-descriptions>
    </el-card>
    <PureTableBar title="查询结果" :columns="columns">
      <template #buttons>
        <el-button type="primary" :icon="useRenderIcon(AddFill)">
          {{ t("buttons:Export") }}
        </el-button>
      </template>
      <template v-slot="{ size, dynamicColumns }">
        <div
          v-if="selectedNum > 0"
          v-motion-fade
          class="bg-[var(--el-fill-color-light)] w-full h-[46px] mb-2 pl-4 flex items-center"
        >
          <div class="flex-auto">
            <span
              style="font-size: var(--el-font-size-base)"
              class="text-[rgba(42,46,54,0.5)] dark:text-[rgba(220,220,242,0.5)]"
            >
              已选 {{ selectedNum }} 项
            </span>
            <el-button type="primary" text @click="onSelectionCancel">
              {{ t("buttons:Deselect") }}
            </el-button>
          </div>
          <el-popconfirm title="是否确认删除?">
            <template #reference>
              <el-button type="danger" text class="mr-1">
                {{ t("buttons:DeleteInBatches") }}
              </el-button>
            </template>
          </el-popconfirm>
        </div>
        <pure-table
          ref="tableRef"
          row-key="id"
          adaptive
          border
          stripe
          :adaptiveConfig="{ offsetBottom: 45 }"
          align-whole="center"
          table-layout="auto"
          :loading="loading"
          :data="dataList"
          :columns="dynamicColumns"
          :pagination="pagination"
          :paginationSmall="size === 'small' ? true : false"
          :header-cell-style="{
            background: 'var(--el-fill-color-light)',
            color: 'var(--el-text-color-primary)'
          }"
          @selection-change="handleSelectionChange"
        >
          <template #operation="{ row }">
            <el-button
              class="reset-margin"
              link
              type="primary"
              :size="size"
              :icon="useRenderIcon(EditPen)"
              @click="handleDetail(row)"
            >
              {{ t("buttons:Details") }}
            </el-button>
          </template>
        </pure-table>
      </template>
    </PureTableBar>
    <el-drawer v-model="drawerStatus" title="查询详情" :size="`50%`" show-close>
      <el-collapse v-model="activeCollapse" :accordion="false">
        <!-- 基本信息 -->
        <el-collapse-item title="基本信息" name="baseInfo">
          <el-descriptions border>
            <el-descriptions-item align="center" label="查询文本">{{
              rowInfo.query_text
            }}</el-descriptions-item>
          </el-descriptions>
        </el-collapse-item>
        <!-- 查询结果 -->
        <el-collapse-item
          v-for="(item, index) in rowInfo.result_text"
          :key="item.id"
          :title="`匹配结果${index + 1}`"
          :name="`result${index + 1}`"
        >
          <el-descriptions border :column="1">
            <el-descriptions-item align="center" label="编码ID">{{
              item.id
            }}</el-descriptions-item>
            <el-descriptions-item align="center" label="海关编码">{{
              item.code
            }}</el-descriptions-item>
            <el-descriptions-item align="center" label="编码描述">{{
              item.description
            }}</el-descriptions-item>
            <el-descriptions-item align="center" label="匹配率">{{
              item.match_rate ? `${item.match_rate}%` : "0%"
            }}</el-descriptions-item>
          </el-descriptions>
        </el-collapse-item>
      </el-collapse>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "QueryCodedetails"
});
import { ref, reactive, onMounted, h } from "vue";
import { useRouter, useRoute } from "vue-router";
import dayjs from "dayjs";
import { useI18n } from "vue-i18n";
import { isEmpty, isString } from "@pureadmin/utils";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
// import { useMultiTagsStoreHook } from "@/store/modules/multiTags";
import EditPen from "@iconify-icons/ep/edit-pen";
import Refresh from "@iconify-icons/ep/refresh";
import AddFill from "@iconify-icons/ri/add-circle-line";
// import { $t } from "@/plugins/i18n";
import type {
  QueryCodeLogInfo,
  QueryResult,
  QueryResultItem
} from "types/code";
import { getCodeLogInfoAPI } from "@/api/code";
import { PaginationProps } from "@pureadmin/table";
const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const getParameter = isEmpty(route.params) ? route.query : route.params;
console.log(getParameter);
// /**初始化加载页面 */
// function init() {
//   Object.keys(getParameter).forEach(param => {
//     if (!isString(getParameter[param])) {
//       getParameter[param] = getParameter[param].toString();
//     } else {
//       getParameter["detailsId"] = "";
//     }
//   });
//   useMultiTagsStoreHook().handleTags("push", {
//     path: "/code/log/details/:detailsId",
//     name: "QueryCodedetails",
//     params: getParameter,
//     meta: {
//       title: $t("menus:QueryCodedetails")
//     },
//     dynamicLevel: 1
//   });
//   router.push({
//     name: "QueryCodedetails",
//     params: getParameter
//   });
// }
// init();
const activeCollapse = ref(["baseInfo"]);
/**
 * 查询结果
 */
const queryInfo = ref<QueryCodeLogInfo>();
/**
 * 数据列表
 */
const dataList = ref<QueryResult[]>([]);
const tableRef = ref();
/**抽屉状态 */
const drawerStatus = ref<boolean>(false);
const loading = ref(true);
const selectedNum = ref(0);
const pagination = reactive<PaginationProps>({
  total: 0,
  pageSize: 10,
  currentPage: 1,
  background: true,
  pageSizes: [10, 20, 30, 40, 50]
});
/**列表值 */
const rowInfo = reactive<QueryResult>({
  query_text: "",
  status: 0,
  id: "",
  result_text: []
});
/**
 * 表格列设置
 */
const columns: TableColumnList = [
  {
    label: "勾选列", // 如果需要表格多选，此处label必须设置
    type: "selection",
    fixed: "left",
    reserveSelection: true // 数据刷新后保留选项
  },
  {
    label: "查询ID",
    prop: "id"
  },
  {
    label: "查询文本",
    prop: "query_text"
  },
  {
    label: "操作",
    fixed: "right",
    width: 250,
    slot: "operation"
  }
];
/**获取查询结果 */
const getQueryInfo = async () => {
  const res = await getCodeLogInfoAPI(getParameter.detailsId as string);
  if (res.success) {
    queryInfo.value = res.data;
    dataList.value = JSON.parse(
      res.data.response_result.replace(/'/g, '"').replace(/None/g, "null")
    );
    loading.value = false;
  }
};
const handleDetail = (row: QueryResultItem) => {
  drawerStatus.value = true;
  Object.assign(rowInfo, row);
};
/** 当CheckBox选择项发生变化时会触发该事件 */
const handleSelectionChange = async (val: any) => {
  selectedNum.value = val.length;
  // 重置表格高度
  tableRef.value.setAdaptive();
};

/** 取消选择 */
const onSelectionCancel = async () => {
  selectedNum.value = 0;
  // 用于多选表格，清空用户的选择
  tableRef.value.getTableRef().clearSelection();
};
onMounted(async () => {
  await getQueryInfo();
});
</script>
